Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: lib/elemHide.js

Issue 6201308310667264: Issue 521- Inject our stylesheet on per-site basis rather than globally (Closed)
Patch Set: WIP Created June 4, 2014, 5:55 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
1 /* 1 /*
2 * This file is part of Adblock Plus <http://adblockplus.org/>, 2 * This file is part of Adblock Plus <http://adblockplus.org/>,
3 * Copyright (C) 2006-2014 Eyeo GmbH 3 * Copyright (C) 2006-2014 Eyeo GmbH
4 * 4 *
5 * Adblock Plus is free software: you can redistribute it and/or modify 5 * Adblock Plus is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 3 as 6 * it under the terms of the GNU General Public License version 3 as
7 * published by the Free Software Foundation. 7 * published by the Free Software Foundation.
8 * 8 *
9 * Adblock Plus is distributed in the hope that it will be useful, 9 * Adblock Plus is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. 12 * GNU General Public License for more details.
13 * 13 *
14 * You should have received a copy of the GNU General Public License 14 * You should have received a copy of the GNU General Public License
15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. 15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
16 */ 16 */
17 17
18 /** 18 /**
19 * @fileOverview Element hiding implementation. 19 * @fileOverview Element hiding implementation.
20 */ 20 */
21 21
22 Cu.import("resource://gre/modules/Services.jsm"); 22 Cu.import("resource://gre/modules/Services.jsm");
23 23
24 let {Utils} = require("utils"); 24 let {Utils} = require("utils");
25 let {IO} = require("io"); 25 let {IO} = require("io");
26 let {Prefs} = require("prefs"); 26 let {Prefs} = require("prefs");
27 let {Policy} = require("contentPolicy");
27 let {ElemHideException} = require("filterClasses"); 28 let {ElemHideException} = require("filterClasses");
28 let {FilterNotifier} = require("filterNotifier"); 29 let {FilterNotifier} = require("filterNotifier");
29 let {AboutHandler} = require("elemHideHitRegistration"); 30 let {AboutHandler} = require("elemHideHitRegistration");
30 let {TimeLine} = require("timeline"); 31 let {TimeLine} = require("timeline");
31 32
32 /** 33 /**
33 * Lookup table, filters by their associated key 34 * Lookup table, filters by their associated key
34 * @type Object 35 * @type Object
35 */ 36 */
36 let filterByKey = {__proto__: null}; 37 let filterByKey = {__proto__: null};
(...skipping 22 matching lines...) Expand all
59 */ 60 */
60 let styleURL = null; 61 let styleURL = null;
61 62
62 /** 63 /**
63 * Element hiding component 64 * Element hiding component
64 * @class 65 * @class
65 */ 66 */
66 let ElemHide = exports.ElemHide = 67 let ElemHide = exports.ElemHide =
67 { 68 {
68 /** 69 /**
69 * Indicates whether filters have been added or removed since the last apply() call. 70 * Indicates whether filters have been added or removed since the last saveSty lesheet() call.
70 * @type Boolean 71 * @type Boolean
71 */ 72 */
72 isDirty: false, 73 isDirty: false,
73 74
74 /** 75 QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver, Ci.nsISupportsWeakRefer ence]),
75 * Inidicates whether the element hiding stylesheet is currently applied.
76 * @type Boolean
77 */
78 applied: false,
79 76
80 /** 77 /**
81 * Called on module startup. 78 * Called on module startup.
82 */ 79 */
83 init: function() 80 init: function()
84 { 81 {
85 TimeLine.enter("Entered ElemHide.init()"); 82 TimeLine.enter("Entered ElemHide.init()");
86 Prefs.addListener(function(name) 83
87 {
88 if (name == "enabled")
89 ElemHide.apply();
90 });
91 onShutdown.add(function() 84 onShutdown.add(function()
92 { 85 {
93 ElemHide.unapply(); 86 Services.obs.removeObserver(this, "content-document-global-created");
94 }); 87 }.bind(this));
95 88
96 TimeLine.log("done adding prefs listener"); 89 TimeLine.log("done adding prefs listener");
97 90
98 let styleFile = IO.resolveFilePath(Prefs.data_directory); 91 let styleFile = IO.resolveFilePath(Prefs.data_directory);
99 styleFile.append("elemhide.css"); 92 styleFile.append("elemhide.css");
100 styleURL = Services.io.newFileURI(styleFile).QueryInterface(Ci.nsIFileURL); 93 styleURL = Services.io.newFileURI(styleFile).QueryInterface(Ci.nsIFileURL);
101 TimeLine.log("done determining stylesheet URL"); 94 TimeLine.log("done determining stylesheet URL");
102 95
96 Services.obs.addObserver(this, "content-document-global-created", true);
97
103 TimeLine.leave("ElemHide.init() done"); 98 TimeLine.leave("ElemHide.init() done");
104 }, 99 },
105 100
106 /** 101 /**
107 * Removes all known filters 102 * Removes all known filters
108 */ 103 */
109 clear: function() 104 clear: function()
110 { 105 {
111 filterByKey = {__proto__: null}; 106 filterByKey = {__proto__: null};
112 keyByFilter = {__proto__: null}; 107 keyByFilter = {__proto__: null};
113 knownExceptions = {__proto__: null}; 108 knownExceptions = {__proto__: null};
114 exceptions = {__proto__: null}; 109 exceptions = {__proto__: null};
115 ElemHide.isDirty = false; 110 ElemHide.isDirty = false;
116 ElemHide.unapply(); 111 },
112
113 observe: function (subject, topic, data, additional)
114 {
115 if (topic != "content-document-global-created")
116 return;
117
118 if (!Prefs.enabled)
119 return;
120
121 let process = Policy.processWindow(subject, Policy.type.ELEMHIDE);
122 dump(subject.document.documentURIObject.spec + " is okay " + process + "\n" );
123 if (process)
124 return;
125
126 var windowUtils = subject.QueryInterface(Ci.nsIInterfaceRequestor).getInterf ace(Ci.nsIDOMWindowUtils);
127 windowUtils.loadSheet(styleURL, Ci.nsIStyleSheetService.USER_SHEET);
117 }, 128 },
118 129
119 /** 130 /**
120 * Add a new element hiding filter 131 * Add a new element hiding filter
121 * @param {ElemHideFilter} filter 132 * @param {ElemHideFilter} filter
122 */ 133 */
123 add: function(filter) 134 add: function(filter)
124 { 135 {
125 if (filter instanceof ElemHideException) 136 if (filter instanceof ElemHideException)
126 { 137 {
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after
189 return null; 200 return null;
190 201
191 let list = exceptions[filter.selector]; 202 let list = exceptions[filter.selector];
192 for (let i = list.length - 1; i >= 0; i--) 203 for (let i = list.length - 1; i >= 0; i--)
193 if (list[i].isActiveOnDomain(docDomain)) 204 if (list[i].isActiveOnDomain(docDomain))
194 return list[i]; 205 return list[i];
195 206
196 return null; 207 return null;
197 }, 208 },
198 209
210 shouldAllowLoad: function(wnd, filter)
211 {
212 let uri = wnd.document.documentURIObject;
213 if (!uri)
214 return true;
215
216 let domain = uri.host;
217 if (!filter.isActiveOnDomain(domain))
218 return true;
219
220 let exception = ElemHide.getException(filter, domain);
221 if (exception)
222 {
223 // FilterStorage.increaseHitCount(exception, wnd);
224 // RequestNotifier.addNodeData(node, topWnd, contentType, domain, thirdPar ty, locationText, exception);
225 return true;
226 }
227
228 // RequestNotifier.addNodeData(node, topWnd, contentType, domain, thirdParty , locationText, match);
229 // if (match)
230 // FilterStorage.increaseHitCount(match, wnd);
231 return false;
232 },
233
199 /** 234 /**
200 * Will be set to true if apply() is running (reentrance protection). 235 * Will be set to true if saveStylesheet() is running (reentrance protection).
201 * @type Boolean 236 * @type Boolean
202 */ 237 */
203 _applying: false, 238 _applying: false,
204 239
205 /** 240 /**
206 * Will be set to true if an apply() call arrives while apply() is already 241 * Will be set to true if an saveStylesheet() call arrives while saveStyleshee t()
207 * running (delayed execution). 242 * is already running (delayed execution).
208 * @type Boolean 243 * @type Boolean
209 */ 244 */
210 _needsApply: false, 245 _needsApply: false,
211 246
212 /** 247 /**
213 * Generates stylesheet URL and applies it globally 248 * Generates stylesheet URL.
214 */ 249 */
215 apply: function() 250 saveStylesheet: function()
216 { 251 {
217 if (this._applying) 252 if (this._applying)
218 { 253 {
219 this._needsApply = true; 254 this._needsApply = true;
220 return; 255 return;
221 } 256 }
222 257
223 TimeLine.enter("Entered ElemHide.apply()"); 258 TimeLine.enter("Entered ElemHide.saveStylesheet()");
224
225 if (!ElemHide.isDirty || !Prefs.enabled)
226 {
227 // Nothing changed, looks like we merely got enabled/disabled
228 if (Prefs.enabled && !ElemHide.applied)
229 {
230 try
231 {
232 Utils.styleService.loadAndRegisterSheet(styleURL, Ci.nsIStyleSheetServ ice.USER_SHEET);
233 ElemHide.applied = true;
234 }
235 catch (e)
236 {
237 Cu.reportError(e);
238 }
239 TimeLine.log("Applying existing stylesheet finished");
240 }
241 else if (!Prefs.enabled && ElemHide.applied)
242 {
243 ElemHide.unapply();
244 TimeLine.log("ElemHide.unapply() finished");
245 }
246
247 TimeLine.leave("ElemHide.apply() done (no file changes)");
248 return;
249 }
250 259
251 IO.writeToFile(styleURL.file, this._generateCSSContent(), function(e) 260 IO.writeToFile(styleURL.file, this._generateCSSContent(), function(e)
252 { 261 {
253 TimeLine.enter("ElemHide.apply() write callback"); 262 TimeLine.enter("ElemHide.saveStylesheet() write callback");
254 this._applying = false; 263 this._applying = false;
255 264
256 // _generateCSSContent is throwing NS_ERROR_NOT_AVAILABLE to indicate that 265 // _generateCSSContent is throwing NS_ERROR_NOT_AVAILABLE to indicate that
257 // there are no filters. If that exception is passed through XPCOM we will 266 // there are no filters. If that exception is passed through XPCOM we will
258 // see a proper exception here, otherwise a number. 267 // see a proper exception here, otherwise a number.
259 let noFilters = (e == Cr.NS_ERROR_NOT_AVAILABLE || (e && e.result == Cr.NS _ERROR_NOT_AVAILABLE)); 268 let noFilters = (e == Cr.NS_ERROR_NOT_AVAILABLE || (e && e.result == Cr.NS _ERROR_NOT_AVAILABLE));
260 if (noFilters) 269 if (noFilters)
261 { 270 {
262 e = null; 271 e = null;
263 IO.removeFile(styleURL.file, function(e) {}); 272 IO.removeFile(styleURL.file, function(e) {});
264 } 273 }
265 else if (e) 274 else if (e)
275 {
266 Cu.reportError(e); 276 Cu.reportError(e);
277 }
267 278
268 if (this._needsApply) 279 if (this._needsApply)
269 { 280 {
270 this._needsApply = false; 281 this._needsApply = false;
271 this.apply(); 282 this.saveStylesheet();
272 } 283 }
273 else if (!e) 284 else if (!e)
274 { 285 {
275 ElemHide.isDirty = false; 286 ElemHide.isDirty = false;
276 287
277 ElemHide.unapply();
278 TimeLine.log("ElemHide.unapply() finished");
279
280 if (!noFilters)
281 {
282 try
283 {
284 Utils.styleService.loadAndRegisterSheet(styleURL, Ci.nsIStyleSheetSe rvice.USER_SHEET);
285 ElemHide.applied = true;
286 }
287 catch (e)
288 {
289 Cu.reportError(e);
290 }
291 TimeLine.log("Applying stylesheet finished");
292 }
293
294 FilterNotifier.triggerListeners("elemhideupdate"); 288 FilterNotifier.triggerListeners("elemhideupdate");
295 } 289 }
296 TimeLine.leave("ElemHide.apply() write callback done"); 290 TimeLine.leave("ElemHide.saveStylesheet() write callback done");
297 }.bind(this), "ElemHideWrite"); 291 }.bind(this), "ElemHideWrite");
298 292
299 this._applying = true; 293 this._applying = true;
300 294
301 TimeLine.leave("ElemHide.apply() done", "ElemHideWrite"); 295 TimeLine.leave("ElemHide.saveStylesheet() done", "ElemHideWrite");
302 }, 296 },
303 297
304 _generateCSSContent: function() 298 _generateCSSContent: function()
305 { 299 {
306 // Grouping selectors by domains 300 // Grouping selectors by domains
307 TimeLine.log("start grouping selectors"); 301 TimeLine.log("start grouping selectors");
308 let domains = {__proto__: null}; 302 let domains = {__proto__: null};
309 let hasFilters = false; 303 let hasFilters = false;
310 for (let key in filterByKey) 304 for (let key in filterByKey)
311 { 305 {
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
350 + 'url-prefix("news://"),url-prefix("snews://"){'; 344 + 'url-prefix("news://"),url-prefix("snews://"){';
351 } 345 }
352 346
353 for (let selector in list) 347 for (let selector in list)
354 yield selector.replace(/[^\x01-\x7F]/g, escapeChar) + "{" + cssTemplate. replace("%ID%", list[selector]) + "}"; 348 yield selector.replace(/[^\x01-\x7F]/g, escapeChar) + "{" + cssTemplate. replace("%ID%", list[selector]) + "}";
355 yield '}'; 349 yield '}';
356 } 350 }
357 }, 351 },
358 352
359 /** 353 /**
360 * Unapplies current stylesheet URL
361 */
362 unapply: function()
363 {
364 if (ElemHide.applied)
365 {
366 try
367 {
368 Utils.styleService.unregisterSheet(styleURL, Ci.nsIStyleSheetService.USE R_SHEET);
369 }
370 catch (e)
371 {
372 Cu.reportError(e);
373 }
374 ElemHide.applied = false;
375 }
376 },
377
378 /**
379 * Retrieves the currently applied stylesheet URL
380 * @type String
381 */
382 get styleURL()
383 {
384 return ElemHide.applied ? styleURL.spec : null;
385 },
386
387 /**
388 * Retrieves an element hiding filter by the corresponding protocol key 354 * Retrieves an element hiding filter by the corresponding protocol key
389 */ 355 */
390 getFilterByKey: function(/**String*/ key) /**Filter*/ 356 getFilterByKey: function(/**String*/ key) /**Filter*/
391 { 357 {
392 return (key in filterByKey ? filterByKey[key] : null); 358 return (key in filterByKey ? filterByKey[key] : null);
393 }, 359 },
394 360
395 /** 361 /**
396 * Returns a list of all selectors active on a particular domain (currently 362 * Returns a list of all selectors active on a particular domain (currently
397 * used only in Chrome, Opera and Safari). 363 * used only in Chrome, Opera and Safari).
(...skipping 12 matching lines...) Expand all
410 376
411 if (specificOnly && (!domains || domains[""])) 377 if (specificOnly && (!domains || domains[""]))
412 continue; 378 continue;
413 379
414 if (filter.isActiveOnDomain(domain) && !this.getException(filter, domain)) 380 if (filter.isActiveOnDomain(domain) && !this.getException(filter, domain))
415 result.push(filter.selector); 381 result.push(filter.selector);
416 } 382 }
417 return result; 383 return result;
418 } 384 }
419 }; 385 };
OLDNEW
« lib/contentPolicy.js ('K') | « lib/contentPolicy.js ('k') | lib/elemHideHitRegistration.js » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld