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) {
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 if (arguments.length < 2)
72 function siteFilter(uri)
73 let (match = array.nth(siteFilter.filters, function (f) f(uri), 0))
74 match ? match.result : default_;
76 return update(siteFilter, {
77 toString: function () this.filters.join(","),
79 toJSONXML: function (modules) let (uri = modules && modules.buffer.uri)
80 template.map(this.filters,
81 function (f) ["span", { highlight: uri && f(uri) ? "Filter" : "" },
82 "toJSONXML" in f ? f.toJSONXML() : String(f)],
85 filters: Option.parse.sitelist(patterns)
89 defaultFilter: Class.Memoize(function () this.compileFilter(["*"]))
92 var Contexts = Module("contexts", {
94 this.pluginModules = {};
97 cleanup: function () {
98 for each (let module in this.pluginModules)
99 util.trapErrors("unload", module);
101 this.pluginModules = {};
104 Local: function Local(dactyl, modules, window) ({
106 const contexts = this;
107 this.modules = modules;
109 Object.defineProperty(modules.plugins, "contexts", Const({}));
113 this.groupsProto = {};
117 this.builtin = this.addGroup("builtin", "Builtin items");
118 this.user = this.addGroup("user", "User-defined items", null, true);
119 this.builtinGroups = [this.builtin, this.user];
120 this.builtin.modifiable = false;
122 this.GroupFlag = Class("GroupFlag", CommandOption, {
123 init: function (name) {
126 this.type = ArgType("group", function (group) {
127 return isString(group) ? contexts.getGroup(group, name)
132 get toStringParams() [this.name],
134 names: ["-group", "-g"],
136 description: "Group to which to add",
138 get default() (contexts.context && contexts.context.group || contexts.user)[this.name],
140 completer: function (context) modules.completion.group(context)
143 memoize(modules, "userContext", function () contexts.Context(modules.io.getRCFile("~", true), contexts.user, [modules, true]));
144 memoize(modules, "_userContext", function () contexts.Context(modules.io.getRCFile("~", true), contexts.user, [modules.userContext]));
147 cleanup: function () {
148 for each (let hive in this.groupList.slice())
149 util.trapErrors("cleanup", hive, "shutdown");
152 destroy: function () {
153 for each (let hive in values(this.groupList.slice()))
154 util.trapErrors("destroy", hive, "shutdown");
156 for (let [name, plugin] in iter(this.modules.plugins.contexts))
157 if (plugin && "onUnload" in plugin && callable(plugin.onUnload))
158 util.trapErrors("onUnload", plugin);
162 "browser.locationChange": function (webProgress, request, uri) {
167 Group: Class("Group", Group, { modules: modules, get hiveMap() modules.contexts.hives }),
169 Hives: Class("Hives", Class.Property, {
170 init: function init(name, constructor) {
171 const { contexts } = modules;
177 get: () => array(contexts.groups[this.name])
180 this.Hive = constructor;
182 memoize(contexts.Group.prototype, name, function () {
183 let group = constructor(this);
184 this.hives.push(group);
189 memoize(contexts.hives, name,
190 function () Object.create(Object.create(contexts.hiveProto,
191 { _hive: { value: name } })));
193 memoize(contexts.groupsProto, name,
194 function () [group[name] for (group in values(this.groups)) if (Set.has(group, name))]);
197 get toStringParams() [this.name, this.Hive]
201 Context: function Context(file, group, args) {
202 const { contexts, io, newContext, plugins, userContext } = this.modules;
204 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
205 function (dir) dir.contains(file, true),
207 let isRuntime = array.nth(io.getRuntimeDirectories(""),
208 function (dir) dir.contains(file, true),
211 let name = isPlugin ? file.getRelativeDescriptor(isPlugin).replace(File.PATH_SEP, "-")
213 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
215 let contextPath = file.path;
216 let self = Set.has(plugins, contextPath) && plugins.contexts[contextPath];
218 if (!self && isPlugin && false)
219 self = Set.has(plugins, id) && plugins[id];
222 if (Set.has(self, "onUnload"))
223 util.trapErrors("onUnload", self);
226 let params = Array.slice(args || [userContext]);
227 params[2] = params[2] || File(file).URI.spec;
229 self = args && !isArray(args) ? args : newContext.apply(null, params);
233 PATH: Const(file.path),
235 CONTEXT: Const(self),
237 set isGlobalModule(val) {
243 unload: Const(function unload() {
244 if (plugins[this.NAME] === this || plugins[this.PATH] === this)
246 util.trapErrors("onUnload", this);
248 if (plugins[this.NAME] === this)
249 delete plugins[this.NAME];
251 if (plugins[this.PATH] === this)
252 delete plugins[this.PATH];
254 if (plugins.contexts[contextPath] === this)
255 delete plugins.contexts[contextPath];
257 if (!this.GROUP.builtin)
258 contexts.removeGroup(this.GROUP);
262 if (group !== this.user)
263 Class.replaceProperty(plugins, file.path, self);
265 // This belongs elsewhere
267 Object.defineProperty(plugins, self.NAME, {
270 get: function () self,
271 set: function (val) {
272 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
277 let path = isRuntime ? file.getRelativeDescriptor(isRuntime) : file.path;
278 let name = isRuntime ? path.replace(/^(plugin|color)s([\\\/])/, "$1$2") : "script-" + path;
281 group = this.addGroup(commands.nameRegexp
282 .iterate(name.replace(/\.[^.]*$/, ""))
283 .join("-").replace(/--+/g, "-"),
284 _("context.scriptGroup", file.path),
287 Class.replaceProperty(self, "GROUP", group);
288 Class.replaceProperty(self, "group", group);
290 return plugins.contexts[contextPath] = self;
293 Script: function Script(file, group) {
294 return this.Context(file, group, [this.modules.userContext, true]);
297 Module: function Module(uri, isPlugin) {
298 const { io, plugins } = this.modules;
300 let canonical = uri.spec;
301 if (uri.scheme == "resource")
302 canonical = services["resource:"].resolveURI(uri);
304 if (uri instanceof Ci.nsIFileURL)
305 var file = File(uri.file);
307 let isPlugin = array.nth(io.getRuntimeDirectories("plugins"),
308 function (dir) dir.contains(file, true),
311 let name = isPlugin && file && file.getRelativeDescriptor(isPlugin)
312 .replace(File.PATH_SEP, "-");
313 let id = util.camelCase(name.replace(/\.[^.]*$/, ""));
315 let self = Set.has(this.pluginModules, canonical) && this.pluginModules[canonical];
318 self = Object.create(jsmodules);
323 PATH: Const(file && file.path),
325 CONTEXT: Const(self),
327 get isGlobalModule() true,
328 set isGlobalModule(val) {
329 util.assert(val, "Loading non-global module as global",
333 unload: Const(function unload() {
334 if (contexts.pluginModules[canonical] == this) {
336 util.trapErrors("onUnload", this);
338 delete contexts.pluginModules[canonical];
341 for each (let { plugins } in overlay.modules)
342 if (plugins[this.NAME] == this)
343 delete plugins[this.name];
347 JSMLoader.loadSubScript(uri.spec, self, File.defaultEncoding);
348 this.pluginModules[canonical] = self;
351 // This belongs elsewhere
353 Object.defineProperty(plugins, self.NAME, {
356 get: function () self,
357 set: function (val) {
358 util.dactyl(val).reportError(FailedAssertion(_("plugin.notReplacingContext", self.NAME), 3, false), true);
368 * Returns a frame object describing the currently executing
369 * command, if applicable, otherwise returns the passed frame.
371 * @param {nsIStackFrame} frame
373 getCaller: function getCaller(frame) {
374 if (this.context && this.context.file)
377 filename: this.context.file[0] == "[" ? this.context.file
378 : File(this.context.file).URI.spec,
379 lineNumber: this.context.line
384 groups: Class.Memoize(function () this.matchingGroups()),
386 allGroups: Class.Memoize(function () Object.create(this.groupsProto, {
387 groups: { value: this.initializedGroups() }
390 matchingGroups: function (uri) Object.create(this.groupsProto, {
391 groups: { value: this.activeGroups(uri) }
394 activeGroups: function (uri) {
395 if (uri instanceof Ci.nsIDOMDocument)
396 var [doc, uri] = [uri, uri.documentURIObject || util.newURI(uri.documentURI)];
399 var { uri, doc } = this.modules.buffer;
401 return this.initializedGroups().filter(function (g) {
402 let res = uri && g.filter(uri, doc);
404 g.lastDocument = res && doc;
409 flush: function flush() {
411 delete this.allGroups;
414 initializedGroups: function (hive)
415 let (need = hive ? [hive] : Object.keys(this.hives))
416 this.groupList.filter(function (group) need.some(Set.has(group))),
418 addGroup: function addGroup(name, description, filter, persist, replace) {
419 let group = this.getGroup(name);
424 group = this.Group(name, description, filter, persist);
425 this.groupList.unshift(group);
426 this.groupMap[name] = group;
427 this.hiveProto.__defineGetter__(name, function () group[this._hive]);
431 util.trapErrors("cleanup", group);
434 group.description = description;
436 group.filter = filter;
437 group.persist = persist;
444 removeGroup: function removeGroup(name) {
445 if (isObject(name)) {
446 if (this.groupList.indexOf(name) === -1)
451 let group = this.getGroup(name);
453 util.assert(!group || !group.builtin, _("group.cantRemoveBuiltin"));
457 this.groupList.splice(this.groupList.indexOf(group), 1);
458 util.trapErrors("destroy", group);
461 if (this.context && this.context.group === group)
462 this.context.group = null;
464 delete this.groupMap[name];
465 delete this.hiveProto[name];
470 getGroup: function getGroup(name, hive) {
471 if (name === "default")
472 var group = this.context && this.context.context && this.context.context.GROUP;
473 else if (Set.has(this.groupMap, name))
474 group = this.groupMap[name];
481 getDocs: function getDocs(context) {
483 if (isinstance(context, ["Sandbox"])) {
484 let info = "INFO" in context && Cu.evalInSandbox("this.INFO instanceof XML ? INFO.toXMLString() : this.INFO", context);
485 return /^</.test(info) ? XML(info) : info;
487 if (DOM.isJSONXML(context.INFO))
489 if (typeof context.INFO == "xml" && config.haveGecko(null, "14.*"))
496 bindMacro: function (args, default_, params) {
497 const { dactyl, events, modules } = this.modules;
499 function Proxy(obj, key) Class.Property({
502 get: function Proxy_get() process(obj[key]),
503 set: function Proxy_set(val) obj[key] = val
506 let process = util.identity;
508 if (callable(params))
509 var makeParams = function makeParams(self, args)
510 let (obj = params.apply(self, args))
511 iter.toObject([k, Proxy(obj, k)] for (k in properties(obj)));
513 makeParams = function makeParams(self, args)
514 iter.toObject([name, process(args[i])]
515 for ([i, name] in Iterator(params)));
517 let rhs = args.literalArg;
518 let type = ["-builtin", "-ex", "-javascript", "-keys"].reduce(function (a, b) args[b] ? b : a, default_);
525 let silent = args["-silent"];
526 rhs = DOM.Event.canonicalKeys(rhs, true);
527 var action = function action() {
528 events.feedkeys(action.macro(makeParams(this, arguments)),
531 action.macro = util.compileMacro(rhs, true);
535 action = function action() modules.commands
536 .execute(action.macro, makeParams(this, arguments),
537 false, null, action.context);
538 action.macro = util.compileMacro(rhs, true);
539 action.context = this.context && update({}, this.context);
543 if (callable(params))
544 action = dactyl.userEval("(function action() { with (action.makeParams(this, arguments)) {" + args.literalArg + "} })");
546 action = dactyl.userFunc.apply(dactyl, params.concat(args.literalArg));
547 process = function (param) isObject(param) && param.valueOf ? param.valueOf() : param;
548 action.params = params;
549 action.makeParams = makeParams;
553 action.toString = function toString() (type === default_ ? "" : type + " ") + rhs;
558 withContext: function withContext(defaults, callback, self)
559 this.withSavedValues(["context"], function () {
560 this.context = defaults && update({}, defaults);
561 return callback.call(self, this.context);
564 Hive: Class("Hive", {
565 init: function init(group) {
569 cleanup: function cleanup() {},
570 destroy: function destroy() {},
572 get modifiable() this.group.modifiable,
574 get argsExtra() this.group.argsExtra,
575 get makeArgs() this.group.makeArgs,
576 get builtin() this.group.builtin,
578 get name() this.group.name,
579 set name(val) this.group.name = val,
581 get description() this.group.description,
582 set description(val) this.group.description = val,
584 get filter() this.group.filter,
585 set filter(val) this.group.filter = val,
587 get persist() this.group.persist,
588 set persist(val) this.group.persist = val,
590 prefix: Class.Memoize(function () this.name === "builtin" ? "" : this.name + ":"),
592 get toStringParams() [this.name]
595 commands: function initCommands(dactyl, modules, window) {
596 const { commands, contexts } = modules;
598 commands.add(["gr[oup]"],
599 "Create or select a group",
601 if (args.length > 0) {
602 var name = Option.dequote(args[0]);
603 util.assert(name !== "builtin", _("group.cantModifyBuiltin"));
604 util.assert(commands.validName.test(name), _("group.invalidName", name));
606 var group = contexts.getGroup(name);
609 var group = args.context && args.context.group;
611 return void modules.completion.listCompleter("group", "", null, null);
613 util.assert(group || name, _("group.noCurrent"));
615 let filter = Group.compileFilter(args["-locations"]);
616 if (!group || args.bang)
617 group = contexts.addGroup(name, args["-description"], filter, !args["-nopersist"], args.bang);
618 else if (!group.builtin) {
619 if (args.has("-locations"))
620 group.filter = filter;
621 if (args.has("-description"))
622 group.description = args["-description"];
623 if (args.has("-nopersist"))
624 group.persist = !args["-nopersist"];
627 if (!group.builtin && args.has("-args")) {
628 group.argsExtra = contexts.bindMacro({ literalArg: "return " + args["-args"] },
629 "-javascript", util.identity);
630 group.args = args["-args"];
634 args.context.group = group;
635 if (args.context.context) {
636 args.context.context.group = group;
638 let parent = args.context.context.GROUP;
639 if (parent && parent != group) {
640 group.parent = parent;
641 if (!~parent.children.indexOf(group))
642 parent.children.push(group);
647 util.assert(!group.builtin ||
648 !["-description", "-locations", "-nopersist"]
649 .some(Set.has(args.explicitOpts)),
650 _("group.cantModifyBuiltin"));
655 completer: function (context, args) {
656 if (args.length == 1)
657 modules.completion.group(context);
662 names: ["-args", "-a"],
663 description: "JavaScript Object which augments the arguments passed to commands, mappings, and autocommands",
664 type: CommandOption.STRING
667 names: ["-description", "-desc", "-d"],
668 description: "A description of this group",
669 default: "User-defined group",
670 type: CommandOption.STRING
673 names: ["-locations", "-locs", "-loc", "-l"],
674 description: "The URLs for which this group should be active",
676 type: CommandOption.LIST
679 names: ["-nopersist", "-n"],
680 description: "Do not save this group to an auto-generated RC file"
684 serialize: function () [
688 options: iter([v, typeof group[k] == "boolean" ? null : group[k]]
689 // FIXME: this map is expressed multiple times
690 for ([k, v] in Iterator({
692 description: "-description",
695 if (group[k])).toObject(),
696 arguments: [group.name],
699 for (group in values(contexts.initializedGroups()))
700 if (!group.builtin && group.persist)
701 ].concat([{ command: this.name, arguments: ["user"] }])
704 commands.add(["delg[roup]"],
707 util.assert(args.bang ^ !!args[0], _("error.argumentOrBang"));
710 contexts.groupList = contexts.groupList.filter(function (g) g.builtin);
712 util.assert(contexts.getGroup(args[0]), _("group.noSuch", args[0]));
713 contexts.removeGroup(args[0]);
719 completer: function (context, args) {
722 context.filters.push(function ({ item }) !item.builtin);
723 modules.completion.group(context);
727 commands.add(["fini[sh]"],
728 "Stop sourcing a script file",
730 util.assert(args.context, _("command.finish.illegal"));
731 args.context.finished = true;
735 function checkStack(cmd) {
736 util.assert(contexts.context && contexts.context.stack &&
737 contexts.context.stack[cmd] && contexts.context.stack[cmd].length,
738 _("command.conditional.illegal"));
742 return contexts.context.stack[cmd].pop();
744 function push(cmd, value) {
745 util.assert(contexts.context, _("command.conditional.illegal"));
746 if (arguments.length < 2)
747 value = contexts.context.noExecute;
748 contexts.context.stack = contexts.context.stack || {};
749 contexts.context.stack[cmd] = (contexts.context.stack[cmd] || []).concat([value]);
753 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
754 function (args) { args.context.noExecute = !dactyl.userEval(args[0]); },
756 always: function (args) { push("if"); },
760 commands.add(["elsei[f]", "elif"],
761 "Execute commands until the next :elseif, :else, or :endif only if the argument returns true",
764 always: function (args) {
766 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
767 !args.context.noExecute || !dactyl.userEval(args[0]);
772 commands.add(["el[se]"],
773 "Execute commands until the next :endif only if the previous conditionals were not executed",
776 always: function (args) {
778 args.context.noExecute = args.context.stack.if.slice(-1)[0] ||
779 !args.context.noExecute;
783 commands.add(["en[dif]", "fi"],
784 "End a string of :if/:elseif/:else conditionals",
787 always: function (args) { args.context.noExecute = pop("if"); },
791 completion: function initCompletion(dactyl, modules, window) {
792 const { completion, contexts } = modules;
794 completion.group = function group(context, active) {
795 context.title = ["Group"];
796 let uri = modules.buffer.uri;
798 active: function (group) group.filter(uri),
800 description: function (g) ["", g.filter.toJSONXML ? g.filter.toJSONXML(modules).concat("\u00a0") : "", g.description || ""]
802 context.completions = (active === undefined ? contexts.groupList : contexts.initializedGroups(active))
805 iter({ Active: true, Inactive: false }).forEach(function ([name, active]) {
806 context.split(name, null, function (context) {
807 context.title[0] = name + " Groups";
808 context.filters.push(function ({ item }) !!item.filter(modules.buffer.uri) == active);
817 // catch(e){ if (!e.stack) e = Error(e); dump(e.fileName+":"+e.lineNumber+": "+e+"\n" + e.stack); }
819 // vim: set fdm=marker sw=4 sts=4 ts=8 et ft=javascript: