1
0
mirror of https://github.com/gorhill/uBlock.git synced 2024-10-06 09:37:12 +02:00

improve DOM inspector

- Fix regressions reported in #3159
- Fix #2001
- Fix some item points in #407
This commit is contained in:
gorhill 2017-11-20 08:42:32 -05:00
parent 949b994811
commit 806032cdc4
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2
12 changed files with 743 additions and 1018 deletions

View File

@ -735,32 +735,21 @@ vAPI.messaging.listen = function(listenerName, callback) {
vAPI.messaging.onPortMessage = (function() { vAPI.messaging.onPortMessage = (function() {
var messaging = vAPI.messaging, var messaging = vAPI.messaging,
toAuxPending = new Map(); supportsUserStylesheets = vAPI.supportsUserStylesheets;
var supportsUserStylesheets = vAPI.supportsUserStylesheets;
// Use a wrapper to avoid closure and to allow reuse. // Use a wrapper to avoid closure and to allow reuse.
var CallbackWrapper = function(port, request, timeout) { var CallbackWrapper = function(port, request) {
this.callback = this.proxy.bind(this); // bind once this.callback = this.proxy.bind(this); // bind once
this.init(port, request, timeout); this.init(port, request);
}; };
CallbackWrapper.prototype = { CallbackWrapper.prototype = {
timerId: null, init: function(port, request) {
init: function(port, request, timeout) {
this.port = port; this.port = port;
this.request = request; this.request = request;
if ( timeout !== undefined ) {
this.timerId = vAPI.setTimeout(this.callback, timeout);
}
return this; return this;
}, },
proxy: function(response) { proxy: function(response) {
if ( this.timerId !== null ) {
clearTimeout(this.timerId);
toAuxPending.delete(this.timerId);
this.timerId = null;
}
// https://github.com/chrisaljoudi/uBlock/issues/383 // https://github.com/chrisaljoudi/uBlock/issues/383
if ( messaging.ports.has(this.port.name) ) { if ( messaging.ports.has(this.port.name) ) {
this.port.postMessage({ this.port.postMessage({
@ -777,67 +766,53 @@ vAPI.messaging.onPortMessage = (function() {
var callbackWrapperJunkyard = []; var callbackWrapperJunkyard = [];
var callbackWrapperFactory = function(port, request, timeout) { var callbackWrapperFactory = function(port, request) {
var wrapper = callbackWrapperJunkyard.pop(); var wrapper = callbackWrapperJunkyard.pop();
if ( wrapper ) { if ( wrapper ) {
return wrapper.init(port, request, timeout); return wrapper.init(port, request);
} }
return new CallbackWrapper(port, request, timeout); return new CallbackWrapper(port, request);
}; };
var toAux = function(details, portFrom) { var toFramework = function(request, port) {
var port, portTo, var sender = port && port.sender;
chromiumTabId = toChromiumTabId(details.toTabId); if ( !sender ) { return; }
var tabId = sender.tab && sender.tab.id;
// TODO: This could be an issue with a lot of tabs: easy to address
// with a port name to tab id map.
// When sending to an auxiliary process, the target is always the
// port associated with the root frame.
for ( var entry of messaging.ports ) {
port = entry[1];
if ( port.sender.frameId === 0 && port.sender.tab.id === chromiumTabId ) {
portTo = port;
break;
}
}
var wrapper;
if ( details.auxProcessId !== undefined ) {
wrapper = callbackWrapperFactory(portFrom, details, 1023);
}
// Destination not found:
if ( portTo === undefined ) {
if ( wrapper !== undefined ) {
wrapper.callback();
}
return;
}
if ( wrapper !== undefined ) {
toAuxPending.set(wrapper.timerId, wrapper);
}
portTo.postMessage({
mainProcessId: wrapper && wrapper.timerId,
channelName: details.toChannel,
msg: details.msg
});
};
var toAuxResponse = function(details) {
var mainProcessId = details.mainProcessId;
if ( mainProcessId === undefined ) { return; }
var wrapper = toAuxPending.get(mainProcessId);
if ( wrapper === undefined ) { return; }
toAuxPending.delete(mainProcessId);
wrapper.callback(details.msg);
};
var toFramework = function(msg, sender) {
var tabId = sender && sender.tab && sender.tab.id;
if ( !tabId ) { return; } if ( !tabId ) { return; }
var msg = request.msg,
toPort;
switch ( msg.what ) { switch ( msg.what ) {
case 'connectionAccepted':
case 'connectionRefused':
toPort = messaging.ports.get(msg.fromToken);
if ( toPort !== undefined ) {
msg.tabId = tabId.toString();
toPort.postMessage(request);
} else {
msg.what = 'connectionBroken';
port.postMessage(request);
}
break;
case 'connectionRequested':
msg.tabId = '' + tabId.toString();
for ( toPort of messaging.ports.values() ) {
toPort.postMessage(request);
}
break;
case 'connectionBroken':
case 'connectionCheck':
case 'connectionMessage':
toPort = messaging.ports.get(
port.name === msg.fromToken ? msg.toToken : msg.fromToken
);
if ( toPort !== undefined ) {
msg.tabId = tabId.toString();
toPort.postMessage(request);
} else {
msg.what = 'connectionBroken';
port.postMessage(request);
}
break;
case 'userCSS': case 'userCSS':
var details = { var details = {
code: undefined, code: undefined,
@ -863,23 +838,23 @@ vAPI.messaging.onPortMessage = (function() {
} }
}; };
// https://bugzilla.mozilla.org/show_bug.cgi?id=1392067
// Workaround: manually remove ports matching removed tab.
chrome.tabs.onRemoved.addListener(function(tabId) {
for ( var port of messaging.ports.values() ) {
var tab = port.sender && port.sender.tab;
if ( !tab ) { continue; }
if ( tab.id === tabId ) {
vAPI.messaging.onPortDisconnect(port);
}
}
});
return function(request, port) { return function(request, port) {
// Auxiliary process to auxiliary process
if ( request.toTabId !== undefined ) {
toAux(request, port);
return;
}
// Auxiliary process to auxiliary process: response
if ( request.mainProcessId !== undefined ) {
toAuxResponse(request);
return;
}
// Content process to main process: framework handler. // Content process to main process: framework handler.
// No callback supported/needed for now. // No callback supported/needed for now.
if ( request.channelName === 'vapi-background' ) { if ( request.channelName === 'vapi' ) {
toFramework(request.msg, port.sender); toFramework(request, port);
return; return;
} }
@ -952,8 +927,8 @@ vAPI.messaging.broadcast = function(message) {
broadcast: true, broadcast: true,
msg: message msg: message
}; };
for ( var entry of this.ports ) { for ( var port of this.ports.values() ) {
entry[1].postMessage(messageWrapper); port.postMessage(messageWrapper);
} }
}; };

View File

@ -71,13 +71,35 @@ vAPI.messaging = {
port: null, port: null,
portTimer: null, portTimer: null,
portTimerDelay: 10000, portTimerDelay: 10000,
channels: Object.create(null), channels: new Map(),
channelCount: 0, connections: new Map(),
pending: Object.create(null), pending: new Map(),
pendingCount: 0,
auxProcessId: 1, auxProcessId: 1,
shuttingDown: false, shuttingDown: false,
Connection: function(handler, details) {
var messaging = vAPI.messaging;
this.messaging = messaging;
this.handler = handler;
this.id = details.id;
this.to = details.to;
this.toToken = details.toToken;
this.from = details.from;
this.fromToken = details.fromToken;
this.checkBound = this.check.bind(this);
this.checkTimer = undefined;
// On Firefox it appears ports are not automatically disconnected when
// navigating to another page.
if ( messaging.Connection.pagehide !== undefined ) { return; }
messaging.Connection.pagehide = function() {
for ( var connection of this.connections.values() ) {
connection.disconnect();
connection.handler(connection.toDetails('connectionBroken'));
}
}.bind(messaging);
window.addEventListener('pagehide', messaging.Connection.pagehide);
},
shutdown: function() { shutdown: function() {
this.shuttingDown = true; this.shuttingDown = true;
this.destroyPort(); this.destroyPort();
@ -87,46 +109,65 @@ vAPI.messaging = {
this.port = null; this.port = null;
vAPI.shutdown.exec(); vAPI.shutdown.exec();
}, },
disconnectListenerCallback: null, disconnectListenerBound: null,
messageListener: function(details) { messageListener: function(details) {
if ( !details ) { if ( !details ) { return; }
return;
}
// Sent to all channels // Sent to all channels
if ( details.broadcast === true && !details.channelName ) { if ( details.broadcast ) {
for ( var channelName in this.channels ) { for ( var channelName of this.channels.keys() ) {
this.sendToChannelListeners(channelName, details.msg); this.sendToChannelListeners(channelName, details.msg);
} }
return; return;
} }
// Response to specific message previously sent // Response to specific message previously sent
var listener;
if ( details.auxProcessId ) { if ( details.auxProcessId ) {
var listener = this.pending[details.auxProcessId]; listener = this.pending.get(details.auxProcessId);
delete this.pending[details.auxProcessId]; if ( listener !== undefined ) {
delete details.auxProcessId; // TODO: why? this.pending.delete(details.auxProcessId);
if ( listener ) {
this.pendingCount -= 1;
listener(details.msg); listener(details.msg);
return; return;
} }
} }
// Sent to a specific channel if ( details.channelName !== 'vapi' ) { return; }
var response = this.sendToChannelListeners(details.channelName, details.msg);
// Respond back if required // Internal handler
if ( details.mainProcessId === undefined ) { var connection;
return;
} switch ( details.msg.what ) {
var port = this.connect(); case 'connectionAccepted':
if ( port !== null ) { case 'connectionBroken':
port.postMessage({ case 'connectionCheck':
mainProcessId: details.mainProcessId, case 'connectionMessage':
msg: response case 'connectionRefused':
}); connection = this.connections.get(details.msg.id);
if ( connection === undefined ) { return; }
connection.receive(details.msg);
break;
case 'connectionRequested':
var listeners = this.channels.get(details.msg.to);
if ( listeners === undefined ) { return; }
var port = this.getPort();
if ( port === null ) { return; }
for ( listener of listeners ) {
if ( listener(details.msg) !== true ) { continue; }
details.msg.what = 'connectionAccepted';
details.msg.toToken = port.name;
connection = new this.Connection(listener, details.msg);
this.connections.set(connection.id, connection);
break;
}
if ( details.msg.what !== 'connectionAccepted' ) {
details.msg.what = 'connectionRefused';
}
port.postMessage(details);
break;
default:
break;
} }
}, },
messageListenerCallback: null, messageListenerCallback: null,
@ -135,15 +176,16 @@ vAPI.messaging = {
this.portTimer = null; this.portTimer = null;
if ( if (
this.port !== null && this.port !== null &&
this.channelCount === 0 && this.channels.size === 0 &&
this.pendingCount === 0 this.connections.size === 0 &&
this.pending.size === 0
) { ) {
return this.destroyPort(); return this.destroyPort();
} }
this.portTimer = vAPI.setTimeout(this.portPollerCallback, this.portTimerDelay); this.portTimer = vAPI.setTimeout(this.portPollerBound, this.portTimerDelay);
this.portTimerDelay = Math.min(this.portTimerDelay * 2, 60 * 60 * 1000); this.portTimerDelay = Math.min(this.portTimerDelay * 2, 60 * 60 * 1000);
}, },
portPollerCallback: null, portPollerBound: null,
destroyPort: function() { destroyPort: function() {
if ( this.portTimer !== null ) { if ( this.portTimer !== null ) {
@ -154,20 +196,21 @@ vAPI.messaging = {
if ( port !== null ) { if ( port !== null ) {
port.disconnect(); port.disconnect();
port.onMessage.removeListener(this.messageListenerCallback); port.onMessage.removeListener(this.messageListenerCallback);
port.onDisconnect.removeListener(this.disconnectListenerCallback); port.onDisconnect.removeListener(this.disconnectListenerBound);
this.port = null; this.port = null;
} }
if ( this.channelCount !== 0 ) { this.channels.clear();
this.channels = Object.create(null); if ( this.connections.size !== 0 ) {
this.channelCount = 0; for ( var connection of this.connections.values() ) {
connection.receive({ what: 'connectionBroken' });
}
this.connections.clear();
} }
// service pending callbacks // service pending callbacks
if ( this.pendingCount !== 0 ) { if ( this.pending.size !== 0 ) {
var pending = this.pending, callback; var pending = this.pending;
this.pending = Object.create(null); this.pending = new Map();
this.pendingCount = 0; for ( var callback of pending.values() ) {
for ( var auxId in pending ) {
callback = pending[auxId];
if ( typeof callback === 'function' ) { if ( typeof callback === 'function' ) {
callback(null); callback(null);
} }
@ -176,13 +219,11 @@ vAPI.messaging = {
}, },
createPort: function() { createPort: function() {
if ( this.shuttingDown ) { if ( this.shuttingDown ) { return null; }
return null;
}
if ( this.messageListenerCallback === null ) { if ( this.messageListenerCallback === null ) {
this.messageListenerCallback = this.messageListener.bind(this); this.messageListenerCallback = this.messageListener.bind(this);
this.disconnectListenerCallback = this.disconnectListener.bind(this); this.disconnectListenerBound = this.disconnectListener.bind(this);
this.portPollerCallback = this.portPoller.bind(this); this.portPollerBound = this.portPoller.bind(this);
} }
try { try {
this.port = chrome.runtime.connect({name: vAPI.sessionId}) || null; this.port = chrome.runtime.connect({name: vAPI.sessionId}) || null;
@ -191,102 +232,109 @@ vAPI.messaging = {
} }
if ( this.port !== null ) { if ( this.port !== null ) {
this.port.onMessage.addListener(this.messageListenerCallback); this.port.onMessage.addListener(this.messageListenerCallback);
this.port.onDisconnect.addListener(this.disconnectListenerCallback); this.port.onDisconnect.addListener(this.disconnectListenerBound);
} this.portTimerDelay = 10000;
this.portTimerDelay = 10000; if ( this.portTimer === null ) {
if ( this.portTimer === null ) { this.portTimer = vAPI.setTimeout(
this.portTimer = vAPI.setTimeout(this.portPollerCallback, this.portTimerDelay); this.portPollerBound,
this.portTimerDelay
);
}
} }
return this.port; return this.port;
}, },
connect: function() { getPort: function() {
return this.port !== null ? this.port : this.createPort(); return this.port !== null ? this.port : this.createPort();
}, },
send: function(channelName, message, callback) { send: function(channelName, message, callback) {
this.sendTo(channelName, message, undefined, undefined, callback);
},
sendTo: function(channelName, message, toTabId, toChannel, callback) {
// Too large a gap between the last request and the last response means // Too large a gap between the last request and the last response means
// the main process is no longer reachable: memory leaks and bad // the main process is no longer reachable: memory leaks and bad
// performance become a risk -- especially for long-lived, dynamic // performance become a risk -- especially for long-lived, dynamic
// pages. Guard against this. // pages. Guard against this.
if ( this.pendingCount > 25 ) { if ( this.pending.size > 25 ) {
vAPI.shutdown.exec(); vAPI.shutdown.exec();
} }
var port = this.connect(); var port = this.getPort();
if ( port === null ) { if ( port === null ) {
if ( typeof callback === 'function' ) { if ( typeof callback === 'function' ) { callback(); }
callback();
}
return; return;
} }
var auxProcessId; var auxProcessId;
if ( callback ) { if ( callback ) {
auxProcessId = this.auxProcessId++; auxProcessId = this.auxProcessId++;
this.pending[auxProcessId] = callback; this.pending.set(auxProcessId, callback);
this.pendingCount += 1;
} }
port.postMessage({ port.postMessage({
channelName: channelName, channelName: channelName,
auxProcessId: auxProcessId, auxProcessId: auxProcessId,
toTabId: toTabId,
toChannel: toChannel,
msg: message msg: message
}); });
}, },
addChannelListener: function(channelName, callback) { connectTo: function(from, to, handler) {
if ( typeof callback !== 'function' ) { var port = this.getPort();
return; if ( port === null ) { return; }
} var connection = new this.Connection(handler, {
var listeners = this.channels[channelName]; id: from + '-' + to + '-' + vAPI.sessionId,
if ( listeners !== undefined && listeners.indexOf(callback) !== -1 ) { to: to,
console.error('Duplicate listener on channel "%s"', channelName); from: from,
return; fromToken: port.name
} });
if ( listeners === undefined ) { this.connections.set(connection.id, connection);
this.channels[channelName] = [callback]; port.postMessage({
this.channelCount += 1; channelName: 'vapi',
} else { msg: {
listeners.push(callback); what: 'connectionRequested',
} id: connection.id,
this.connect(); from: from,
fromToken: port.name,
to: to
}
});
return connection.id;
}, },
removeChannelListener: function(channelName, callback) { disconnectFrom: function(connectionId) {
if ( typeof callback !== 'function' ) { var connection = this.connections.get(connectionId);
return; if ( connection === undefined ) { return; }
} connection.disconnect();
var listeners = this.channels[channelName]; },
sendTo: function(connectionId, payload) {
var connection = this.connections.get(connectionId);
if ( connection === undefined ) { return; }
connection.send(payload);
},
addChannelListener: function(channelName, listener) {
var listeners = this.channels.get(channelName);
if ( listeners === undefined ) { if ( listeners === undefined ) {
return; this.channels.set(channelName, [ listener ]);
} } else if ( listeners.indexOf(listener) === -1 ) {
var pos = listeners.indexOf(callback); listeners.push(listener);
if ( pos === -1 ) {
console.error('Listener not found on channel "%s"', channelName);
return;
} }
this.getPort();
},
removeChannelListener: function(channelName, listener) {
var listeners = this.channels.get(channelName);
if ( listeners === undefined ) { return; }
var pos = listeners.indexOf(listener);
if ( pos === -1 ) { return; }
listeners.splice(pos, 1); listeners.splice(pos, 1);
if ( listeners.length === 0 ) { if ( listeners.length === 0 ) {
delete this.channels[channelName]; this.channels.delete(channelName);
this.channelCount -= 1;
} }
}, },
removeAllChannelListeners: function(channelName) { removeAllChannelListeners: function(channelName) {
var listeners = this.channels[channelName]; this.channels.delete(channelName);
if ( listeners === undefined ) {
return;
}
delete this.channels[channelName];
this.channelCount -= 1;
}, },
sendToChannelListeners: function(channelName, msg) { sendToChannelListeners: function(channelName, msg) {
var listeners = this.channels[channelName]; var listeners = this.channels.get(channelName);
if ( listeners === undefined ) { return; } if ( listeners === undefined ) { return; }
listeners = listeners.slice(0); listeners = listeners.slice(0);
var response; var response;
@ -300,9 +348,94 @@ vAPI.messaging = {
/******************************************************************************/ /******************************************************************************/
vAPI.messaging.Connection.prototype = {
toDetails: function(what, payload) {
return {
what: what,
id: this.id,
from: this.from,
fromToken: this.fromToken,
to: this.to,
toToken: this.toToken,
payload: payload
};
},
disconnect: function() {
if ( this.checkTimer !== undefined ) {
clearTimeout(this.checkTimer);
this.checkTimer = undefined;
}
this.messaging.connections.delete(this.id);
var port = this.messaging.getPort();
if ( port === null ) { return; }
port.postMessage({
channelName: 'vapi',
msg: this.toDetails('connectionBroken')
});
},
checkAsync: function() {
if ( this.checkTimer !== undefined ) {
clearTimeout(this.checkTimer);
}
this.checkTimer = vAPI.setTimeout(this.checkBound, 499);
},
check: function() {
this.checkTimer = undefined;
if ( this.messaging.connections.has(this.id) === false ) { return; }
var port = this.messaging.getPort();
if ( port === null ) { return; }
port.postMessage({
channelName: 'vapi',
msg: this.toDetails('connectionCheck')
});
this.checkAsync();
},
receive: function(details) {
switch ( details.what ) {
case 'connectionAccepted':
this.toToken = details.toToken;
this.handler(details);
this.checkAsync();
break;
case 'connectionBroken':
this.messaging.connections.delete(this.id);
this.handler(details);
break;
case 'connectionMessage':
this.handler(details);
this.checkAsync();
break;
case 'connectionCheck':
var port = this.messaging.getPort();
if ( port === null ) { return; }
if ( this.messaging.connections.has(this.id) ) {
this.checkAsync();
} else {
details.what = 'connectionBroken';
port.postMessage({ channelName: 'vapi', msg: details });
}
break;
case 'connectionRefused':
this.messaging.connections.delete(this.id);
this.handler(details);
break;
}
},
send: function(payload) {
var port = this.messaging.getPort();
if ( port === null ) { return; }
port.postMessage({
channelName: 'vapi',
msg: this.toDetails('connectionMessage', payload)
});
}
};
/******************************************************************************/
vAPI.shutdown.add(function() { vAPI.shutdown.add(function() {
vAPI.messaging.shutdown(); vAPI.messaging.shutdown();
delete window.vAPI; window.vAPI = undefined;
}); });
// https://www.youtube.com/watch?v=rT5zCHn0tsg // https://www.youtube.com/watch?v=rT5zCHn0tsg

View File

@ -1572,31 +1572,22 @@ vAPI.messaging.listen = function(listenerName, callback) {
vAPI.messaging.onMessage = (function() { vAPI.messaging.onMessage = (function() {
var messaging = vAPI.messaging; var messaging = vAPI.messaging;
var toAuxPending = {};
// Use a wrapper to avoid closure and to allow reuse. // Use a wrapper to avoid closure and to allow reuse.
var CallbackWrapper = function(messageManager, listenerId, channelName, auxProcessId, timeout) { var CallbackWrapper = function(messageManager, listenerId, channelName, auxProcessId) {
this.callback = this.proxy.bind(this); // bind once this.callback = this.proxy.bind(this); // bind once
this.init(messageManager, listenerId, channelName, auxProcessId, timeout); this.init(messageManager, listenerId, channelName, auxProcessId);
}; };
CallbackWrapper.prototype.init = function(messageManager, listenerId, channelName, auxProcessId, timeout) { CallbackWrapper.prototype.init = function(messageManager, listenerId, channelName, auxProcessId) {
this.messageManager = messageManager; this.messageManager = messageManager;
this.listenerId = listenerId; this.listenerId = listenerId;
this.channelName = channelName; this.channelName = channelName;
this.auxProcessId = auxProcessId; this.auxProcessId = auxProcessId;
this.timerId = timeout !== undefined ?
vAPI.setTimeout(this.callback, timeout) :
null;
return this; return this;
}; };
CallbackWrapper.prototype.proxy = function(response) { CallbackWrapper.prototype.proxy = function(response) {
if ( this.timerId !== null ) {
clearTimeout(this.timerId);
delete toAuxPending[this.timerId];
this.timerId = null;
}
var message = JSON.stringify({ var message = JSON.stringify({
auxProcessId: this.auxProcessId, auxProcessId: this.auxProcessId,
channelName: this.channelName, channelName: this.channelName,
@ -1619,97 +1610,15 @@ vAPI.messaging.onMessage = (function() {
var callbackWrapperJunkyard = []; var callbackWrapperJunkyard = [];
var callbackWrapperFactory = function(messageManager, listenerId, channelName, auxProcessId, timeout) { var callbackWrapperFactory = function(messageManager, listenerId, channelName, auxProcessId) {
var wrapper = callbackWrapperJunkyard.pop(); var wrapper = callbackWrapperJunkyard.pop();
if ( wrapper ) { if ( wrapper ) {
return wrapper.init(messageManager, listenerId, channelName, auxProcessId, timeout); return wrapper.init(messageManager, listenerId, channelName, auxProcessId);
} }
return new CallbackWrapper(messageManager, listenerId, channelName, auxProcessId, timeout); return new CallbackWrapper(messageManager, listenerId, channelName, auxProcessId);
};
// "Auxiliary process": any process other than main process.
var toAux = function(target, details) {
var messageManagerFrom = target.messageManager;
// Message came from a popup, and its message manager is not usable.
// So instead we broadcast to the parent window.
if ( !messageManagerFrom ) {
messageManagerFrom = getOwnerWindow(
target.webNavigation.QueryInterface(Ci.nsIDocShell).chromeEventHandler
).messageManager;
}
var wrapper;
if ( details.auxProcessId !== undefined ) {
var channelNameRaw = details.channelName;
var pos = channelNameRaw.indexOf('|');
wrapper = callbackWrapperFactory(
messageManagerFrom,
channelNameRaw.slice(0, pos),
channelNameRaw.slice(pos + 1),
details.auxProcessId,
1023
);
}
var messageManagerTo = null;
var browser = tabWatcher.browserFromTabId(details.toTabId);
if ( browser !== null && browser.messageManager ) {
messageManagerTo = browser.messageManager;
}
if ( messageManagerTo === null ) {
if ( wrapper !== undefined ) {
wrapper.callback();
}
return;
}
// As per HTML5, timer id is always an integer, thus suitable to be used
// as a key, and which value is safe to use across process boundaries.
if ( wrapper !== undefined ) {
toAuxPending[wrapper.timerId] = wrapper;
}
var targetId = location.host + ':broadcast';
var payload = JSON.stringify({
mainProcessId: wrapper && wrapper.timerId,
channelName: details.toChannel,
msg: details.msg
});
if ( messageManagerTo.sendAsyncMessage ) {
messageManagerTo.sendAsyncMessage(targetId, payload);
} else {
messageManagerTo.broadcastAsyncMessage(targetId, payload);
}
};
var toAuxResponse = function(details) {
var mainProcessId = details.mainProcessId;
if ( mainProcessId === undefined ) {
return;
}
if ( toAuxPending.hasOwnProperty(mainProcessId) === false ) {
return;
}
var wrapper = toAuxPending[mainProcessId];
delete toAuxPending[mainProcessId];
wrapper.callback(details.msg);
}; };
return function({target, data}) { return function({target, data}) {
// Auxiliary process to auxiliary process
if ( data.toTabId !== undefined ) {
toAux(target, data);
return;
}
// Auxiliary process to auxiliary process: response
if ( data.mainProcessId !== undefined ) {
toAuxResponse(data);
return;
}
// Auxiliary process to main process // Auxiliary process to main process
var messageManager = target.messageManager; var messageManager = target.messageManager;
@ -1748,15 +1657,11 @@ vAPI.messaging.onMessage = (function() {
if ( typeof listener === 'function' ) { if ( typeof listener === 'function' ) {
r = listener(data.msg, sender, callback); r = listener(data.msg, sender, callback);
} }
if ( r !== messaging.UNHANDLED ) { if ( r !== messaging.UNHANDLED ) { return; }
return;
}
// Auxiliary process to main process: default handler // Auxiliary process to main process: default handler
r = messaging.defaultHandler(data.msg, sender, callback); r = messaging.defaultHandler(data.msg, sender, callback);
if ( r !== messaging.UNHANDLED ) { if ( r !== messaging.UNHANDLED ) { return; }
return;
}
// Auxiliary process to main process: no handler // Auxiliary process to main process: no handler
console.error('uBlock> messaging > unknown request: %o', data); console.error('uBlock> messaging > unknown request: %o', data);

View File

@ -150,22 +150,18 @@ var processUserCSS = function(details, callback) {
/******************************************************************************/ /******************************************************************************/
vAPI.messaging = { vAPI.messaging = {
channels: Object.create(null), channels: new Map(),
channelCount: 0, pending: new Map(),
pending: Object.create(null),
pendingCount: 0,
auxProcessId: 1, auxProcessId: 1,
connected: false, connected: false,
messageListener: function(msg) { messageListener: function(msg) {
var details = JSON.parse(msg); var details = JSON.parse(msg);
if ( !details ) { if ( !details ) { return; }
return;
}
// Sent to all channels // Sent to all channels
if ( details.broadcast && !details.channelName ) { if ( details.broadcast && !details.channelName ) {
for ( var channelName in this.channels ) { for ( var channelName of this.channels.keys() ) {
this.sendToChannelListeners(channelName, details.msg); this.sendToChannelListeners(channelName, details.msg);
} }
return; return;
@ -173,42 +169,27 @@ vAPI.messaging = {
// Response to specific message previously sent // Response to specific message previously sent
if ( details.auxProcessId ) { if ( details.auxProcessId ) {
var listener = this.pending[details.auxProcessId]; var listener = this.pending.get(details.auxProcessId);
delete this.pending[details.auxProcessId]; this.pending.delete(details.auxProcessId);
delete details.auxProcessId; // TODO: why?
if ( listener ) { if ( listener ) {
this.pendingCount -= 1;
listener(details.msg); listener(details.msg);
return; return;
} }
} }
// Sent to a specific channel // Sent to a specific channel
var response = this.sendToChannelListeners(details.channelName, details.msg); this.sendToChannelListeners(details.channelName, details.msg);
// Respond back if required
if ( details.mainProcessId === undefined ) {
return;
}
sendAsyncMessage('ublock0:background', {
mainProcessId: details.mainProcessId,
msg: response
});
}, },
builtinListener: function(msg) { builtinListener: function(msg) {
if ( msg.cmd === 'injectScript' ) { if ( msg.cmd === 'injectScript' ) {
// injectScript is not always present. // injectScript is not always present.
// - See contentObserver.initContentScripts in frameModule.js // - See contentObserver.initContentScripts in frameModule.js
if ( typeof self.injectScript !== 'function' ) { if ( typeof self.injectScript !== 'function' ) { return; }
return;
}
var details = msg.details; var details = msg.details;
// Whether to inject in all child frames. Default to only top frame. // Whether to inject in all child frames. Default to only top frame.
var allFrames = details.allFrames || false; var allFrames = details.allFrames || false;
if ( allFrames !== true && window !== window.top ) { if ( allFrames !== true && window !== window.top ) { return; }
return;
}
// https://github.com/gorhill/uBlock/issues/876 // https://github.com/gorhill/uBlock/issues/876
// Enforce `details.runAt`. Default to `document_end`. // Enforce `details.runAt`. Default to `document_end`.
var runAt = details.runAt || 'document_end'; var runAt = details.runAt || 'document_end';
@ -225,7 +206,7 @@ vAPI.messaging = {
} }
if ( msg.cmd === 'shutdownSandbox' ) { if ( msg.cmd === 'shutdownSandbox' ) {
vAPI.shutdown.exec(); vAPI.shutdown.exec();
this.stop(); vAPI.messaging.stop();
if ( typeof self.outerShutdown === 'function' ) { if ( typeof self.outerShutdown === 'function' ) {
outerShutdown(); outerShutdown();
} }
@ -263,7 +244,7 @@ vAPI.messaging = {
toggleListenerCallback: null, toggleListenerCallback: null,
start: function() { start: function() {
this.addChannelListener('vAPI', this.builtinListener.bind(this)); this.addChannelListener('vAPI', this.builtinListener);
if ( this.toggleListenerCallback === null ) { if ( this.toggleListenerCallback === null ) {
this.toggleListenerCallback = this.toggleListener.bind(this); this.toggleListenerCallback = this.toggleListener.bind(this);
} }
@ -277,14 +258,11 @@ vAPI.messaging = {
window.removeEventListener('pageshow', this.toggleListenerCallback, true); window.removeEventListener('pageshow', this.toggleListenerCallback, true);
} }
this.disconnect(); this.disconnect();
this.channels = Object.create(null); this.channels.clear();
this.channelCount = 0;
// service pending callbacks // service pending callbacks
var pending = this.pending, callback; var pending = this.pending;
this.pending = Object.create(null); this.pending = new Map();
this.pendingCount = 0; for ( var callback of pending.values() ) {
for ( var auxId in pending ) {
callback = pending[auxId];
if ( typeof callback === 'function' ) { if ( typeof callback === 'function' ) {
callback(null); callback(null);
} }
@ -307,17 +285,11 @@ vAPI.messaging = {
send: function(channelName, message, callback) { send: function(channelName, message, callback) {
// User stylesheets are handled content-side on legacy Firefox. // User stylesheets are handled content-side on legacy Firefox.
if ( channelName === 'vapi-background' && message.what === 'userCSS' ) { if ( channelName === 'vapi' && message.what === 'userCSS' ) {
return processUserCSS(message, callback); return processUserCSS(message, callback);
} }
this.sendTo(channelName, message, undefined, undefined, callback);
},
sendTo: function(channelName, message, toTabId, toChannel, callback) {
if ( !this.connected ) { if ( !this.connected ) {
if ( typeof callback === 'function' ) { if ( typeof callback === 'function' ) { callback(); }
callback();
}
return; return;
} }
// Too large a gap between the last request and the last response means // Too large a gap between the last request and the last response means
@ -331,67 +303,57 @@ vAPI.messaging = {
var auxProcessId; var auxProcessId;
if ( callback ) { if ( callback ) {
auxProcessId = this.auxProcessId++; auxProcessId = this.auxProcessId++;
this.pending[auxProcessId] = callback; this.pending.set(auxProcessId, callback);
this.pendingCount += 1;
} }
sendAsyncMessage('ublock0:background', { sendAsyncMessage('ublock0:background', {
channelName: self._sandboxId_ + '|' + channelName, channelName: self._sandboxId_ + '|' + channelName,
auxProcessId: auxProcessId, auxProcessId: auxProcessId,
toTabId: toTabId,
toChannel: toChannel,
msg: message msg: message
}); });
}, },
addChannelListener: function(channelName, callback) { // TODO: implement as time permits.
if ( typeof callback !== 'function' ) { connectTo: function(from, to, handler) {
return; handler({
} what: 'connectionRefused',
var listeners = this.channels[channelName]; from: from,
if ( listeners !== undefined && listeners.indexOf(callback) !== -1 ) { to: to
console.error('Duplicate listener on channel "%s"', channelName); });
return; },
}
disconnectFrom: function() {
},
sendTo: function() {
},
addChannelListener: function(channelName, listener) {
var listeners = this.channels.get(channelName);
if ( listeners === undefined ) { if ( listeners === undefined ) {
this.channels[channelName] = [callback]; this.channels.set(channelName, [ listener ]);
this.channelCount += 1; } else if ( listeners.indexOf(listener) === -1 ) {
} else { listeners.push(listener);
listeners.push(callback);
} }
this.connect(); this.connect();
}, },
removeChannelListener: function(channelName, callback) { removeChannelListener: function(channelName, listener) {
if ( typeof callback !== 'function' ) { var listeners = this.channels.get(channelName);
return; if ( listeners === undefined ) { return; }
} var pos = this.listeners.indexOf(listener);
var listeners = this.channels[channelName]; if ( pos === -1 ) { return; }
if ( listeners === undefined ) {
return;
}
var pos = this.listeners.indexOf(callback);
if ( pos === -1 ) {
console.error('Listener not found on channel "%s"', channelName);
return;
}
listeners.splice(pos, 1); listeners.splice(pos, 1);
if ( listeners.length === 0 ) { if ( listeners.length === 0 ) {
delete this.channels[channelName]; this.channels.delete(channelName);
this.channelCount -= 1;
} }
}, },
removeAllChannelListeners: function(channelName) { removeAllChannelListeners: function(channelName) {
var listeners = this.channels[channelName]; this.channels.delete(channelName);
if ( listeners === undefined ) {
return;
}
delete this.channels[channelName];
this.channelCount -= 1;
}, },
sendToChannelListeners: function(channelName, msg) { sendToChannelListeners: function(channelName, msg) {
var listeners = this.channels[channelName]; var listeners = this.channels.get(channelName);
if ( listeners === undefined ) { return; } if ( listeners === undefined ) { return; }
listeners = listeners.slice(0); listeners = listeners.slice(0);
var response; var response;

View File

@ -33,7 +33,7 @@ vAPI.userStylesheet = {
removed: new Set(), removed: new Set(),
apply: function() { apply: function() {
if ( this.added.size === 0 && this.removed.size === 0 ) { return; } if ( this.added.size === 0 && this.removed.size === 0 ) { return; }
vAPI.messaging.send('vapi-background', { vAPI.messaging.send('vapi', {
what: 'userCSS', what: 'userCSS',
add: Array.from(this.added), add: Array.from(this.added),
remove: Array.from(this.removed) remove: Array.from(this.removed)

View File

@ -28,16 +28,23 @@
background-color: #fee; background-color: #fee;
} }
#domInspector li > * { #domInspector li > * {
font-size: 0.8rem;
display: inline-block;
line-height: 1.2;
margin-right: 1em; margin-right: 1em;
vertical-align: middle;
}
#domInspector li > span {
color: #aaa;
} }
#domInspector li > span:first-child { #domInspector li > span:first-child {
color: #000; color: #000;
cursor: default; cursor: default;
display: inline-block; font-size: 1rem;
margin-right: 0; margin-right: 0;
opacity: 0.5; opacity: 0.5;
padding: 0 4px 0 1px;
visibility: hidden; visibility: hidden;
width: 1em;
} }
#domInspector li > span:first-child:hover { #domInspector li > span:first-child:hover {
opacity: 1; opacity: 1;
@ -54,30 +61,51 @@
} }
#domInspector li.branch.show > span:first-child:before { #domInspector li.branch.show > span:first-child:before {
content: '\25be'; content: '\25be';
visibility: visible;
} }
#domInspector li.branch.hasCosmeticHide > span:first-child:before { #domInspector li.branch.hasCosmeticHide > span:first-child:before {
color: red; color: red;
} }
#domInspector li > code { #domInspector li > code {
cursor: pointer; cursor: pointer;
font: 12px/1.4 monospace; font-family: monospace;
overflow: hidden;
text-overflow: ellipsis;
} }
#domInspector li > code.off { #domInspector li > code.off {
text-decoration: line-through; text-decoration: line-through;
} }
#domInspector li > span {
color: #aaa;
}
#domInspector li > code.filter { #domInspector li > code.filter {
color: red; color: red;
} }
#domInspector li > ul { #domInspector li > ul {
display: block;
}
#domInspector li:not(.hasCosmeticHide):not(.isCosmeticHide):not(.show) > ul {
display: none; display: none;
} }
#domInspector li.show > ul {
#domInspector.vCompact li:not(.hasCosmeticHide):not(.isCosmeticHide) {
display: none;
}
#domInspector #domTree > li {
display: block; display: block;
} }
#domInspector.vCompact ul {
display: block;
}
#domInspector li > ul > li:not(.hasCosmeticHide):not(.isCosmeticHide) {
display: none;
}
#domInspector li.show > ul > li:not(.hasCosmeticHide):not(.isCosmeticHide) {
display: block;
}
#domInspector li:not(.hasCosmeticHide):not(.isCosmeticHide) {
display: block;
}
#domInspector.hCompact li > code:first-of-type {
max-width: 12em;
}
#cosmeticFilteringDialog .dialog { #cosmeticFilteringDialog .dialog {
text-align: center; text-align: center;

View File

@ -60,6 +60,7 @@ textarea {
#inspectors { #inspectors {
bottom: 0; bottom: 0;
font: 13px sans-serif;
position: absolute; position: absolute;
top: 0; top: 0;
width: 100%; width: 100%;
@ -80,18 +81,22 @@ textarea {
width: 100%; width: 100%;
} }
#netInspector { .vCompactToggler.button:before {
font: 13px sans-serif;
}
#inspectors.dom #netInspector {
display: none;
}
#netInspector #compactViewToggler.button:before {
content: '\f102'; content: '\f102';
} }
#netInspector.compactView #compactViewToggler.button:before { .vCompact .vCompactToggler.button:before {
content: '\f103'; content: '\f103';
} }
.hCompactToggler.button:before {
content: '\f100';
}
.hCompact .hCompactToggler.button:before {
content: '\f101';
}
#inspectors.dom #netInspector {
display: none;
}
#netInspector #filterButton { #netInspector #filterButton {
opacity: 0.25; opacity: 0.25;
} }
@ -190,7 +195,7 @@ body #netInspector td {
#netInspector tr td:last-of-type { #netInspector tr td:last-of-type {
border-right: none; border-right: none;
} }
#netInspector.compactView td { #netInspector.vCompact td {
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;

View File

@ -32,7 +32,11 @@
var showdomButton = uDom.nodeFromId('showdom'); var showdomButton = uDom.nodeFromId('showdom');
// Don't bother if the browser is not modern enough. // Don't bother if the browser is not modern enough.
if ( typeof Map === 'undefined' || Map.polyfill || typeof WeakMap === 'undefined' ) { if (
typeof Map === 'undefined' ||
Map.polyfill ||
typeof WeakMap === 'undefined'
) {
showdomButton.classList.add('disabled'); showdomButton.classList.add('disabled');
return; return;
} }
@ -40,13 +44,10 @@ if ( typeof Map === 'undefined' || Map.polyfill || typeof WeakMap === 'undefined
/******************************************************************************/ /******************************************************************************/
var logger = self.logger; var logger = self.logger;
var messaging = vAPI.messaging; var inspectorConnectionId;
var inspectedTabId = ''; var inspectedTabId = '';
var inspectedURL = ''; var inspectedURL = '';
var inspectedHostname = ''; var inspectedHostname = '';
var pollTimer = null;
var fingerprint = null;
var inspector = uDom.nodeFromId('domInspector'); var inspector = uDom.nodeFromId('domInspector');
var domTree = uDom.nodeFromId('domTree'); var domTree = uDom.nodeFromId('domTree');
var tabSelector = uDom.nodeFromId('pageSelector'); var tabSelector = uDom.nodeFromId('pageSelector');
@ -55,13 +56,45 @@ var filterToIdMap = new Map();
/******************************************************************************/ /******************************************************************************/
var messaging = vAPI.messaging;
messaging.addChannelListener('loggerUI', function(msg) {
switch ( msg.what ) {
case 'connectionBroken':
if ( inspectorConnectionId === msg.id ) {
filterToIdMap.clear();
logger.removeAllChildren(domTree);
inspectorConnectionId = undefined;
}
injectInspector();
break;
case 'connectionMessage':
if ( msg.payload.what === 'domLayoutFull' ) {
inspectedURL = msg.payload.url;
inspectedHostname = msg.payload.hostname;
renderDOMFull(msg.payload);
} else if ( msg.payload.what === 'domLayoutIncremental' ) {
renderDOMIncremental(msg.payload);
}
break;
case 'connectionRequested':
if ( msg.from !== 'domInspector' ) { return false; }
if ( msg.tabId !== inspectedTabId ) { return false; }
filterToIdMap.clear();
logger.removeAllChildren(domTree);
inspectorConnectionId = msg.id;
return true;
}
});
/******************************************************************************/
var nodeFromDomEntry = function(entry) { var nodeFromDomEntry = function(entry) {
var node, value; var node, value;
var li = document.createElement('li'); var li = document.createElement('li');
li.setAttribute('id', entry.nid); li.setAttribute('id', entry.nid);
// expander/collapser // expander/collapser
node = document.createElement('span'); li.appendChild(document.createElement('span'));
li.appendChild(node);
// selector // selector
node = document.createElement('code'); node = document.createElement('code');
node.textContent = entry.sel; node.textContent = entry.sel;
@ -190,16 +223,14 @@ var renderDOMIncremental = function(response) {
// 1 = node added // 1 = node added
// -1 = node removed // -1 = node removed
var journal = response.journal; var journal = response.journal;
var nodes = response.nodes; var nodes = new Map(response.nodes);
var entry, previous, li, ul; var entry, previous, li, ul;
for ( var i = 0, n = journal.length; i < n; i++ ) { for ( var i = 0, n = journal.length; i < n; i++ ) {
entry = journal[i]; entry = journal[i];
// Remove node // Remove node
if ( entry.what === -1 ) { if ( entry.what === -1 ) {
li = document.getElementById(entry.nid); li = document.getElementById(entry.nid);
if ( li === null ) { if ( li === null ) { continue; }
continue;
}
patchIncremental(li, -1); patchIncremental(li, -1);
li.parentNode.removeChild(li); li.parentNode.removeChild(li);
continue; continue;
@ -218,7 +249,7 @@ var renderDOMIncremental = function(response) {
continue; continue;
} }
ul = previous.parentElement; ul = previous.parentElement;
li = nodeFromDomEntry(nodes[entry.nid]); li = nodeFromDomEntry(nodes.get(entry.nid));
ul.insertBefore(li, previous.nextElementSibling); ul.insertBefore(li, previous.nextElementSibling);
patchIncremental(li, 1); patchIncremental(li, 1);
continue; continue;
@ -237,7 +268,7 @@ var renderDOMIncremental = function(response) {
li.appendChild(ul); li.appendChild(ul);
li.classList.add('branch'); li.classList.add('branch');
} }
li = nodeFromDomEntry(nodes[entry.nid]); li = nodeFromDomEntry(nodes.get(entry.nid));
ul.appendChild(li); ul.appendChild(li);
patchIncremental(li, 1); patchIncremental(li, 1);
continue; continue;
@ -350,7 +381,7 @@ var startDialog = (function() {
}; };
})(); })();
var onClick = function(ev) { var onClicked = function(ev) {
var target = ev.target; var target = ev.target;
// click outside the dialog proper // click outside the dialog proper
@ -367,83 +398,51 @@ var startDialog = (function() {
} }
}; };
var onCooked = function(entries) { var showCommitted = function() {
if ( Array.isArray(entries) === false ) { messaging.sendTo(inspectorConnectionId, {
return; what: 'showCommitted',
hide: hideSelectors.join(',\n'),
unhide: unhideSelectors.join(',\n')
});
};
var showInteractive = function() {
messaging.sendTo(inspectorConnectionId, {
what: 'showInteractive',
hide: hideSelectors.join(',\n'),
unhide: unhideSelectors.join(',\n')
});
};
var start = function() {
hideSelectors = [];
textarea.addEventListener('input', onInputChanged);
var node;
for ( node of domTree.querySelectorAll('code.off') ) {
if ( node.classList.contains('filter') === false ) {
hideSelectors.push(selectorFromNode(node));
}
} }
hideSelectors = entries; var taValue = [];
var taValue = [], i, node;
var d = new Date(); var d = new Date();
taValue.push('! ' + d.toLocaleString() + ' ' + inspectedURL); taValue.push('! ' + d.toLocaleString() + ' ' + inspectedURL);
for ( i = 0; i < entries.length; i++ ) { for ( var selector of hideSelectors ) {
taValue.push(inspectedHostname + '##' + entries[i]); taValue.push(inspectedHostname + '##' + selector);
} }
var ids = new Set(), id; var ids = new Set(), id;
var nodes = domTree.querySelectorAll('code.filter.off'); for ( node of domTree.querySelectorAll('code.filter.off') ) {
for ( i = 0; i < nodes.length; i++ ) {
node = nodes[i];
id = node.getAttribute('data-filter-id'); id = node.getAttribute('data-filter-id');
if ( ids.has(id) ) { if ( ids.has(id) ) { continue; }
continue;
}
ids.add(id); ids.add(id);
unhideSelectors.push(node.textContent); unhideSelectors.push(node.textContent);
taValue.push(inspectedHostname + '#@#' + node.textContent); taValue.push(inspectedHostname + '#@#' + node.textContent);
} }
textarea.value = taValue.join('\n'); textarea.value = taValue.join('\n');
document.body.appendChild(dialog); document.body.appendChild(dialog);
dialog.addEventListener('click', onClick, true); dialog.addEventListener('click', onClicked, true);
showCommitted(); showCommitted();
}; };
var showCommitted = function() {
messaging.sendTo(
'loggerUI',
{
what: 'showCommitted',
hide: hideSelectors.join(',\n'),
unhide: unhideSelectors.join(',\n')
},
inspectedTabId,
'domInspector'
);
};
var showInteractive = function() {
messaging.sendTo(
'loggerUI',
{
what: 'showInteractive',
hide: hideSelectors.join(',\n'),
unhide: unhideSelectors.join(',\n')
},
inspectedTabId,
'domInspector'
);
};
var start = function() {
textarea.addEventListener('input', onInputChanged);
var node, entries = [];
var nodes = domTree.querySelectorAll('code.off');
for ( var i = 0; i < nodes.length; i++ ) {
node = nodes[i];
if ( node.classList.contains('filter') === false ) {
entries.push({
nid: nidFromNode(node),
selector: selectorFromNode(node)
});
}
}
messaging.sendTo(
'loggerUI',
{ what: 'cookFilters', entries: entries },
inspectedTabId,
'domInspector',
onCooked
);
};
var stop = function() { var stop = function() {
if ( inputTimer !== null ) { if ( inputTimer !== null ) {
clearTimeout(inputTimer); clearTimeout(inputTimer);
@ -453,7 +452,7 @@ var startDialog = (function() {
hideSelectors = []; hideSelectors = [];
unhideSelectors = []; unhideSelectors = [];
textarea.removeEventListener('input', onInputChanged); textarea.removeEventListener('input', onInputChanged);
dialog.removeEventListener('click', onClick, true); dialog.removeEventListener('click', onClicked, true);
document.body.removeChild(dialog); document.body.removeChild(dialog);
}; };
@ -462,12 +461,10 @@ var startDialog = (function() {
/******************************************************************************/ /******************************************************************************/
var onClick = function(ev) { var onClicked = function(ev) {
ev.stopPropagation(); ev.stopPropagation();
if ( inspectedTabId === '' ) { if ( inspectedTabId === '' ) { return; }
return;
}
var target = ev.target; var target = ev.target;
var parent = target.parentElement; var parent = target.parentElement;
@ -479,30 +476,28 @@ var onClick = function(ev) {
parent.classList.contains('branch') && parent.classList.contains('branch') &&
target === parent.firstElementChild target === parent.firstElementChild
) { ) {
target.parentElement.classList.toggle('show'); var state = parent.classList.toggle('show');
if ( !state ) {
for ( var node of parent.querySelectorAll('.branch') ) {
node.classList.remove('show');
}
}
return; return;
} }
// Not a node or filter // Not a node or filter
if ( target.localName !== 'code' ) { if ( target.localName !== 'code' ) { return; }
return;
}
// Toggle cosmetic filter // Toggle cosmetic filter
if ( target.classList.contains('filter') ) { if ( target.classList.contains('filter') ) {
messaging.sendTo( messaging.sendTo(inspectorConnectionId, {
'loggerUI', what: 'toggleFilter',
{ original: false,
what: 'toggleFilter', target: target.classList.toggle('off'),
original: false, selector: selectorFromNode(target),
target: target.classList.toggle('off'), filter: selectorFromFilter(target),
selector: selectorFromNode(target), nid: nidFromNode(target)
filter: selectorFromFilter(target), });
nid: ''
},
inspectedTabId,
'domInspector'
);
uDom('[data-filter-id="' + target.getAttribute('data-filter-id') + '"]', inspector).toggleClass( uDom('[data-filter-id="' + target.getAttribute('data-filter-id') + '"]', inspector).toggleClass(
'off', 'off',
target.classList.contains('off') target.classList.contains('off')
@ -510,18 +505,13 @@ var onClick = function(ev) {
} }
// Toggle node // Toggle node
else { else {
messaging.sendTo( messaging.sendTo(inspectorConnectionId, {
'loggerUI', what: 'toggleNodes',
{ original: true,
what: 'toggleNodes', target: target.classList.toggle('off') === false,
original: true, selector: selectorFromNode(target),
target: target.classList.toggle('off') === false, nid: nidFromNode(target)
selector: selectorFromNode(target), });
nid: nidFromNode(target)
},
inspectedTabId,
'domInspector'
);
} }
var cantCreate = domTree.querySelector('.off') === null; var cantCreate = domTree.querySelector('.off') === null;
@ -537,38 +527,25 @@ var onMouseOver = (function() {
var timerHandler = function() { var timerHandler = function() {
mouseoverTimer = null; mouseoverTimer = null;
messaging.sendTo( messaging.sendTo(inspectorConnectionId, {
'loggerUI', what: 'highlightOne',
{ selector: selectorFromNode(mouseoverTarget),
what: 'highlightOne', nid: nidFromNode(mouseoverTarget),
selector: selectorFromNode(mouseoverTarget), scrollTo: true
nid: nidFromNode(mouseoverTarget), });
scrollTo: true
},
inspectedTabId,
'domInspector'
);
}; };
return function(ev) { return function(ev) {
if ( inspectedTabId === '' ) { if ( inspectedTabId === '' ) { return; }
return;
}
// Convenience: skip real-time highlighting if shift key is pressed. // Convenience: skip real-time highlighting if shift key is pressed.
if ( ev.shiftKey ) { if ( ev.shiftKey ) { return; }
return;
}
// Find closest `li` // Find closest `li`
var target = ev.target; var target = ev.target;
while ( target !== null ) { while ( target !== null ) {
if ( target.localName === 'li' ) { if ( target.localName === 'li' ) { break; }
break;
}
target = target.parentElement; target = target.parentElement;
} }
if ( target === mouseoverTarget ) { if ( target === mouseoverTarget ) { return; }
return;
}
mouseoverTarget = target; mouseoverTarget = target;
if ( mouseoverTimer === null ) { if ( mouseoverTimer === null ) {
mouseoverTimer = vAPI.setTimeout(timerHandler, 50); mouseoverTimer = vAPI.setTimeout(timerHandler, 50);
@ -579,121 +556,33 @@ var onMouseOver = (function() {
/******************************************************************************/ /******************************************************************************/
var currentTabId = function() { var currentTabId = function() {
if ( showdomButton.classList.contains('active') === false ) { if ( showdomButton.classList.contains('active') === false ) { return ''; }
return '';
}
var tabId = logger.tabIdFromClassName(tabSelector.value) || ''; var tabId = logger.tabIdFromClassName(tabSelector.value) || '';
return tabId !== 'bts' ? tabId : ''; return tabId !== 'bts' ? tabId : '';
}; };
/******************************************************************************/ /******************************************************************************/
var fetchDOMAsync = (function() {
var onFetched = function(response) {
if ( !response || currentTabId() !== inspectedTabId ) {
shutdownInspector();
injectInspectorAsync(250);
return;
}
switch ( response.status ) {
case 'full':
renderDOMFull(response);
fingerprint = response.fingerprint;
inspectedURL = response.url;
inspectedHostname = response.hostname;
break;
case 'incremental':
renderDOMIncremental(response);
break;
case 'nochange':
case 'busy':
break;
default:
break;
}
fetchDOMAsync();
};
var onTimeout = function() {
pollTimer = null;
messaging.sendTo(
'loggerUI',
{
what: 'domLayout',
fingerprint: fingerprint
},
inspectedTabId,
'domInspector',
onFetched
);
};
// Poll for DOM layout data every ~2 seconds at most
return function(delay) {
if ( pollTimer === null ) {
pollTimer = vAPI.setTimeout(onTimeout, delay || 2003);
}
};
})();
/******************************************************************************/
var injectInspector = function() { var injectInspector = function() {
var tabId = currentTabId(); var tabId = currentTabId();
// No valid tab, go back if ( tabId === '' ) { return; }
if ( tabId === '' ) {
injectInspectorAsync();
return;
}
inspectedTabId = tabId; inspectedTabId = tabId;
fingerprint = null; messaging.send('loggerUI', {
messaging.send( what: 'scriptlet',
'loggerUI', tabId: tabId,
{ scriptlet: 'dom-inspector'
what: 'scriptlet', });
tabId: tabId,
scriptlet: 'dom-inspector'
}
);
fetchDOMAsync(250);
};
/******************************************************************************/
var injectInspectorAsync = function(delay) {
if ( pollTimer !== null ) {
return;
}
if ( showdomButton.classList.contains('active') === false ) {
return;
}
pollTimer = vAPI.setTimeout(function() {
pollTimer = null;
injectInspector();
}, delay || 1001);
}; };
/******************************************************************************/ /******************************************************************************/
var shutdownInspector = function() { var shutdownInspector = function() {
if ( inspectedTabId !== '' ) { if ( inspectorConnectionId !== undefined ) {
messaging.sendTo( messaging.disconnectFrom(inspectorConnectionId);
'loggerUI', inspectorConnectionId = undefined;
{ what: 'shutdown' },
inspectedTabId,
'domInspector'
);
} }
logger.removeAllChildren(domTree); logger.removeAllChildren(domTree);
if ( pollTimer !== null ) { inspector.classList.add('vCompact');
clearTimeout(pollTimer);
pollTimer = null;
}
inspectedTabId = ''; inspectedTabId = '';
}; };
@ -702,34 +591,38 @@ var shutdownInspector = function() {
var onTabIdChanged = function() { var onTabIdChanged = function() {
if ( inspectedTabId !== currentTabId() ) { if ( inspectedTabId !== currentTabId() ) {
shutdownInspector(); shutdownInspector();
injectInspectorAsync(250); injectInspector();
} }
}; };
/******************************************************************************/ /******************************************************************************/
var toggleVCompactView = function() {
var state = !inspector.classList.toggle('vCompact');
var branches = document.querySelectorAll('#domInspector li.branch');
for ( var branch of branches ) {
branch.classList.toggle('show', state);
}
};
var toggleHCompactView = function() {
inspector.classList.toggle('hCompact');
};
/******************************************************************************/
var toggleHighlightMode = function() { var toggleHighlightMode = function() {
messaging.sendTo( messaging.sendTo(inspectorConnectionId, {
'loggerUI', what: 'highlightMode',
{ invert: uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').classList.toggle('invert')
what: 'highlightMode', });
invert: uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').classList.toggle('invert')
},
inspectedTabId,
'domInspector'
);
}; };
/******************************************************************************/ /******************************************************************************/
var revert = function() { var revert = function() {
uDom('#domTree .off').removeClass('off'); uDom('#domTree .off').removeClass('off');
messaging.sendTo( messaging.sendTo(inspectorConnectionId, { what: 'resetToggledNodes' });
'loggerUI',
{ what: 'resetToggledNodes' },
inspectedTabId,
'domInspector'
);
inspector.querySelector('.permatoolbar .revert').classList.add('disabled'); inspector.querySelector('.permatoolbar .revert').classList.add('disabled');
inspector.querySelector('.permatoolbar .commit').classList.add('disabled'); inspector.querySelector('.permatoolbar .commit').classList.add('disabled');
}; };
@ -739,8 +632,10 @@ var revert = function() {
var toggleOn = function() { var toggleOn = function() {
window.addEventListener('beforeunload', toggleOff); window.addEventListener('beforeunload', toggleOff);
tabSelector.addEventListener('change', onTabIdChanged); tabSelector.addEventListener('change', onTabIdChanged);
domTree.addEventListener('click', onClick, true); domTree.addEventListener('click', onClicked, true);
domTree.addEventListener('mouseover', onMouseOver, true); domTree.addEventListener('mouseover', onMouseOver, true);
uDom.nodeFromSelector('#domInspector .vCompactToggler').addEventListener('click', toggleVCompactView);
uDom.nodeFromSelector('#domInspector .hCompactToggler').addEventListener('click', toggleHCompactView);
uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').addEventListener('click', toggleHighlightMode); uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').addEventListener('click', toggleHighlightMode);
uDom.nodeFromSelector('#domInspector .permatoolbar .revert').addEventListener('click', revert); uDom.nodeFromSelector('#domInspector .permatoolbar .revert').addEventListener('click', revert);
uDom.nodeFromSelector('#domInspector .permatoolbar .commit').addEventListener('click', startDialog); uDom.nodeFromSelector('#domInspector .permatoolbar .commit').addEventListener('click', startDialog);
@ -753,8 +648,10 @@ var toggleOff = function() {
shutdownInspector(); shutdownInspector();
window.removeEventListener('beforeunload', toggleOff); window.removeEventListener('beforeunload', toggleOff);
tabSelector.removeEventListener('change', onTabIdChanged); tabSelector.removeEventListener('change', onTabIdChanged);
domTree.removeEventListener('click', onClick, true); domTree.removeEventListener('click', onClicked, true);
domTree.removeEventListener('mouseover', onMouseOver, true); domTree.removeEventListener('mouseover', onMouseOver, true);
uDom.nodeFromSelector('#domInspector .vCompactToggler').removeEventListener('click', toggleVCompactView);
uDom.nodeFromSelector('#domInspector .hCompactToggler').removeEventListener('click', toggleHCompactView);
uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').removeEventListener('click', toggleHighlightMode); uDom.nodeFromSelector('#domInspector .permatoolbar .highlightMode').removeEventListener('click', toggleHighlightMode);
uDom.nodeFromSelector('#domInspector .permatoolbar .revert').removeEventListener('click', revert); uDom.nodeFromSelector('#domInspector .permatoolbar .revert').removeEventListener('click', revert);
uDom.nodeFromSelector('#domInspector .permatoolbar .commit').removeEventListener('click', startDialog); uDom.nodeFromSelector('#domInspector .permatoolbar .commit').removeEventListener('click', startDialog);

View File

@ -412,12 +412,8 @@ var synchronizeTabIds = function(newTabIds) {
var rowVoided = false; var rowVoided = false;
var trs; var trs;
for ( var tabId in oldTabIds ) { for ( var tabId in oldTabIds ) {
if ( oldTabIds.hasOwnProperty(tabId) === false ) { if ( oldTabIds.hasOwnProperty(tabId) === false ) { continue; }
continue; if ( newTabIds.hasOwnProperty(tabId) ) { continue; }
}
if ( newTabIds.hasOwnProperty(tabId) ) {
continue;
}
// Mark or remove voided rows // Mark or remove voided rows
trs = uDom('.tab_' + tabId); trs = uDom('.tab_' + tabId);
if ( autoDeleteVoidRows ) { if ( autoDeleteVoidRows ) {
@ -440,9 +436,7 @@ var synchronizeTabIds = function(newTabIds) {
var option; var option;
for ( var i = 0, j = 2; i < tabIds.length; i++ ) { for ( var i = 0, j = 2; i < tabIds.length; i++ ) {
tabId = tabIds[i]; tabId = tabIds[i];
if ( tabId === noTabId ) { if ( tabId === noTabId ) { continue; }
continue;
}
option = select.options[j]; option = select.options[j];
if ( !option ) { if ( !option ) {
option = document.createElement('option'); option = document.createElement('option');
@ -1515,8 +1509,8 @@ var cleanBuffer = function() {
/******************************************************************************/ /******************************************************************************/
var toggleCompactView = function() { var toggleVCompactView = function() {
uDom.nodeFromId('netInspector').classList.toggle('compactView'); uDom.nodeFromId('netInspector').classList.toggle('vCompact');
}; };
/******************************************************************************/ /******************************************************************************/
@ -1646,7 +1640,7 @@ uDom('#pageSelector').on('change', pageSelectorChanged);
uDom('#refresh').on('click', reloadTab); uDom('#refresh').on('click', reloadTab);
uDom('#showdom').on('click', toggleInspectors); uDom('#showdom').on('click', toggleInspectors);
uDom('#compactViewToggler').on('click', toggleCompactView); uDom('#netInspector .vCompactToggler').on('click', toggleVCompactView);
uDom('#clean').on('click', cleanBuffer); uDom('#clean').on('click', cleanBuffer);
uDom('#clear').on('click', clearBuffer); uDom('#clear').on('click', clearBuffer);
uDom('#maxEntries').on('change', onMaxEntriesChanged); uDom('#maxEntries').on('change', onMaxEntriesChanged);

View File

@ -137,6 +137,8 @@ var cssEscape = (function(/*root*/) {
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
var loggerConnectionId;
// Highlighter-related // Highlighter-related
var svgRoot = null; var svgRoot = null;
var pickerRoot = null; var pickerRoot = null;
@ -153,29 +155,16 @@ var reHasCSSCombinators = /[ >+~]/;
/******************************************************************************/ /******************************************************************************/
// Some kind of fingerprint for the DOM, without incurring too much overhead.
var domFingerprint = function() {
return sessionId;
};
/******************************************************************************/
var domLayout = (function() { var domLayout = (function() {
var skipTagNames = { var skipTagNames = new Set([
'br': true, 'br', 'head', 'link', 'meta', 'script', 'style', 'title'
'link': true, ]);
'meta': true, var resourceAttrNames = new Map([
'script': true, [ 'a', 'href' ],
'style': true [ 'iframe', 'src' ],
}; [ 'img', 'src' ],
[ 'object', 'data' ]
var resourceAttrNames = { ]);
'a': 'href',
'iframe': 'src',
'img': 'src',
'object': 'data'
};
var idGenerator = 0; var idGenerator = 0;
@ -206,11 +195,15 @@ var domLayout = (function() {
} }
} }
// Tag-specific attributes // Tag-specific attributes
if ( resourceAttrNames.hasOwnProperty(tag) ) { attr = resourceAttrNames.get(tag);
attr = resourceAttrNames[tag]; if ( attr !== undefined ) {
str = node.getAttribute(attr) || ''; str = node.getAttribute(attr) || '';
str = str.trim(); str = str.trim();
pos = str.indexOf('#'); if ( str.startsWith('data:') ) {
pos = 5;
} else {
pos = str.search(/[#?]/);
}
if ( pos !== -1 ) { if ( pos !== -1 ) {
str = str.slice(0, pos); str = str.slice(0, pos);
sw = '^'; sw = '^';
@ -242,13 +235,9 @@ var domLayout = (function() {
var domNodeFactory = function(level, node) { var domNodeFactory = function(level, node) {
var localName = node.localName; var localName = node.localName;
if ( skipTagNames.hasOwnProperty(localName) ) { if ( skipTagNames.has(localName) ) { return null; }
return null;
}
// skip uBlock's own nodes // skip uBlock's own nodes
if ( node.classList.contains(sessionId) ) { if ( node.classList.contains(sessionId) ) { return null; }
return null;
}
if ( level === 0 && localName === 'body' ) { if ( level === 0 && localName === 'body' ) {
return new DomRoot(); return new DomRoot();
} }
@ -260,7 +249,7 @@ var domLayout = (function() {
var getLayoutData = function() { var getLayoutData = function() {
var layout = []; var layout = [];
var stack = []; var stack = [];
var node = document.body; var node = document.documentElement;
var domNode; var domNode;
var lvl = 0; var lvl = 0;
@ -324,37 +313,31 @@ var domLayout = (function() {
return layout; return layout;
}; };
// Track and report mutations to the DOM // Track and report mutations of the DOM
var mutationObserver = null; var mutationObserver = null;
var mutationTimer = null; var mutationTimer;
var addedNodelists = []; var addedNodelists = [];
var removedNodelist = []; var removedNodelist = [];
var journalEntries = [];
var journalNodes = Object.create(null);
var previousElementSiblingId = function(node) { var previousElementSiblingId = function(node) {
var sibling = node; var sibling = node;
for (;;) { for (;;) {
sibling = sibling.previousElementSibling; sibling = sibling.previousElementSibling;
if ( sibling === null ) { if ( sibling === null ) { return null; }
return null; if ( skipTagNames.has(sibling.localName) ) { continue; }
}
if ( skipTagNames.hasOwnProperty(sibling.localName) ) {
continue;
}
return nodeToIdMap.get(sibling); return nodeToIdMap.get(sibling);
} }
}; };
var journalFromBranch = function(root, added) { var journalFromBranch = function(root, newNodes, newNodeToIdMap) {
var domNode; var domNode;
var node = root.firstElementChild; var node = root.firstElementChild;
while ( node !== null ) { while ( node !== null ) {
domNode = domNodeFactory(undefined, node); domNode = domNodeFactory(undefined, node);
if ( domNode !== null ) { if ( domNode !== null ) {
journalNodes[domNode.nid] = domNode; newNodeToIdMap.set(domNode.nid, domNode);
added.push(node); newNodes.push(node);
} }
// down // down
if ( node.firstElementChild !== null ) { if ( node.firstElementChild !== null ) {
@ -368,9 +351,7 @@ var domLayout = (function() {
} }
// up then right // up then right
for (;;) { for (;;) {
if ( node.parentElement === root ) { if ( node.parentElement === root ) { return; }
return;
}
node = node.parentElement; node = node.parentElement;
if ( node.nextElementSibling !== null ) { if ( node.nextElementSibling !== null ) {
node = node.nextElementSibling; node = node.nextElementSibling;
@ -381,51 +362,33 @@ var domLayout = (function() {
}; };
var journalFromMutations = function() { var journalFromMutations = function() {
mutationTimer = null; var nodelist, node, domNode, nid;
if ( mutationObserver === null ) {
addedNodelists = [];
removedNodelist = [];
return;
}
var i, m, nodelist, j, n, node, domNode, nid;
// This is used to temporarily hold all added nodes, before resolving // This is used to temporarily hold all added nodes, before resolving
// their node id and relative position. // their node id and relative position.
var added = []; var newNodes = [];
var journalEntries = [];
var newNodeToIdMap = new Map();
for ( i = 0, m = addedNodelists.length; i < m; i++ ) { for ( nodelist of addedNodelists ) {
nodelist = addedNodelists[i]; for ( node of nodelist ) {
for ( j = 0, n = nodelist.length; j < n; j++ ) { if ( node.nodeType !== 1 ) { continue; }
node = nodelist[j]; if ( node.parentElement === null ) { continue; }
if ( node.nodeType !== 1 ) {
continue;
}
// I don't think this can ever happen
if ( node.parentElement === null ) {
continue;
}
cosmeticFilterMapper.incremental(node); cosmeticFilterMapper.incremental(node);
domNode = domNodeFactory(undefined, node); domNode = domNodeFactory(undefined, node);
if ( domNode !== null ) { if ( domNode !== null ) {
journalNodes[domNode.nid] = domNode; newNodeToIdMap.set(domNode.nid, domNode);
added.push(node); newNodes.push(node);
} }
journalFromBranch(node, added); journalFromBranch(node, newNodes, newNodeToIdMap);
} }
} }
addedNodelists = []; addedNodelists = [];
for ( i = 0, m = removedNodelist.length; i < m; i++ ) { for ( nodelist of removedNodelist ) {
nodelist = removedNodelist[i]; for ( node of nodelist ) {
for ( j = 0, n = nodelist.length; j < n; j++ ) { if ( node.nodeType !== 1 ) { continue; }
node = nodelist[j];
if ( node.nodeType !== 1 ) {
continue;
}
nid = nodeToIdMap.get(node); nid = nodeToIdMap.get(node);
if ( nid === undefined ) { if ( nid === undefined ) { continue; }
continue;
}
journalEntries.push({ journalEntries.push({
what: -1, what: -1,
nid: nid nid: nid
@ -433,8 +396,7 @@ var domLayout = (function() {
} }
} }
removedNodelist = []; removedNodelist = [];
for ( i = 0, n = added.length; i < n; i++ ) { for ( node of newNodes ) {
node = added[i];
journalEntries.push({ journalEntries.push({
what: 1, what: 1,
nid: nodeToIdMap.get(node), nid: nodeToIdMap.get(node),
@ -442,12 +404,20 @@ var domLayout = (function() {
l: previousElementSiblingId(node) l: previousElementSiblingId(node)
}); });
} }
if ( journalEntries.length === 0 ) { return; }
vAPI.messaging.sendTo(loggerConnectionId, {
what: 'domLayoutIncremental',
url: window.location.href,
hostname: window.location.hostname,
journal: journalEntries,
nodes: Array.from(newNodeToIdMap)
});
}; };
var onMutationObserved = function(mutationRecords) { var onMutationObserved = function(mutationRecords) {
var record; for ( var record of mutationRecords ) {
for ( var i = 0, n = mutationRecords.length; i < n; i++ ) {
record = mutationRecords[i];
if ( record.addedNodes.length !== 0 ) { if ( record.addedNodes.length !== 0 ) {
addedNodelists.push(record.addedNodes); addedNodelists.push(record.addedNodes);
} }
@ -455,55 +425,27 @@ var domLayout = (function() {
removedNodelist.push(record.removedNodes); removedNodelist.push(record.removedNodes);
} }
} }
if ( mutationTimer === null ) { if ( mutationTimer === undefined ) {
mutationTimer = vAPI.setTimeout(journalFromMutations, 1000); mutationTimer = vAPI.setTimeout(journalFromMutations, 1000);
} }
}; };
// API // API
var getLayout = function(fingerprint) { var getLayout = function() {
if ( fingerprint !== domFingerprint() ) { cosmeticFilterMapper.reset();
reset(); mutationObserver = new MutationObserver(onMutationObserved);
} mutationObserver.observe(document.body, {
childList: true,
subtree: true
});
var response = { return {
what: 'domLayout', what: 'domLayoutFull',
fingerprint: domFingerprint(),
url: window.location.href, url: window.location.href,
hostname: window.location.hostname hostname: window.location.hostname,
layout: patchLayoutData(getLayoutData())
}; };
if ( document.readyState !== 'complete' ) {
response.status = 'busy';
return response;
}
// No mutation observer means we need to send full layout
if ( mutationObserver === null ) {
cosmeticFilterMapper.reset();
mutationObserver = new MutationObserver(onMutationObserved);
mutationObserver.observe(document.body, {
childList: true,
subtree: true
});
response.status = 'full';
response.layout = patchLayoutData(getLayoutData());
return response;
}
// Incremental layout
if ( journalEntries.length !== 0 ) {
response.status = 'incremental';
response.journal = journalEntries;
response.nodes = journalNodes;
journalEntries = [];
journalNodes = Object.create(null);
return response;
}
response.status = 'nochange';
return response;
}; };
var reset = function() { var reset = function() {
@ -511,9 +453,9 @@ var domLayout = (function() {
}; };
var shutdown = function() { var shutdown = function() {
if ( mutationTimer !== null ) { if ( mutationTimer !== undefined ) {
clearTimeout(mutationTimer); clearTimeout(mutationTimer);
mutationTimer = null; mutationTimer = undefined;
} }
if ( mutationObserver !== null ) { if ( mutationObserver !== null ) {
mutationObserver.disconnect(); mutationObserver.disconnect();
@ -521,8 +463,6 @@ var domLayout = (function() {
} }
addedNodelists = []; addedNodelists = [];
removedNodelist = []; removedNodelist = [];
journalEntries = [];
journalNodes = Object.create(null);
nodeToIdMap = new WeakMap(); nodeToIdMap = new WeakMap();
}; };
@ -550,136 +490,6 @@ try {
/******************************************************************************/ /******************************************************************************/
var cosmeticFilterFromEntries = function(entries) {
var out = [];
var entry, i = entries.length;
while ( i-- ) {
entry = entries[i];
out.push(cosmeticFilterFromTarget(entry.nid, entry.selector));
}
return out;
};
/******************************************************************************/
// Extract the best possible cosmetic filter, i.e. as specific as possible.
var cosmeticFilterFromNode = function(elem) {
var tagName = elem.localName;
var prefix = '';
var suffix = [];
var v, i;
// Id
v = typeof elem.id === 'string' && cssEscape(elem.id);
if ( v ) {
suffix.push('#', v);
}
// Class(es)
if ( suffix.length === 0 ) {
v = elem.classList;
if ( v ) {
i = v.length || 0;
while ( i-- ) {
suffix.push('.' + cssEscape(v.item(i)));
}
}
}
// Tag name
if ( suffix.length === 0 ) {
prefix = tagName;
}
// Attributes (depends on tag name)
var attributes = [], attr;
switch ( tagName ) {
case 'a':
v = elem.getAttribute('href');
if ( v ) {
v = v.replace(/\?.*$/, '');
if ( v.length ) {
attributes.push({ k: 'href', v: v });
}
}
break;
case 'img':
v = elem.getAttribute('alt');
if ( v && v.length !== 0 ) {
attributes.push({ k: 'alt', v: v });
}
break;
default:
break;
}
while ( (attr = attributes.pop()) ) {
if ( attr.v.length === 0 ) {
continue;
}
suffix.push('[', attr.k, '="', cssEscape(attr.v, true), '"]');
}
var selector = prefix + suffix.join('');
// https://github.com/chrisaljoudi/uBlock/issues/637
// If the selector is still ambiguous at this point, further narrow using
// `nth-of-type`. It is preferable to use `nth-of-type` as opposed to
// `nth-child`, as `nth-of-type` is less volatile.
var parent = elem.parentElement;
if ( elementsFromSelector(cssScope + selector, parent).length > 1 ) {
i = 1;
while ( elem.previousElementSibling !== null ) {
elem = elem.previousElementSibling;
if ( elem.localName !== tagName ) {
continue;
}
i++;
}
selector += ':nth-of-type(' + i + ')';
}
return selector;
};
/******************************************************************************/
var cosmeticFilterFromTarget = function(nid, coarseSelector) {
var elems = elementsFromSelector(coarseSelector);
var target = null;
var i = elems.length;
while ( i-- ) {
if ( nodeToIdMap.get(elems[i]) === nid ) {
target = elems[i];
break;
}
}
if ( target === null ) {
return coarseSelector;
}
// Find the most concise selector from the target node
var segments = [], segment;
var node = target;
while ( node !== document.body ) {
segment = cosmeticFilterFromNode(node);
segments.unshift(segment);
if ( segment.charAt(0) === '#' ) {
break;
}
node = node.parentElement;
}
var fineSelector = segments.join(' > ');
if ( fineSelector.charAt(0) === '#' ) {
return fineSelector;
}
if ( fineSelector.charAt(0) === '.' && elementsFromSelector(fineSelector).length === 1 ) {
return fineSelector;
}
return 'body > ' + fineSelector;
};
/******************************************************************************/
var cosmeticFilterMapper = (function() { var cosmeticFilterMapper = (function() {
// https://github.com/gorhill/uBlock/issues/546 // https://github.com/gorhill/uBlock/issues/546
var matchesFnName; var matchesFnName;
@ -735,7 +545,6 @@ var cosmeticFilterMapper = (function() {
}; };
var incremental = function(rootNode) { var incremental = function(rootNode) {
vAPI.domFilterer.toggle(false);
nodesFromStyleTag(rootNode); nodesFromStyleTag(rootNode);
}; };
@ -821,13 +630,10 @@ var getSvgRootChildren = function() {
} }
}; };
var highlightElements = function(scrollTo) { var highlightElements = function() {
var wv = pickerRoot.contentWindow.innerWidth;
var hv = pickerRoot.contentWindow.innerHeight;
var islands; var islands;
var elem, rect, poly; var elem, rect, poly;
var xl, xr, yt, yb, w, h, ws; var xl, xr, yt, yb, w, h, ws;
var xlu = Number.MAX_VALUE, xru = 0, ytu = Number.MAX_VALUE, ybu = 0;
var svgRootChildren = getSvgRootChildren(); var svgRootChildren = getSvgRootChildren();
islands = []; islands = [];
@ -914,43 +720,23 @@ var highlightElements = function(scrollTo) {
islands.push(poly); islands.push(poly);
} }
svgRootChildren[3].setAttribute('d', islands.join('') || 'M0 0'); svgRootChildren[3].setAttribute('d', islands.join('') || 'M0 0');
if ( !scrollTo ) {
return;
}
// Highlighted area completely within viewport
if ( xlu >= 0 && xru <= wv && ytu >= 0 && ybu <= hv ) {
return;
}
var dx = 0, dy = 0;
if ( xru > wv ) {
dx = xru - wv;
xlu -= dx;
}
if ( xlu < 0 ) {
dx += xlu;
}
if ( ybu > hv ) {
dy = ybu - hv;
ytu -= dy;
}
if ( ytu < 0 ) {
dy += ytu;
}
if ( dx !== 0 || dy !== 0 ) {
window.scrollBy(dx, dy);
}
}; };
/******************************************************************************/ /******************************************************************************/
var onScrolled = function() { var onScrolled = (function() {
highlightElements(); var buffered = false;
}; var timerHandler = function() {
buffered = false;
highlightElements();
};
return function() {
if ( buffered === false ) {
window.requestAnimationFrame(timerHandler);
buffered = true;
}
};
})();
/******************************************************************************/ /******************************************************************************/
@ -979,17 +765,6 @@ var nodesFromFilter = function(selector) {
/******************************************************************************/ /******************************************************************************/
var shutdown = function() {
cosmeticFilterMapper.shutdown();
domLayout.shutdown();
vAPI.messaging.removeAllChannelListeners('domInspector');
window.removeEventListener('scroll', onScrolled, true);
document.documentElement.removeChild(pickerRoot);
pickerRoot = svgRoot = null;
};
/******************************************************************************/
var toggleExceptions = function(nodes, targetState) { var toggleExceptions = function(nodes, targetState) {
for ( var node of nodes ) { for ( var node of nodes ) {
if ( targetState ) { if ( targetState ) {
@ -1010,25 +785,57 @@ var toggleFilter = function(nodes, targetState) {
} }
}; };
var resetToggledNodes = function() {
rwGreenNodes.clear();
rwRedNodes.clear();
};
// https://www.youtube.com/watch?v=L5jRewnxSBY // https://www.youtube.com/watch?v=L5jRewnxSBY
/******************************************************************************/
var start = function() {
var onReady = function(ev) {
if ( ev ) {
document.removeEventListener(ev.type, onReady);
}
vAPI.messaging.sendTo(loggerConnectionId, domLayout.get());
vAPI.domFilterer.toggle(false);
highlightElements();
};
if ( document.readyState === 'loading' ) {
document.addEventListener('DOMContentLoaded', onReady);
} else {
onReady();
}
};
/******************************************************************************/
var shutdown = function() {
cosmeticFilterMapper.shutdown();
domLayout.shutdown();
vAPI.messaging.disconnectFrom(loggerConnectionId);
window.removeEventListener('scroll', onScrolled, true);
document.documentElement.removeChild(pickerRoot);
pickerRoot = svgRoot = null;
};
/******************************************************************************/ /******************************************************************************/
/******************************************************************************/ /******************************************************************************/
var onMessage = function(request) { var onMessage = function(request) {
var response; var response,
nodes;
switch ( request.what ) { switch ( request.what ) {
case 'commitFilters': case 'commitFilters':
highlightElements(); highlightElements();
break; break;
case 'cookFilters':
response = cosmeticFilterFromEntries(request.entries);
break;
case 'domLayout': case 'domLayout':
response = domLayout.get(request.fingerprint); response = domLayout.get();
highlightElements();
break; break;
case 'highlightMode': case 'highlightMode':
@ -1037,13 +844,18 @@ var onMessage = function(request) {
case 'highlightOne': case 'highlightOne':
blueNodes = selectNodes(request.selector, request.nid); blueNodes = selectNodes(request.selector, request.nid);
highlightElements(request.scrollTo); highlightElements();
break;
case 'resetToggledNodes':
resetToggledNodes();
highlightElements();
break; break;
case 'showCommitted': case 'showCommitted':
blueNodes = []; blueNodes = [];
// TODO: show only the new filters and exceptions. // TODO: show only the new filters and exceptions.
highlightElements(true); highlightElements();
break; break;
case 'showInteractive': case 'showInteractive':
@ -1052,23 +864,17 @@ var onMessage = function(request) {
break; break;
case 'toggleFilter': case 'toggleFilter':
toggleExceptions( nodes = selectNodes(request.selector, request.nid);
nodesFromFilter(request.filter), if ( nodes.length !== 0 ) { nodes[0].scrollIntoView(); }
request.target toggleExceptions(nodesFromFilter(request.filter), request.target);
); highlightElements();
highlightElements(true);
break; break;
case 'toggleNodes': case 'toggleNodes':
toggleFilter( nodes = selectNodes(request.selector, request.nid);
selectNodes(request.selector, request.nid), if ( nodes.length !== 0 ) { nodes[0].scrollIntoView(); }
request.target toggleFilter(nodes, request.target);
); highlightElements();
highlightElements(true);
break;
case 'shutdown':
shutdown();
break; break;
default: default:
@ -1078,42 +884,35 @@ var onMessage = function(request) {
return response; return response;
}; };
var messagingHandler = function(msg) {
switch ( msg.what ) {
case 'connectionAccepted':
loggerConnectionId = msg.id;
start();
break;
case 'connectionBroken':
shutdown();
break;
case 'connectionMessage':
onMessage(msg.payload);
break;
}
};
/******************************************************************************/ /******************************************************************************/
// Install DOM inspector widget // Install DOM inspector widget
pickerRoot = document.createElement('iframe'); var bootstrap = function(ev) {
pickerRoot.classList.add(sessionId); if ( ev ) {
pickerRoot.classList.add('dom-inspector'); pickerRoot.removeEventListener(ev.type, bootstrap);
pickerRoot.style.cssText = [ }
'background: transparent',
'border: 0',
'border-radius: 0',
'box-shadow: none',
'display: block',
'height: 100%',
'left: 0',
'margin: 0',
'opacity: 1',
'position: fixed',
'outline: 0',
'padding: 0',
'top: 0',
'visibility: visible',
'width: 100%',
'z-index: 2147483647',
''
].join(' !important;\n');
pickerRoot.onload = function() {
pickerRoot.onload = null;
var pickerDoc = this.contentDocument; var pickerDoc = this.contentDocument;
var style = pickerDoc.createElement('style'); var style = pickerDoc.createElement('style');
style.textContent = [ style.textContent = [
'body {', 'body {',
'background-color: transparent;', 'background-color: transparent;',
'cursor: not-allowed;',
'}', '}',
'svg {', 'svg {',
'height: 100%;', 'height: 100%;',
@ -1155,9 +954,34 @@ pickerRoot.onload = function() {
cosmeticFilterMapper.reset(); cosmeticFilterMapper.reset();
highlightElements(); highlightElements();
vAPI.messaging.addChannelListener('domInspector', onMessage); vAPI.messaging.connectTo('domInspector', 'loggerUI', messagingHandler);
}; };
pickerRoot = document.createElement('iframe');
pickerRoot.classList.add(sessionId);
pickerRoot.classList.add('dom-inspector');
pickerRoot.style.cssText = [
'background: transparent',
'border: 0',
'border-radius: 0',
'box-shadow: none',
'display: block',
'height: 100%',
'left: 0',
'margin: 0',
'opacity: 1',
'position: fixed',
'outline: 0',
'padding: 0',
'pointer-events:none;',
'top: 0',
'visibility: visible',
'width: 100%',
'z-index: 2147483647',
''
].join(' !important;\n');
pickerRoot.addEventListener('load', bootstrap);
document.documentElement.appendChild(pickerRoot); document.documentElement.appendChild(pickerRoot);
/******************************************************************************/ /******************************************************************************/

View File

@ -579,14 +579,14 @@ var reInvalidHostname = /[^a-z0-9.\-\[\]:]/,
pendingEntries.set(key, new Entry(tabId, scriptlet, callback)); pendingEntries.set(key, new Entry(tabId, scriptlet, callback));
} }
vAPI.tabs.injectScript(tabId, { vAPI.tabs.injectScript(tabId, {
file: 'js/scriptlets/' + scriptlet + '.js' file: '/js/scriptlets/' + scriptlet + '.js'
}); });
}; };
// TODO: think about a callback mechanism. // TODO: think about a callback mechanism.
var injectDeep = function(tabId, scriptlet) { var injectDeep = function(tabId, scriptlet) {
vAPI.tabs.injectScript(tabId, { vAPI.tabs.injectScript(tabId, {
file: 'js/scriptlets/' + scriptlet + '.js', file: '/js/scriptlets/' + scriptlet + '.js',
allFrames: true allFrames: true
}); });
}; };

View File

@ -16,15 +16,17 @@
<option value="" data-i18n="logAll"> <option value="" data-i18n="logAll">
<option value="tab_bts" data-i18n="logBehindTheScene"> <option value="tab_bts" data-i18n="logBehindTheScene">
</select> </select>
<span id="refresh" class="button disabled fa needtab">&#xf021;</span> <span id="refresh" class="button fa disabled needtab">&#xf021;</span>
<span id="showdom" class="button fa">&#xf121;</span> <span id="showdom" class="button fa">&#xf121;</span>
</div> </div>
</div> </div>
<div id="inspectors"> <div id="inspectors">
<div id="domInspector" class="inspector"> <div id="domInspector" class="inspector vCompact hCompact">
<div class="permatoolbar"> <div class="permatoolbar">
<div> <div>
<span class="button fa vCompactToggler"></span>
<span class="button fa hCompactToggler"></span>
<span class="button fa highlightMode" style="display: none">&#xf042;</span> <span class="button fa highlightMode" style="display: none">&#xf042;</span>
<span class="button fa revert disabled">&#xf12d;</span> <span class="button fa revert disabled">&#xf12d;</span>
<span class="button fa commit disabled">&#xf0c7;</span> <span class="button fa commit disabled">&#xf0c7;</span>
@ -35,10 +37,10 @@
</div> </div>
</div> </div>
<div id="netInspector" class="inspector compactView f"> <div id="netInspector" class="inspector vCompact f">
<div class="permatoolbar"> <div class="permatoolbar">
<div> <div>
<span id="compactViewToggler" class="button fa"></span> <span class="button fa vCompactToggler"></span>
<span id="clean" class="button fa disabled">&#xf00d;</span> <span id="clean" class="button fa disabled">&#xf00d;</span>
<span id="clear" class="button fa disabled">&#xf12d;</span> <span id="clear" class="button fa disabled">&#xf12d;</span>
<span id="filterButton" class="button fa">&#xf0b0;</span><input id="filterInput" type="text" placeholder="logFilterPrompt"> <span id="filterButton" class="button fa">&#xf0b0;</span><input id="filterInput" type="text" placeholder="logFilterPrompt">