1
0
mirror of https://github.com/gryf/pentadactyl-pm.git synced 2025-12-22 12:17:58 +01:00

Import (and augment) my cookies plugin per Doug's suggestion, and improve dactyl.generateHelp (and :yank).

This commit is contained in:
Kris Maglione
2010-10-15 00:30:03 -04:00
parent bea1c20858
commit a3799d3d05
10 changed files with 348 additions and 62 deletions

View File

@@ -1571,8 +1571,6 @@ const CommandLine = Module("commandline", {
if (typeof arg === "object") if (typeof arg === "object")
arg = util.objectToString(arg, useColor); arg = util.objectToString(arg, useColor);
else if (typeof arg === "string" && /\n/.test(arg))
arg = <span highlight="CmdOutput">{arg}</span>;
else else
arg = String(arg); arg = String(arg);
@@ -1983,7 +1981,8 @@ const ItemList = Class("ItemList", {
this._fill(newOffset); this._fill(newOffset);
if (index >= 0) { if (index >= 0) {
this._getCompletion(index).setAttribute("selected", "true"); this._getCompletion(index).setAttribute("selected", "true");
util.scrollIntoView(this._getCompletion(index)); if (this._container.height != 0)
util.scrollIntoView(this._getCompletion(index));
} }
//if (index == 0) //if (index == 0)

View File

@@ -733,8 +733,11 @@ const Completion = Module("completion", {
let context = CompletionContext(filter); let context = CompletionContext(filter);
context.maxItems = maxItems; context.maxItems = maxItems;
let res = context.fork.apply(context, ["run", 0, this, name].concat(Array.slice(arguments, 3))); let res = context.fork.apply(context, ["run", 0, this, name].concat(Array.slice(arguments, 3)));
if (res) // FIXME if (res) {
return { items: res.map(function (i) ({ item: i })) }; if (Components.stack.caller.name === "runCompleter") // FIXME
return { items: res.map(function (i) ({ item: i })) };
context.contexts["/run"].completions = res;
}
context.wait(true); context.wait(true);
return context.allItems; return context.allItems;
}, },

View File

@@ -603,16 +603,27 @@ const Dactyl = Module("dactyl", {
* @param {XMLList} extraHelp Extra help text beyond the description. * @param {XMLList} extraHelp Extra help text beyond the description.
* @returns {string} * @returns {string}
*/ */
generateHelp: function generateHelp(obj, extraHelp) { generateHelp: function generateHelp(obj, extraHelp, str) {
default xml namespace = ""; default xml namespace = "";
let spec = util.identity;
let tag = util.identity; let link, tag, spec;
if (obj instanceof Command) link = tag = spec = util.identity;
let args = null;
if (obj instanceof Command) {
tag = spec = function (cmd) <>:{cmd}</>; tag = spec = function (cmd) <>:{cmd}</>;
else if (obj instanceof Map && obj.count) link = function (cmd) <ex>:{cmd}</ex>
args = obj.parseArgs("", CompletionContext(str || ""));
}
else if (obj instanceof Map && obj.count) {
spec = function (map) <><oa>count</oa>{map}</>; spec = function (map) <><oa>count</oa>{map}</>;
else if (obj instanceof Option) link = function (map) let (res = /^<(.*?)>(.*?)/.exec(map))
res ? <k name={res[1]}>{res[2]}</k> : <k>{map}</k>;
}
else if (obj instanceof Option) {
tag = spec = function (opt) <>'{opt}'</>; tag = spec = function (opt) <>'{opt}'</>;
link = function (opt) <o>{opt}</o>;
}
XML.prettyPrinting = false; XML.prettyPrinting = false;
XML.ignoreWhitespace = false; XML.ignoreWhitespace = false;
@@ -621,7 +632,17 @@ const Dactyl = Module("dactyl", {
let br = <> let br = <>
</>; </>;
if (obj.completer)
var completions = let (br = br + <> </>) <>
<dl>{ br +
template.map(
completion._runCompleter(obj.completer, "", null, args).items,
function (i) <><dt>{i.text}</dt> <dd>{i.description}</dd></>,
br) }
</dl></>;
return <> return <>
<dt>{link(obj.name)}</dt> <dd>{obj.description ? obj.description.replace(/\.$/, "") : ""}</dd>
<item> <item>
<tags>{template.map(obj.names, tag, " ")}</tags> <tags>{template.map(obj.names, tag, " ")}</tags>
<spec>{spec((obj.specs || obj.names)[0])}</spec>{ <spec>{spec((obj.specs || obj.names)[0])}</spec>{
@@ -631,7 +652,8 @@ const Dactyl = Module("dactyl", {
<description>{ <description>{
obj.description ? br+<p>{obj.description.replace(/\.?$/, ".")}</p> : "" }{ obj.description ? br+<p>{obj.description.replace(/\.?$/, ".")}</p> : "" }{
extraHelp ? br+extraHelp : "" }{ extraHelp ? br+extraHelp : "" }{
!(extraHelp || obj.description) ? br+<p>Sorry, no help available.</p> : "" } !(extraHelp || obj.description) ? br+<p>Sorry, no help available.</p> : "" }{
completions ? br + completions : "" }
</description> </description>
</item></>.toXMLString().replace(/^ {12}/gm, ""); </item></>.toXMLString().replace(/^ {12}/gm, "");
}, },

View File

@@ -226,6 +226,7 @@ This file contains a list of all available commands, mappings and options.
<dt><ex>:comclear</ex></dt> <dd>Delete all user-defined commands</dd> <dt><ex>:comclear</ex></dt> <dd>Delete all user-defined commands</dd>
<dt><ex>:command</ex></dt> <dd>List and define commands</dd> <dt><ex>:command</ex></dt> <dd>List and define commands</dd>
<dt><ex>:contexts</ex></dt> <dd>List the completion contexts used during completion of an Ex command</dd> <dt><ex>:contexts</ex></dt> <dd>List the completion contexts used during completion of an Ex command</dd>
<dt><ex>:cookies</ex></dt> <dd>Change cookie permissions for sites</dd>
<dt><ex>:cunabbrev</ex></dt> <dd>Remove an abbreviation in Command-line mode</dd> <dt><ex>:cunabbrev</ex></dt> <dd>Remove an abbreviation in Command-line mode</dd>
<dt><ex>:cunmap</ex></dt> <dd>Remove a mapping in Command-line mode</dd> <dt><ex>:cunmap</ex></dt> <dd>Remove a mapping in Command-line mode</dd>
<dt><ex>:delbmarks</ex></dt> <dd>Delete a bookmark</dd> <dt><ex>:delbmarks</ex></dt> <dd>Delete a bookmark</dd>
@@ -364,6 +365,9 @@ This file contains a list of all available commands, mappings and options.
<dt><o>banghist</o></dt> <dd>Replace occurrences of ! with the previous command when executing external commands</dd> <dt><o>banghist</o></dt> <dd>Replace occurrences of ! with the previous command when executing external commands</dd>
<dt><o>cdpath</o></dt> <dd>List of directories searched when executing <ex>:cd</ex></dd> <dt><o>cdpath</o></dt> <dd>List of directories searched when executing <ex>:cd</ex></dd>
<dt><o>complete</o></dt> <dd>Items which are completed at the <ex>:open</ex> prompts</dd> <dt><o>complete</o></dt> <dd>Items which are completed at the <ex>:open</ex> prompts</dd>
<dt><o>cookieaccept</o></dt> <dd>When to accept cookies</dd>
<dt><o>cookielifetime</o></dt> <dd>The lifetime for which to accept cookies</dd>
<dt><o>cookies</o></dt> <dd>The default mode for newly added cookie permissions</dd>
<dt><o>defsearch</o></dt> <dd>Set the default search engine</dd> <dt><o>defsearch</o></dt> <dd>Set the default search engine</dd>
<dt><o>editor</o></dt> <dd>Set the external text editor</dd> <dt><o>editor</o></dt> <dd>Set the external text editor</dd>
<dt><o>encoding</o></dt> <dd>Changes the character encoding of the current buffer</dd> <dt><o>encoding</o></dt> <dd>Changes the character encoding of the current buffer</dd>

View File

@@ -422,6 +422,52 @@
</description> </description>
</item> </item>
<item>
<tags>'cookieaccept' 'ca'</tags>
<spec>'cookieaccept'</spec>
<type>string</type>
<default>all</default>
<description>
<p>When to accept cookies.</p>
<dl>
<dt>all</dt> <dd>Accept all cookies</dd>
<dt>none</dt> <dd>Accept no cookies</dd>
<dt>samesite</dt> <dd>Accept all non-third-party cookies</dd>
</dl>
</description>
</item>
<item>
<tags>'cl' 'cookielifetime'</tags>
<spec>'cookielifetime'</spec>
<type>string</type>
<default>default</default>
<description>
<p>
The lifetime for which to accept cookies. The available
options are:
</p>
<dl>
<dt>default</dt> <dd>The lifetime requested by the setter</dd>
<dt>prompt</dt> <dd>Always prompt for a lifetime</dd>
<dt>session</dt> <dd>The current session</dd>
<dt><a>days</a></dt> <dd>When a number is given, it is
interpreted as the number of days for which to keep
cookies</dd>
</dl>
</description>
</item>
<item>
<tags>'ck' 'cookies'</tags>
<spec>'cookies' 'ck'</spec>
<type>stringlist</type> <default>session</default>
<description>
<p>The default action for the <ex>:cookies</ex> command.</p>
</description>
</item>
<item> <item>
<tags>'cpt' 'complete'</tags> <tags>'cpt' 'complete'</tags>
<spec>'complete' 'cpt'</spec> <spec>'complete' 'cpt'</spec>

View File

@@ -221,6 +221,38 @@
</description> </description>
</item> </item>
<h3 tag="cookie-settings">Cookie Settings</h3>
<item>
<tags>:cookies :ck</tags>
<spec>:cookies <a>host</a> <oa>action</oa></spec>
<description>
<p>
Manage cookies for <a>host</a>. Additionally, the completion
list will show you information about the cookies and
permissions for the current page.
</p>
<p>Available actions:</p>
<dl>
<dt>unset</dt> <dd>Unset special permissions for <a>host</a></dd>
<dt>allow</dt> <dd>Allow cookies from <a>host</a></dd>
<dt>deny</dt> <dd>Deny cookies from <a>host</a></dd>
<dt>session</dt> <dd>Allow cookies from <a>host</a> for the current session</dd>
<dt>list</dt> <dd>List all cookies for <a>host</a></dd>
<dt>clear</dt> <dd>Clear all cookies for <a>host</a></dd>
<dt>clear-persistent</dt> <dd>Clear all persistent cookies for <a>host</a></dd>
<dt>clear-session</dt> <dd>Clear all session cookies for <a>host</a></dd>
</dl>
<p>
If no <oa>action</oa> is given, the value of <o>cookies</o> is used.
</p>
<example>:map -b c :cookies <k name="A-Tab"/></example>
</description>
</item>
<h2 tag="online-help">Online help</h2> <h2 tag="online-help">Online help</h2>
<item> <item>

View File

@@ -760,28 +760,6 @@ Class.extend = function extend(subclass, superclass, overrides) {
superclass.prototype.constructor = superclass; superclass.prototype.constructor = superclass;
} }
/**
* A base class generator for classes which impliment XPCOM interfaces.
*
* @param {nsIIID|[nsIJSIID]} interfaces The interfaces which the class
* implements.
* @param {Class} superClass A super class. @optional
* @returns {Class}
*/
function XPCOM(interfaces, superClass) {
interfaces = Array.concat(interfaces);
let shim = interfaces.reduce(function (shim, iface) shim.QueryInterface(iface),
Cc["@dactyl.googlecode.com/base/xpc-interface-shim"].createInstance());
let res = Class("XPCOM(" + interfaces + ")", superClass || Class, update(
array([k, v === undefined || callable(v) ? function stub() null : v]
for ([k, v] in Iterator(shim))).toObject(),
{ QueryInterface: XPCOMUtils.generateQI(interfaces) }));
shim = interfaces = null;
return res;
}
/** /**
* Memoizes the value of a class property to the falue returned by * Memoizes the value of a class property to the falue returned by
* the passed function the first time the property is accessed. * the passed function the first time the property is accessed.
@@ -843,6 +821,28 @@ Class.prototype = {
} }
}; };
/**
* A base class generator for classes which impliment XPCOM interfaces.
*
* @param {nsIIID|[nsIJSIID]} interfaces The interfaces which the class
* implements.
* @param {Class} superClass A super class. @optional
* @returns {Class}
*/
function XPCOM(interfaces, superClass) {
interfaces = Array.concat(interfaces);
let shim = interfaces.reduce(function (shim, iface) shim.QueryInterface(iface),
Cc["@dactyl.googlecode.com/base/xpc-interface-shim"].createInstance());
let res = Class("XPCOM(" + interfaces + ")", superClass || Class, update(
array([k, v === undefined || callable(v) ? function stub() null : v]
for ([k, v] in Iterator(shim))).toObject(),
{ QueryInterface: XPCOMUtils.generateQI(interfaces) }));
shim = interfaces = null;
return res;
}
/** /**
* Constructs a mew Module class and instantiates an instance into the current * Constructs a mew Module class and instantiates an instance into the current
* module global object. * module global object.

View File

@@ -32,7 +32,7 @@ Highlight.defaultValue("baseClass", function () /^(\w*)/.exec(this.class)[0]);
Highlight.defaultValue("selector", function () highlight.selector(this.class)); Highlight.defaultValue("selector", function () highlight.selector(this.class));
Highlight.defaultValue("sites", function () Highlight.defaultValue("sites", function ()
this.base ? this.base.sites this.base ? this.base.sites
: ["chrome://dactyl/*", "dactyl:*", "file://*"].concat( : ["chrome://dactyl/*", "dactyl:*", "file://*", "resource://gre-resources/hiddenWindow.html"].concat(
highlight.styleableChrome)); highlight.styleableChrome));
Highlight.defaultValue("style", function () Highlight.defaultValue("style", function ()
styles.addSheet(true, "highlight:" + this.class, this.sites, this.css, this.agent, true)); styles.addSheet(true, "highlight:" + this.class, this.sites, this.css, this.agent, true));

View File

@@ -8,8 +8,6 @@
// TODO: // TODO:
// - fix Sanitize autocommand // - fix Sanitize autocommand
// - add warning for TIMESPAN_EVERYTHING? // - add warning for TIMESPAN_EVERYTHING?
// - respect privacy.clearOnShutdown et al or recommend Leave autocommand?
// - integrate with the Clear Private Data dialog?
// FIXME: // FIXME:
// - finish 1.9.0 support if we're going to support sanitizing in Melodactyl // - finish 1.9.0 support if we're going to support sanitizing in Melodactyl
@@ -304,6 +302,24 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
return errors; return errors;
}) })
}, { }, {
PERMS: {
unset: 0,
allow: 1,
deny: 2,
session: 8,
},
UNPERMS: Class.memoize(function () array.toObject([[v, k] for ([k, v] in Iterator(this.PERMS))])),
COMMANDS: {
unset: "Unset",
allow: "Allowed",
deny: "Denied",
session: "Allowed for the current session",
list: "List all cookies for domain",
clear: "Clear all cookies for domain",
"clear-persistent": "Clear all persistent cookies for domain",
"clear-session": "Clear all session cookies for domain",
},
argPrefMap: { argPrefMap: {
offlineapps: "offlineApps", offlineapps: "offlineApps",
sitesettings: "siteSettings", sitesettings: "siteSettings",
@@ -414,6 +430,93 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
], ],
privateData: true privateData: true
}); });
function getPerms(host) {
let uri = util.createURI(host);
if (uri)
return Sanitizer.UNPERMS[services.get("permissions").testPermission(uri, "cookie")];
return "unset";
}
function setPerms(host, perm) {
let uri = util.createURI(host);
services.get("permissions").remove(uri, "cookie");
services.get("permissions").add(uri, "cookie", Sanitizer.PERMS[perm]);
}
commands.addUserCommand(["cookies", "ck"],
"Change cookie permissions for sites.",
function (args) {
let host = args.shift();
let session = true;
if (!args.length)
args = modules.options["cookies"];
for (let [,cmd] in Iterator(args))
switch (cmd) {
case "clear":
for (let c in Sanitizer.iterCookies(host))
services.get("cookies").remove(c.host, c.name, c.path, false);
break;
case "clear-persistent":
session = false;
case "clear-session":
for (let c in Sanitizer.iterCookies(host))
if (c.isSession == session)
services.get("cookies").remove(c.host, c.name, c.path, false);
return;
case "list":
modules.commandLine.commandOutput(template.tabular(
["Host", "Session", "Path", "Value"], ["padding-right: 1em", "padding-right: 1em", "padding-right: 1em"],
([c.host,
<span highlight={c.isSession ? "Enabled" : "Disabled"}>{c.isSession ? "session" : "persistent"}</span>,
c.path,
c.value]
for (c in Sanitizer.iterCookies(host)))));
return;
default:
util.assert(cmd in Sanitizer.PERMS, "Invalid argument");
setPerms(host, cmd);
}
}, {
argCount: "+",
completer: function (context, args) {
switch (args.completeArg) {
case 0:
modules.completion.visibleHosts(context);
context.title[1] = "Current Permissions";
context.keys.description = function desc(host) {
let count = [0, 0];
for (let c in Sanitizer.iterCookies(host))
count[c.isSession + 0]++;
return <>{Sanitizer.COMMANDS[getPerms(host)]} (session: {count[1]} persistent: {count[0]})</>;
}
break;
case 1:
context.completions = Sanitizer.COMMANDS;
break;
}
},
}, true);
},
completion: function (dactyl, modules, window) {
modules.completion.visibleHosts = function completeHosts(context) {
let res = [], seen = {};
(function rec(frame) {
try {
res = res.concat(util.subdomains(frame.location.host));
} catch (e) {}
Array.forEach(frame.frames, rec);
})(window.content);
if (context.filter && !res.some(function (host) host.indexOf(context.filter) >= 0))
res.push(context.filter);
context.title = ["Domain"];
context.anchored = false;
context.compare = modules.CompletionContext.Sort.unsorted;
context.keys = { text: util.identity, description: util.identity };
context.completions = res.filter(function (h) !set.add(seen, h));
};
}, },
options: function (dactyl, modules) { options: function (dactyl, modules) {
const options = modules.options; const options = modules.options;
@@ -427,7 +530,8 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
setter: function (value) { setter: function (value) {
if (services.get("privateBrowsing").privateBrowsingEnabled != value) if (services.get("privateBrowsing").privateBrowsingEnabled != value)
services.get("privateBrowsing").privateBrowsingEnabled = value services.get("privateBrowsing").privateBrowsingEnabled = value
} },
persist: false
}); });
options.add(["sanitizeitems", "si"], options.add(["sanitizeitems", "si"],
@@ -481,6 +585,55 @@ const Sanitizer = Module("sanitizer", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakR
}, },
validator: function (value) /^(a(ll)?|s(ession)|\d+[mhdw])$/.test(value) validator: function (value) /^(a(ll)?|s(ession)|\d+[mhdw])$/.test(value)
}); });
options.add(["cookies", "ck"],
"The default mode for newly added cookie permissions",
"stringlist", "session",
{ completer: function (context) iter(Sanitizer.COMMANDS) });
options.add(["cookieaccept", "ca"],
"When to accept cookies",
"string", "all",
{
PREF: "network.cookie.cookieBehavior",
completer: function (context) [
["all", "Accept all cookies"],
["samesite", "Accept all non-third-party cookies"],
["none", "Accept no cookies"]
],
getter: function () (this.completer()[prefs.get(this.PREF)] || ["all"])[0],
setter: function (val) {
prefs.set(this.PREF, this.completer().map(function (i) i[0]).indexOf(val));
return val;
},
initialValue: true,
persist: false
});
options.add(["cookielifetime", "cl"],
"The lifetime for which to accept cookies",
"string", "default", {
PREF: "network.cookie.lifetimePolicy",
PREF_DAYS: "network.cookie.lifetime.days",
completer: function (context) [
["default", "The lifetime requested by the setter"],
["prompt", "Always prompt for a lifetime"],
["session", "The current session"]
],
getter: function () (this.completer()[prefs.get(this.PREF)]
|| [prefs.get(this.PREF_DAYS)])[0],
setter: function (value) {
let val = this.completer().map(function (i) i[0]).indexOf(value);
if (val > -1)
prefs.set(this.PREF, val);
else {
prefs.set(this.PREF, 3);
prefs.set(this.PREF_DAYS, parseInt(value));
}
},
initialValue: true,
persist: false,
validator: function (val) parseInt(val) == val || modules.Option.validateCompleter.call(this, val)
});
} }
}); });

View File

@@ -268,10 +268,14 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
domToString: function (node) { domToString: function (node) {
this._div.appendChild(this._div.ownerDocument.importNode(node, true)); this._div.appendChild(this._div.ownerDocument.importNode(node, true));
let sel = this._div.ownerDocument.defaultView.getSelection(); if (/^pre(-wrap)?$/.test(this.computedStyle(this._div.lastChild).whiteSpace))
sel.removeAllRanges(); var res = this._div.textContent;
sel.selectAllChildren(this._div); else {
let res = sel.toString(); let sel = this._div.ownerDocument.defaultView.getSelection();
sel.removeAllRanges();
sel.selectAllChildren(this._div);
var res = sel.toString();
}
while (this._div.firstChild) while (this._div.firstChild)
this._div.removeChild(this._div.firstChild); this._div.removeChild(this._div.firstChild);
return res; return res;
@@ -730,6 +734,12 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
} }
}, },
overlayWindow: function (url, fn) {
Array.concat(url).forEach(function (url) {
this.overlays[url] = fn;
}, this);
},
/** /**
* Parses the fields of a form and returns a URL/POST-data pair * Parses the fields of a form and returns a URL/POST-data pair
* that is the equivalent of submitting the form. * that is the equivalent of submitting the form.
@@ -797,6 +807,26 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
} }
}, },
/**
* An interruptible generator that returns all values between <b>start</b>
* and <b>end</b>. The thread yields every <b>time</b> milliseconds.
*
* @param {number} start The interval's start value.
* @param {number} end The interval's end value.
* @param {number} time The time in milliseconds between thread yields.
* @returns {Iterator(Object)}
*/
interruptibleRange: function interruptibleRange(start, end, time) {
let endTime = Date.now() + time;
while (start < end) {
if (Date.now() > endTime) {
util.threadYield(true, true);
endTime = Date.now() + time;
}
yield start++;
}
},
maxErrors: 15, maxErrors: 15,
errors: Class.memoize(function () []), errors: Class.memoize(function () []),
reportError: function (error) { reportError: function (error) {
@@ -823,29 +853,26 @@ const Util = Module("Util", XPCOM([Ci.nsIObserver, Ci.nsISupportsWeakReference])
}, },
/** /**
* An interruptible generator that returns all values between <b>start</b> * Given a domain, returns an array of all non-toplevel subdomains
* and <b>end</b>. The thread yields every <b>time</b> milliseconds. * of that domain.
* *
* @param {number} start The interval's start value. * @param {string} host The host for which to find subdomains.
* @param {number} end The interval's end value. * @returns {[string]}
* @param {number} time The time in milliseconds between thread yields.
* @returns {Iterator(Object)}
*/ */
interruptibleRange: function interruptibleRange(start, end, time) { subdomains: function subdomains(host) {
let endTime = Date.now() + time; if (/(^|\.)\d+$|:.*:/.test(host))
while (start < end) { // IP address or similar
if (Date.now() > endTime) { return [host];
util.threadYield(true, true);
endTime = Date.now() + time;
}
yield start++;
}
},
overlayWindow: function (url, fn) { let base = host.replace(/.*\.(.+?\..+?)$/, "$1");
Array.concat(url).forEach(function (url) { try {
this.overlays[url] = fn; base = services.get("tld").getBaseDomainFromHost(host);
}, this); }
catch (e) {}
let ary = host.split(".");
ary = [ary.slice(i).join(".") for (i in util.range(ary.length - 1, 0, -1))];
return ary.filter(function (h) h.length >= base.length);
}, },
/** /**