diff options
| -rw-r--r-- | chrome/content/code/browserOverlay.xul.js | 12 | ||||
| -rw-r--r-- | chrome/content/code/editRedirect.xul.js | 2 | ||||
| -rw-r--r-- | chrome/content/code/prefs.js | 3 | ||||
| -rw-r--r-- | chrome/content/code/redirect.js | 241 | ||||
| -rw-r--r-- | chrome/content/code/redirector.prototype.js | 357 | ||||
| -rw-r--r-- | chrome/content/code/settings.xul.js | 95 | ||||
| -rw-r--r-- | chrome/content/ui/browserOverlay.xul | 1 | ||||
| -rw-r--r-- | chrome/content/ui/settings.xul | 1 | ||||
| -rw-r--r-- | chrome/content/unittest/run.html | 2 | ||||
| -rw-r--r-- | chrome/content/unittest/testcases.js | 5 | ||||
| -rw-r--r-- | components/interfaces/nsIFile.idl | 343 | ||||
| -rw-r--r-- | components/interfaces/nsISimpleEnumerator.idl | 81 | ||||
| -rw-r--r-- | components/interfaces/rdIMatchResult.idl | 17 | ||||
| -rw-r--r-- | components/interfaces/rdIRedirect.idl | 23 | ||||
| -rw-r--r-- | components/interfaces/rdIRedirector.idl | 16 | ||||
| -rw-r--r-- | components/redirector.component.js | 5 | 
16 files changed, 871 insertions, 333 deletions
| diff --git a/chrome/content/code/browserOverlay.xul.js b/chrome/content/code/browserOverlay.xul.js index 28047b1..2a6fbac 100644 --- a/chrome/content/code/browserOverlay.xul.js +++ b/chrome/content/code/browserOverlay.xul.js @@ -1,10 +1,11 @@  //// $Id$ -var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.nsISupports).wrappedJSObject; +var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.rdIRedirector);  var RedirectorOverlay = {      strings     : null, +    prefs		: null,      onLoad : function(event) {          try { @@ -14,8 +15,9 @@ var RedirectorOverlay = {                  .addEventListener("popupshowing", function(e) { RedirectorOverlay.showContextMenu(e); }, false);              this.strings = document.getElementById("redirector-strings"); -            this.changedPrefs(Redirector.prefs); -            Redirector.prefs.addListener(this); +            this.prefs = new Prefs(); +            this.changedPrefs(this.prefs); +            this.prefs.addListener(this);          } catch(e) {              if (this.strings) {                  alert(this.strings.getString("initError") + "\n\n" + e); @@ -26,7 +28,7 @@ var RedirectorOverlay = {      },      onUnload : function(event) { -        Redirector.prefs.removeListener(this); +        this.prefs.dispose();          Redirector.debug("Finished cleanup");      }, @@ -71,7 +73,7 @@ var RedirectorOverlay = {      },      toggleEnabled : function(event) { -        Redirector.prefs.enabled = !Redirector.prefs.enabled; +        this.prefs.enabled = !this.prefs.enabled;      },      openSettings : function() { diff --git a/chrome/content/code/editRedirect.xul.js b/chrome/content/code/editRedirect.xul.js index 578f498..72513e8 100644 --- a/chrome/content/code/editRedirect.xul.js +++ b/chrome/content/code/editRedirect.xul.js @@ -1,7 +1,5 @@  //// $Id$
 -var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.nsISupports).wrappedJSObject;
 -
  var EditRedirect = {
      txtExampleUrl : null,
      txtIncludePattern : null,
 diff --git a/chrome/content/code/prefs.js b/chrome/content/code/prefs.js index c87eb27..4118bc5 100644 --- a/chrome/content/code/prefs.js +++ b/chrome/content/code/prefs.js @@ -49,7 +49,8 @@ Prefs.prototype = {          this.service.addObserver('extensions.redirector', this, false);
      },
 -    destroy : function() {
 +    dispose : function() {
 +	    this._listeners = null;
          this.service.removeObserver('extensions.redirector', this);
  	},
 diff --git a/chrome/content/code/redirect.js b/chrome/content/code/redirect.js index e65ca50..2be8fc9 100644 --- a/chrome/content/code/redirect.js +++ b/chrome/content/code/redirect.js @@ -1,5 +1,7 @@  //// $Id$
 +Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 +
  function Redirect(exampleUrl, includePattern, redirectUrl, patternType, excludePattern, unescapeMatches, disabled) {
  	this._init(exampleUrl, includePattern, redirectUrl, patternType, excludePattern, unescapeMatches, disabled);
  }
 @@ -9,33 +11,145 @@ Redirect.WILDCARD = 'W';  Redirect.REGEX = 'R';
  Redirect.prototype = {
 -	
 -	//These are the only ones that are necessary to have as properties for now
 -	//The others can be changed to properties later as neccessary
 -	_includePattern : null,
 -	_excludePattern : null,
 -	_patternType : null,
 -	_rxInclude : null,
 -	_rxExclude : null,
 -
 -	get patternType() { return this._patternType; },
 -	set patternType(value) { 
 -		this._patternType = value;
 -		this.compile();
 -	},
 +	// rdIRedirect implementation
 +	
 +	//attributes
 +	exampleUrl : null,
 +			
  	get includePattern() { return this._includePattern; },
  	set includePattern(value) { 
  		this._includePattern = value;
  		this._rxInclude = this._compile(value); 
  	},
 -
 +	
  	get excludePattern() { return this._excludePattern; },
  	set excludePattern(value) { 
  		this._excludePattern = value; 
  		this._rxExclude = this._compile(value); 
  	},
 +	redirectTo : null,
 +	
 +	get patternType() { return this._patternType; },
 +	set patternType(value) { 
 +		this._patternType = value;
 +		this.compile();
 +	},
 +
 +	unescapeMatches : false,
 +	
 +	disabled : false,
 +	
 +	//Functions
 +    clone : function() {
 +		return new Redirect(this.exampleUrl, this.includePattern, 
 +							this.redirectUrl, this.patternType, 
 +							this.excludePattern, this.unescapeMatches,
 +							this.disabled);    
 +    },
 +    
 +	compile : function() {
 +		this._rxInclude = this._compile(this._includePattern); 
 +		this._rxExclude = this._compile(this._excludePattern); 
 +	},
 +
 +	copyValues : function(other) {
 +		this.exampleUrl = other.exampleUrl;
 +		this.includePattern = other.includePattern;
 +		this.excludePattern = other.excludePattern;
 +		this.redirectUrl = other.redirectUrl;
 +		this.patternType = other.patternType;
 +		this.unescapeMatches = other.unescapeMatches;
 +		this.disabled = other.disabled;
 +    },
 +
 +	deserialize : function(str) {
 +		if (!str || !str.split) {
 +			throw Error("Invalid serialized redirect: " + str);
 +		}	
 +		var parts = str.split(',,,');
 +		if (parts.length < 5) {
 +			throw Error("Invalid serialized redirect, too few fields: " + str);
 +		}
 +		this._init.apply(this, parts);
 +	},
 +	
 +    equals : function(redirect) {
 +		return this.exampleUrl == redirect.exampleUrl
 +			&& this.includePattern == redirect.includePattern
 +			&& this.excludePattern == redirect.excludePattern
 +			&& this.redirectUrl == redirect.redirectUrl
 +			&& this.patternType == redirect.patternType
 +			&& this.unescapeMatches == redirect.unescapeMatches
 +		;
 +    },
 +	
 +	getMatch: function(url) {
 +		var result = { 
 +			isMatch : false, 
 +			isExcludeMatch : false, 
 +			isDisabledMatch : false, 
 +			redirectTo : '',
 +			toString : function() { return "{ isMatch : " + this.isMatch + 
 +			                               ", isExcludeMatch : " + this.isExcludeMatch + 
 +			                               ", isDisabledMatch : " + this.isDisabledMatch + 
 +			                               ", redirectTo : \"" + this.redirectTo + "\"" +
 +			                               "}"; }
 +		};
 +		var redirectTo = null;
 +
 +		redirectTo = this._includeMatch(url);
 +        if (redirectTo !== null) {
 +	        if (this.disabled) {
 +				result.isDisabledMatch = true;
 +			} else if (this._excludeMatch(url)) {
 +	            result.isExcludeMatch = true;
 +		  	} else {
 +	         	result.isMatch = true;
 +	         	result.redirectTo = redirectTo;
 +	        }
 +        }
 +     	return result;   
 +	},
 +	
 +	isRegex: function() {
 +		return this.patternType == Redirect.REGEX;
 +	},
 +	
 +	isWildcard : function() {
 +		return this.patternType == Redirect.WILDCARD;	
 +	},
 +
 +	serialize : function() {
 +		return [ this.exampleUrl
 +			   , this.includePattern
 +			   , this.redirectUrl
 +			   , this.patternType
 +			   , this.excludePattern
 +			   , this.unescapeMatches
 +			   , this.disabled ].join(',,,');
 +	},
 +	
 +	test : function() {
 +		return this.getMatch(this.exampleUrl);	
 +	},
 +
 +	//end rdIRedirect
 +	
 +	//nsISupports
 +	QueryInterface : XPCOMUtils.generateQI([Components.interfaces.rdIRedirect]),
 +	
 +	//end nsISupports
 +	
 +	//Private functions below	
 +
 +	_includePattern : null,
 +	_excludePattern : null,
 +	_patternType : null,
 +	_rxInclude : null,
 +	_rxExclude : null,
 +	
  	_preparePattern : function(pattern) {
  		if (this.patternType == Redirect.REGEX) {
  			return pattern;	
 @@ -55,12 +169,7 @@ Redirect.prototype = {  			return converted;
  		}
  	},
 -	
 -	compile : function() {
 -		this._rxInclude = this._compile(this._includePattern); 
 -		this._rxExclude = this._compile(this._excludePattern); 
 -	},
 -	
 +
  	_compile : function(pattern) {
  		if (!pattern) {
  			return null;
 @@ -90,67 +199,6 @@ Redirect.prototype = {  			+  '\n}\n';
  	},
 -	isWildcard : function() {
 -		return this.patternType == Redirect.WILDCARD;	
 -	},
 -	
 -	isRegex: function() {
 -		return this.patternType == Redirect.REGEX;
 -	},
 -	
 -	test : function() {
 -		return this.getMatch(this.exampleUrl);	
 -	},
 -
 -	serialize : function() {
 -		return [ this.exampleUrl
 -			   , this.includePattern
 -			   , this.redirectUrl
 -			   , this.patternType
 -			   , this.excludePattern
 -			   , this.unescapeMatches
 -			   , this.disabled ].join(',,,');
 -	},
 -	
 -	deserialize : function(str) {
 -		if (!str || !str.split) {
 -			throw Error("Invalid serialized redirect: " + str);
 -		}	
 -		var parts = str.split(',,,');
 -		if (parts.length < 5) {
 -			throw Error("Invalid serialized redirect, too few fields: " + str);
 -		}
 -		this._init.apply(this, parts);
 -	},
 -	
 -	getMatch: function(url) {
 -		var result = { 
 -			isMatch : false, 
 -			isExcludeMatch : false, 
 -			isDisabledMatch : false, 
 -			redirectTo : '',
 -			toString : function() { return "{ isMatch : " + this.isMatch + 
 -			                               ", isExcludeMatch : " + this.isExcludeMatch + 
 -			                               ", isDisabledMatch : " + this.isDisabledMatch + 
 -			                               ", redirectTo : \"" + this.redirectTo + "\"" +
 -			                               "}"; }
 -		};
 -		var redirectTo = null;
 -
 -		redirectTo = this._includeMatch(url);
 -        if (redirectTo !== null) {
 -	        if (this.disabled) {
 -				result.isDisabledMatch = true;
 -			} else if (this._excludeMatch(url)) {
 -	            result.isExcludeMatch = true;
 -		  	} else {
 -	         	result.isMatch = true;
 -	         	result.redirectTo = redirectTo;
 -	        }
 -        }
 -     	return result;   
 -	},
 -	
  	_includeMatch : function(url) {
  		if (!this._rxInclude) {
  			return null;
 @@ -174,32 +222,5 @@ Redirect.prototype = {  		var shouldExclude = !!this._rxExclude.exec(url);	
  		this._rxExclude.lastIndex = 0;
  		return shouldExclude;
 -	},
 -    
 -    clone : function() {
 -		return new Redirect(this.exampleUrl, this.includePattern, 
 -							this.redirectUrl, this.patternType, 
 -							this.excludePattern, this.unescapeMatches,
 -							this.disabled);    
 -    },
 -    
 -    copyValues : function(other) {
 -		this.exampleUrl = other.exampleUrl;
 -		this.includePattern = other.includePattern;
 -		this.excludePattern = other.excludePattern;
 -		this.redirectUrl = other.redirectUrl;
 -		this.patternType = other.patternType;
 -		this.unescapeMatches = other.unescapeMatches;
 -		this.disabled = other.disabled;
 -    },
 -    
 -    equals : function(redirect) {
 -		return this.exampleUrl == redirect.exampleUrl
 -			&& this.includePattern == redirect.includePattern
 -			&& this.excludePattern == redirect.excludePattern
 -			&& this.redirectUrl == redirect.redirectUrl
 -			&& this.patternType == redirect.patternType
 -			&& this.unescapeMatches == redirect.unescapeMatches
 -		;
 -    }    
 +	}
  };
\ No newline at end of file diff --git a/chrome/content/code/redirector.prototype.js b/chrome/content/code/redirector.prototype.js index 1b32ad1..23400d4 100644 --- a/chrome/content/code/redirector.prototype.js +++ b/chrome/content/code/redirector.prototype.js @@ -1,70 +1,146 @@  //// $Id$
  Redirector.prototype = {
 +	
 +	//rdIRedirector implementation
 +	get enabled() {
 +		return this._prefs && this._prefs.enabled;	
 +	},
 +	
 +	set enabled(value) {
 +		if (this._prefs) {
 +			this._prefs.enabled = value;
 +		}
 +	},
 -	prefs : null,
 -	list : null,
 -    strings : null,
 -    cout : Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService),
 +	get redirectCount() {
 +		return this._list.length;
 +	},
 +	
 +    addRedirect : function(redirect) {
 +        this._list.push(redirect);
 +        this.save();
 +    },
 -    init : function() {
 -	    this.prefs = new Prefs();
 -	    //Check if we need to update existing redirects
 -		var data = this.prefs.redirects;
 -	    var version = this.prefs.version;
 -	    this.loadStrings();
 -	    
 -	    //Here update checks are handled
 -	    if (version == 'undefined') { //Either a fresh install of Redirector, or first time install of v2.0
 -	        if (data) { //There is some data in redirects, we are upgrading from a previous version, need to upgrade data
 -	            var tempList = JSON.parse(data);
 -	            var arr;
 -	            var newArr = []
 -	            for each (arr in tempList) {
 -	                if (arr.length == 5) {
 -	                    arr.push(''); //For those that don't have an exclude pattern. Backwards compatibility is a bitch!
 -	                }
 -	                arr.splice(3,1); //Remove the "only if link exists" data
 -	                newArr.push(arr.join(',,,'));
 -	            }
 -	            this.prefs.redirects = newArr.join(':::');
 -	        }
 -	        this.prefs.version = '2.0';
 -	    }
 -	    //Update finished
 -	    
 -	    //Now get from the new format
 -	    data = this.prefs.redirects;
 -	    var arr;
 -	    this.list = [];
 -	    if (data != '') {
 -	        for each (redirectString in data.split(':::')) {
 -		        var redirect = new Redirect();
 -		        redirect.deserialize(redirectString);
 -		        this.list.push(redirect);
 -	        }
 -	    }
 +    debug : function(msg) {
 +        if (this._prefs.debugEnabled) {
 +            this._cout.logStringMessage('REDIRECTOR: ' + msg);
 +        }
      },
 -    loadStrings : function() {
 -        var src = 'chrome://redirector/locale/redirector.properties';
 -        var localeService = Cc["@mozilla.org/intl/nslocaleservice;1"].getService(Ci.nsILocaleService);
 -        var appLocale = localeService.getApplicationLocale();
 -        var stringBundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
 -        this.strings = stringBundleService.createBundle(src, appLocale);    
 -    },    
 +    deleteRedirectAt : function(index) {
 +        this._list.splice(index, 1);
 +        this.save();
 +    },
 -    debug : function(msg) {
 -        if (this.prefs.debugEnabled) {
 -            this.cout.logStringMessage('REDIRECTOR: ' + msg);
 +   	exportRedirects : function(file) {
 +		var fileStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
 +		const PR_WRONLY      = 0x02;
 +		const PR_CREATE_FILE = 0x08;
 +		const PR_TRUNCATE    = 0x20;
 +
 +		fileStream.init(file, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0644, 0);
 +		var stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
 +		stream.init(fileStream, "UTF-8", 16384, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
 +		stream.writeString(this._redirectsAsString('\n'));
 +		stream.close();
 +	},
 +	
 +	getRedirectAt : function(index) {
 +		return this._list[index];	
 +	},
 +	
 +    //Get the redirect url for the given url. This will not check if we are enabled, and
 +    //not do any verification on the url, just assume that it is a good string url that is for http/s
 +    getRedirectUrl : function(url) {
 +        this.debug("Checking " + url);
 +        
 +        for each (var redirect in this._list) {
 +            var result = redirect.getMatch(url);
 +            if (result.isExcludeMatch) {
 +	        	this.debug(url + ' matched exclude pattern ' + redirect.excludePattern + ' so the redirect ' + redirect.includePattern + ' will not be used');
 +            } else if (result.isDisabledMatch) {
 +	        	this.debug(url + ' matched pattern ' + redirect.includePattern + ' but the redirect is disabled');
 +            } else if (result.isMatch) {
 +                redirectUrl = this._makeAbsoluteUrl(url, result.redirectTo);
 +				
 +                //check for loops...
 +                result = redirect.getMatch(redirectUrl);
 +                if (result.isMatch) {
 +	                var title = this._getString('invalidRedirectTitle');
 +	                var msg = this._getFormattedString('invalidRedirectText', [redirect.includePattern, url, redirectUrl]);
 +	                this.debug(msg);
 +					redirect.disabled = true;
 +					this.save();	                
 +					this._msgBox(title, msg);
 +                } else {
 +	                this.debug('Redirecting ' + url + ' to ' + redirectUrl);
 +	                return redirectUrl;
 +                }
 +            }
          }
 +        return null;
 +    },
 +    
 +	importRedirects : function(file) {
 +		var fileStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
 +		fileStream.init(file, 0x01, 0444, 0); //TODO: Find the actual constants for these magic numbers
 +
 +		var stream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
 +		stream.init(fileStream, "UTF-8", 16384, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
 +		stream = stream.QueryInterface(Ci.nsIUnicharLineInputStream);
 +
 +		var importCount = 0, existsCount = 0;
 +		var lines = [];
 +		var line = {value: null};
 +		stream.readLine(line);
 +		while (line.value) {
 +			var redirect = new Redirect();
 +			redirect.deserialize(line.value.replace('\n', ''));
 +			if (this._containsRedirect(redirect)) {
 +				existsCount++;
 +			} else {
 +				this._list.push(redirect);
 +				importCount++;
 +			}
 +			stream.readLine(line);
 +		}
 +		stream.close();
 +		this.save();
 +		return importCount | (existsCount << 16);
 +	},
 +    
 +    reload : function() {
 +		loader.loadSubScript('chrome://redirector/content/code/redirector.prototype.js');
 +		loader.loadSubScript('chrome://redirector/content/code/redirect.js');
 +		var oldEnabled = this.enabled;
 +		for (var key in Redirector.prototype) {
 +			if (key != 'redirectCount' && key != 'enabled') {
 +				this[key] = Redirector.prototype[key];
 +			}
 +		}
 +		this._init();
 +		this.enabled = oldEnabled;
 +    }, 
 +    
 +    save : function() {
 +        this._prefs.redirects = this._redirectsAsString(':::');
      },
 +
 +	switchItems : function(index1, index2) {
 +		var item = this._list[index1];
 +		this._list[index1] = this._list[index2];
 +		this._list[index2] = item;
 +		this.save();
 +	},
 +    
 +    //End rdIRedirector    
 -    // nsIContentPolicy interface implementation
 +    // nsIContentPolicy implementation
      shouldLoad: function(contentType, contentLocation, requestOrigin, aContext, mimeTypeGuess, extra) {
  	    try {
  	    	//This is also done in getRedirectUrl, but we want to exit as quickly as possible for performance
 -		    if (!this.prefs.enabled) {
 +		    if (!this._prefs.enabled) {
  	            return Ci.nsIContentPolicy.ACCEPT;
  	        }
 @@ -94,45 +170,12 @@ Redirector.prototype = {      },
 -    //Get the redirect url for the given url. This will not check if we are enabled, and
 -    //not do any verification on the url, just assume that it is a good string url that is for http/s
 -    getRedirectUrl : function(url) {
 -        this.debug("Checking " + url);
 -        
 -        for each (var redirect in this.list) {
 -            var result = redirect.getMatch(url);
 -            if (result.isExcludeMatch) {
 -	        	this.debug(url + ' matched exclude pattern ' + redirect.excludePattern + ' so the redirect ' + redirect.includePattern + ' will not be used');
 -            } else if (result.isDisabledMatch) {
 -	        	this.debug(url + ' matched pattern ' + redirect.includePattern + ' but the redirect is disabled');
 -            } else if (result.isMatch) {
 -                redirectUrl = this.makeAbsoluteUrl(url, result.redirectTo);
 -				
 -                //check for loops...
 -                result = redirect.getMatch(redirectUrl);
 -                if (result.isMatch) {
 -	                var title = this.getString('invalidRedirectTitle');
 -	                var msg = this.getFormattedString('invalidRedirectText', [redirect.includePattern, url, redirectUrl]);
 -	                this.debug(msg);
 -					redirect.disabled = true;
 -					this.save();	                
 -					this.msgBox(title, msg);
 -                } else {
 -	                this.debug('Redirecting ' + url + ' to ' + redirectUrl);
 -	                return redirectUrl;
 -                }
 -            }
 -        }
 -        return null;
 -    },
 -
 -    // nsIContentPolicy interface implementation
      shouldProcess: function(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) {
          return Ci.nsIContentPolicy.ACCEPT;
      },
 +    //end nsIContentPolicy
 -    //nsIChannelEventSink interface implementation
 -    //Mostly borrowed from the excellent Adblock Plus extension
 +    //nsIChannelEventSink implementation
  	onChannelRedirect: function(oldChannel, newChannel, flags)
  	{
  		try {
 @@ -177,78 +220,72 @@ Redirector.prototype = {  			dump("Redirector: Unexpected error in onChannelRedirect: " + e + "\n");
  		}
  	},
 -		
 -    reload : function() {
 -		loader.loadSubScript('chrome://redirector/content/code/redirector.prototype.js');
 -		loader.loadSubScript('chrome://redirector/content/code/redirect.js');
 -		
 -		for (var key in Redirector.prototype) {
 -			this[key] = Redirector.prototype[key];
 -		}
 -		this.init();
 -    }, 
 -    
 -    addRedirect : function(redirect) {
 -        this.list.push(redirect);
 -        this.save();
 -    },
 +	//end nsIChannelEventSink
 +	
 +	//Private members and methods
 +			
 +	_prefs : null,
 +	_list : null,
 +    _strings : null,
 +    _cout : Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService),
 -    deleteAt : function(index) {
 -        this.list.splice(index, 1);
 -        this.save();
 -    },
 -    
 -    save : function() {
 -        this.prefs.redirects = this.redirectsAsString(':::');
 +    _init : function() {
 +	    if (this._prefs) {
 +		    this._prefs.dispose();
 +	    }
 +	    this._prefs = new Prefs();
 +	    //Check if we need to update existing redirects
 +		var data = this._prefs.redirects;
 +	    var version = this._prefs.version;
 +	    this._loadStrings();
 +	    
 +	    //Here update checks are handled
 +	    if (version == 'undefined') { //Either a fresh install of Redirector, or first time install of v2.0
 +	        if (data) { //There is some data in redirects, we are upgrading from a previous version, need to upgrade data
 +	            var tempList = JSON.parse(data);
 +	            var arr;
 +	            var newArr = []
 +	            for each (arr in tempList) {
 +	                if (arr.length == 5) {
 +	                    arr.push(''); //For those that don't have an exclude pattern. Backwards compatibility is a bitch!
 +	                }
 +	                arr.splice(3,1); //Remove the "only if link exists" data
 +	                newArr.push(arr.join(',,,'));
 +	            }
 +	            this._prefs.redirects = newArr.join(':::');
 +	        }
 +	        this._prefs.version = '2.0';
 +	    }
 +	    //Update finished
 +	    
 +	    //Now get from the new format
 +	    data = this._prefs.redirects;
 +	    var arr;
 +	    this._list = [];
 +	    if (data != '') {
 +	        for each (redirectString in data.split(':::')) {
 +		        var redirect = new Redirect();
 +		        redirect.deserialize(redirectString);
 +		        this._list.push(redirect);
 +	        }
 +	    }
      },
 -    redirectsAsString : function(seperator) {
 -		return [r.serialize() for each (r in this.list)].join(seperator);
 +    _loadStrings : function() {
 +        var src = 'chrome://redirector/locale/redirector.properties';
 +        var localeService = Cc["@mozilla.org/intl/nslocaleservice;1"].getService(Ci.nsILocaleService);
 +        var appLocale = localeService.getApplicationLocale();
 +        var stringBundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
 +        this._strings = stringBundleService.createBundle(src, appLocale);    
 +    },    
 +
 +    _redirectsAsString : function(seperator) {
 +		return [r.serialize() for each (r in this._list)].join(seperator);
      },
 -	exportRedirects : function(file) {
 -		var fileStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
 -		const PR_WRONLY      = 0x02;
 -		const PR_CREATE_FILE = 0x08;
 -		const PR_TRUNCATE    = 0x20;
 -
 -		fileStream.init(file, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, 0644, 0);
 -		var stream = Cc["@mozilla.org/intl/converter-output-stream;1"].createInstance(Ci.nsIConverterOutputStream);
 -		stream.init(fileStream, "UTF-8", 16384, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
 -		stream.writeString(this.redirectsAsString('\n'));
 -		stream.close();
 -	},
 -	
 -	importRedirects : function(file) {
 -		var fileStream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(Ci.nsIFileInputStream);
 -		fileStream.init(file, 0x01, 0444, 0); //TODO: Find the actual constants for these magic numbers
 -
 -		var stream = Cc["@mozilla.org/intl/converter-input-stream;1"].createInstance(Ci.nsIConverterInputStream);
 -		stream.init(fileStream, "UTF-8", 16384, Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
 -		stream = stream.QueryInterface(Ci.nsIUnicharLineInputStream);
 -
 -		var importCount = 0, existsCount = 0;
 -		var lines = [];
 -		var line = {value: null};
 -		stream.readLine(line);
 -		while (line.value) {
 -			var redirect = new Redirect();
 -			redirect.deserialize(line.value.replace('\n', ''));
 -			if (this.containsRedirect(redirect)) {
 -				existsCount++;
 -			} else {
 -				this.list.push(redirect);
 -				importCount++;
 -			}
 -			stream.readLine(line);
 -		}
 -		stream.close();
 -		this.save();
 -		return { imported : importCount, existed : existsCount };	
 -	},
 -	containsRedirect : function(redirect) {
 -		for each (var existing in this.list) {
 +	_containsRedirect : function(redirect) {
 +		for each (var existing in this._list) {
  			if (existing.equals(redirect)) {
  				return true;
  			}	
 @@ -256,21 +293,21 @@ Redirector.prototype = {  		return false;
  	},
 -    getString : function(name) {
 -	    return this.strings.GetStringFromName(name);
 +    _getString : function(name) {
 +	    return this._strings.GetStringFromName(name);
      },
 -    getFormattedString : function(name, params) {
 -		return this.strings.formatStringFromName(name, params, params.length);
 +    _getFormattedString : function(name, params) {
 +		return this._strings.formatStringFromName(name, params, params.length);
      },
 -    msgBox : function(title, text) {
 +    _msgBox : function(title, text) {
          Cc["@mozilla.org/embedcomp/prompt-service;1"]
              .getService(Ci.nsIPromptService)
                  .alert(null, title, text);
      },
 -    makeAbsoluteUrl : function(currentUrl, relativeUrl) {
 +    _makeAbsoluteUrl : function(currentUrl, relativeUrl) {
          if (relativeUrl.match(/https?:/)) {
              return relativeUrl;
 diff --git a/chrome/content/code/settings.xul.js b/chrome/content/code/settings.xul.js index f85c1ee..8958028 100644 --- a/chrome/content/code/settings.xul.js +++ b/chrome/content/code/settings.xul.js @@ -1,6 +1,6 @@  // $Id$
 -var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.nsISupports).wrappedJSObject;
 +var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.rdIRedirector);
  const Cc = Components.classes;
  const Ci = Components.interfaces;
  const nsLocalFile = Components.Constructor("@mozilla.org/file/local;1", "nsILocalFile", "initWithPath");
 @@ -18,6 +18,7 @@ var Settings = {  	chkShowStatusBarIcon : null,
  	chkShowContextMenu : null,
  	chkEnableDebugOutput : null,
 +	prefs : null,
      onLoad : function() {
          try {
 @@ -34,15 +35,20 @@ var Settings = {              this.chkShowContextMenu = document.getElementById('chkShowContextMenu');
              this.chkEnableDebugOutput = document.getElementById('chkEnableDebugOutput');
 +            this.prefs = new Prefs();
              //Preferences
 -            this.setPrefs(Redirector.prefs);
 -            Redirector.prefs.addListener(this);
 +            this.changedPrefs(this.prefs);
 +            this.prefs.addListener(this);
              //Redirect list
              this.lstRedirects.selType = 'single'; 
              this.template = document.getElementsByTagName('richlistitem')[0];
              this.lstRedirects.removeChild(this.template);
 -            this.addItemsToListBox(Redirector.list);
 +            var list = [];
 +            for (var i = 0; i < Redirector.redirectCount; i++) {
 +	            list.push(Redirector.getRedirectAt(i));
 +            }
 +            this.addItemsToListBox(list);
  			this.selectionChange();
              this.strings = document.getElementById('redirector-strings');
 @@ -56,14 +62,10 @@ var Settings = {      },
      onUnload : function() {
 -		Redirector.prefs.removeListener(this);    
 +		this.prefs.dispose();
      },
 -    changedPrefs : function(prefs) {
 -    	this.setPrefs(prefs);
 -	},
 -	
 -	setPrefs : function(prefs) {
 +	changedPrefs : function(prefs) {
          this.chkEnableRedirector.setAttribute('checked', prefs.enabled);
          this.chkShowStatusBarIcon.setAttribute('checked', prefs.showStatusBarIcon);
          this.chkShowContextMenu.setAttribute('checked', prefs.showContextMenu);
 @@ -110,22 +112,18 @@ var Settings = {      },
      moveDown : function() {
 -        if (this.lstRedirects.selectedIndex == Redirector.list.length-1) {
 +        if (this.lstRedirects.selectedIndex == Redirector.redirectCount-1) {
              return;
          }
          this.switchItems(this.lstRedirects.selectedIndex);
      },
      switchItems : function(firstIndex) {
 -        var firstRedirect = Redirector.list[firstIndex];
 -        var secondRedirect = Redirector.list[firstIndex+1];
 -        Redirector.list[firstIndex] = secondRedirect;
 -        Redirector.list[firstIndex+1] = firstRedirect;
 +	    Redirector.switchItems(firstIndex, firstIndex+1);
          var firstItem = this.lstRedirects.children[firstIndex];
          var secondItem = this.lstRedirects.children[firstIndex+1];
          this.lstRedirects.removeChild(secondItem);
          this.lstRedirects.insertBefore(secondItem, firstItem);
 -        Redirector.save();
          this.selectionChange();
      }, 
 @@ -136,7 +134,7 @@ var Settings = {      },
      preferenceChange : function(event) {
 -	    Redirector.prefs[event.originalTarget.getAttribute('preference')] = event.originalTarget.hasAttribute('checked');
 +	    this.prefs[event.originalTarget.getAttribute('preference')] = event.originalTarget.hasAttribute('checked');
      },
      addRedirect : function() {
 @@ -187,7 +185,7 @@ var Settings = {          try {
              this.lstRedirects.removeChild(this.lstRedirects.children[index]);
 -            Redirector.deleteAt(index);
 +            Redirector.deleteRedirectAt(index);
              this.selectionChange();
          } catch(e) {
              alert(e);
 @@ -211,54 +209,55 @@ var Settings = {          this.btnEdit.disabled = (index == -1);
          this.btnDelete.disabled = (index == -1);
          this.btnUp.disabled = (index <= 0);
 -        this.btnDown.disabled = (index == -1 || index >= Redirector.list.length-1);
 -        this.btnExport.disabled = (Redirector.list.length == 0);
 +        this.btnDown.disabled = (index == -1 || index >= Redirector.redirectCount-1);
 +        this.btnExport.disabled = (Redirector.redirectCount== 0);
      },
 -    
 -    importExport : function(mode, captionKey, func) {
 +
 +    getFile : function(captionKey, mode) {
  		//Mostly borrowed from Adblock Plus
  		var picker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
 -		picker.init(window, Redirector.getString(captionKey), mode);
 +		picker.init(window, this.strings.getString(captionKey), mode);
  		picker.defaultExtension = ".rdx";
 -		var dir = Redirector.prefs.defaultDir;
 +		var dir = this.prefs.defaultDir;
  		if (dir) {
  		    picker.displayDirectory = new nsLocalFile(dir);
  		}
 -		picker.appendFilter(Redirector.getString('redirectorFiles'), '*.rdx');
 +		picker.appendFilter(this.strings.getString('redirectorFiles'), '*.rdx');
  		if (picker.show() == picker.returnCancel) {
 -		    return;
 -		}
 -		try {
 -			Redirector.prefs.defaultDir = picker.displayDirectory.path;
 -		    return func(picker.file);
 -		} catch (e) {
 -		    alert(e);
 +		    return null;
  		}
 +		this.prefs.defaultDir = picker.displayDirectory.path;
 +		return picker.file;
      },
      export : function() {
 -		this.importExport(Ci.nsIFilePicker.modeSave, 'exportCaption', function(file) {
 +	    var file = this.getFile('exportCaption', Ci.nsIFilePicker.modeSave);
 +	    if (file) {
  			Redirector.exportRedirects(file);
 -		});
 +	    }
      },
      import : function() {
 -		var result = this.importExport(Ci.nsIFilePicker.modeOpen, 'importCaption', function(file) {
 -			return Redirector.importRedirects(file);
 -		});
 -
 -		var msg
 +	    var file = this.getFile('importCaption', Ci.nsIFilePicker.modeOpen);
 +	    var result;
 +	    if (file) {
 +			result = Redirector.importRedirects(file);
 +	    }
 +	    
 +		var msg, imported, existed;
 +		imported = result & 0xFFFF;
 +		existed = result >> 16;
 -		if (result.imported > 0) {
 -			msg = this.strings.getPluralized('importedMessage', result.imported);
 -			if (result.existed > 0) {
 -				msg += ', ' + this.strings.getPluralized('existedMessage',result.existed);	
 +		if (imported > 0) {
 +			msg = this.strings.getPluralized('importedMessage', imported);
 +			if (existed > 0) {
 +				msg += ', ' + this.strings.getPluralized('existedMessage',existed);	
  			} else {
  				msg += '.';	
  			}
 -		} else if (result.imported == 0 && result.existed > 0) {
 -			msg = this.strings.getPluralized('allExistedMessage', result.existed);
 +		} else if (imported == 0 && existed > 0) {
 +			msg = this.strings.getPluralized('allExistedMessage', existed);
  		} else { //Both 0
  			msg = this.strings.getString('importedNone');
  		}
 @@ -266,10 +265,10 @@ var Settings = {  		var title = this.strings.getString("importResult");
          Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService).alert(null, title, msg);
 -		if (result.imported > 0) {
 +		if (imported > 0) {
  			var newlist = [];
 -			for (var i = Redirector.list.length-result.imported; i < Redirector.list.length; i++) {
 -				newlist.push(Redirector.list[i]);
 +			for (var i = Redirector.redirectCount-result.imported; i < Redirector.redirectCount; i++) {
 +				newlist.push(Redirector.getRedirectAt(i));
  			}				
          	this.addItemsToListBox(newlist);
  		}
 diff --git a/chrome/content/ui/browserOverlay.xul b/chrome/content/ui/browserOverlay.xul index 7b40c65..d67928c 100644 --- a/chrome/content/ui/browserOverlay.xul +++ b/chrome/content/ui/browserOverlay.xul @@ -4,6 +4,7 @@  <overlay id="redirector-overlay"    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">    <script src="../code/redirect.js"/> +  <script src="../code/prefs.js"/>    <script src="../code/browserOverlay.xul.js"/>    <stringbundleset id="stringbundleset"> diff --git a/chrome/content/ui/settings.xul b/chrome/content/ui/settings.xul index 141c5ef..cc9cbf4 100644 --- a/chrome/content/ui/settings.xul +++ b/chrome/content/ui/settings.xul @@ -16,6 +16,7 @@  		xmlns:nc="http://home.netscape.com/NC-rdf#"
          xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
 +	<script type="application/x-javascript" src="../code/prefs.js"/>
  	<script type="application/x-javascript" src="../code/redirect.js"/>
  	<script type="application/x-javascript" src="../code/settings.xul.js"/>
  	<stringbundleset id="stringbundleset">
 diff --git a/chrome/content/unittest/run.html b/chrome/content/unittest/run.html index 1557610..57970d1 100644 --- a/chrome/content/unittest/run.html +++ b/chrome/content/unittest/run.html @@ -16,7 +16,7 @@  		//Global variables
  		var subscriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
 -		var redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.nsISupports).wrappedJSObject;
 +		var redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.rdIRedirector);
  		function setupTest(name, testcase) {
  			var table = document.createElement('table');
 diff --git a/chrome/content/unittest/testcases.js b/chrome/content/unittest/testcases.js index 0ce071e..afefff7 100644 --- a/chrome/content/unittest/testcases.js +++ b/chrome/content/unittest/testcases.js @@ -95,7 +95,8 @@ var tests = {  				var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);  
  				args.contentLocation = ioService.newURI(args.contentLocation, null, null);
 -				var result = redirector.shouldLoad(args.contentType, args.contentLocation, args.requestOrigin, args.aContext, args.mimeTypeGuess, args.extra);
 +				var contentPolicy = redirector.QueryInterface(nsIContentPolicy);
 +				var result = contentPolicy.shouldLoad(args.contentType, args.contentLocation, args.requestOrigin, args.aContext, args.mimeTypeGuess, args.extra);
  				return { passed: result == nsIContentPolicy.ACCEPT, message : "Expected nsIContentPolicy.ACCEPT, actual was " + result };
  			}
 @@ -116,6 +117,8 @@ var tests = {  				try {
  					redirector.enabled = false;
  					return doFunc();
 +					redirector.enabled = true;
 +
  				} catch(e) {
  					redirector.enabled = true;
  					throw e;	
 diff --git a/components/interfaces/nsIFile.idl b/components/interfaces/nsIFile.idl new file mode 100644 index 0000000..cf97192 --- /dev/null +++ b/components/interfaces/nsIFile.idl @@ -0,0 +1,343 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is Mozilla Communicator client code, released + * March 31, 1998. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998-1999 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + *   Doug Turner <dougt@netscape.com> + *   Christopher Blizzard <blizzard@mozilla.org> + *   Darin Fisher <darin@netscape.com> + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +interface nsISimpleEnumerator; + +/** + * This is the only correct cross-platform way to specify a file. + * Strings are not such a way. If you grew up on windows or unix, you + * may think they are.  Welcome to reality. + * + * All methods with string parameters have two forms.  The preferred + * form operates on UCS-2 encoded characters strings.  An alternate + * form operates on characters strings encoded in the "native" charset. + * + * A string containing characters encoded in the native charset cannot + * be safely passed to javascript via xpconnect.  Therefore, the "native + * methods" are not scriptable.  + * + * @status FROZEN + */ +[scriptable, uuid(c8c0a080-0868-11d3-915f-d9d889d48e3c)] +interface nsIFile : nsISupports +{ +    /** +     *  Create Types +     * +     *  NORMAL_FILE_TYPE - A normal file. +     *  DIRECTORY_TYPE   - A directory/folder. +     */ +    const unsigned long NORMAL_FILE_TYPE = 0; +    const unsigned long DIRECTORY_TYPE   = 1; + +    /** +     *  append[Native] +     * +     *  This function is used for constructing a descendent of the +     *  current nsIFile. +     * +     *   @param node +     *       A string which is intended to be a child node of the nsIFile. +     *       For the |appendNative| method, the node must be in the native +     *       filesystem charset. +     */ +    void append(in AString node); +    [noscript] void appendNative(in ACString node); + +    /** +     *  Normalize the pathName (e.g. removing .. and . components on Unix). +     */ +    void normalize(); + +    /** +     *  create +     * +     *  This function will create a new file or directory in the +     *  file system. Any nodes that have not been created or +     *  resolved, will be.  If the file or directory already +     *  exists create() will return NS_ERROR_FILE_ALREADY_EXISTS. +     * +     *   @param type +     *       This specifies the type of file system object +     *       to be made.  The only two types at this time +     *       are file and directory which are defined above. +     *       If the type is unrecongnized, we will return an +     *       error (NS_ERROR_FILE_UNKNOWN_TYPE). +     * +     *   @param permissions +     *       The unix style octal permissions.  This may +     *       be ignored on systems that do not need to do +     *       permissions. +     */ +    void create(in unsigned long type, in unsigned long permissions); + +    /** +     *  Accessor to the leaf name of the file itself.       +     *  For the |nativeLeafName| method, the nativeLeafName must  +     *  be in the native filesystem charset. +     */ +    attribute AString leafName; +    [noscript] attribute ACString nativeLeafName; + +    /** +     *  copyTo[Native] +     * +     *  This will copy this file to the specified newParentDir. +     *  If a newName is specified, the file will be renamed. +     *  If 'this' is not created we will return an error +     *  (NS_ERROR_FILE_TARGET_DOES_NOT_EXIST). +     * +     *  copyTo may fail if the file already exists in the destination  +     *  directory. +     * +     *  copyTo will NOT resolve aliases/shortcuts during the copy. +     * +     *   @param newParentDir +     *       This param is the destination directory. If the +     *       newParentDir is null, copyTo() will use the parent +     *       directory of this file. If the newParentDir is not +     *       empty and is not a directory, an error will be +     *       returned (NS_ERROR_FILE_DESTINATION_NOT_DIR). For the  +     *       |CopyToNative| method, the newName must be in the  +     *       native filesystem charset. +     * +     *   @param newName +     *       This param allows you to specify a new name for +     *       the file to be copied. This param may be empty, in +     *       which case the current leaf name will be used. +     */ +    void copyTo(in nsIFile newParentDir, in AString newName); +    [noscript] void CopyToNative(in nsIFile newParentDir, in ACString newName); + +    /** +     *  copyToFollowingLinks[Native] +     * +     *  This function is identical to copyTo with the exception that, +     *  as the name implies, it follows symbolic links.  The XP_UNIX +     *  implementation always follow symbolic links when copying.  For  +     *  the |CopyToFollowingLinks| method, the newName must be in the  +     *  native filesystem charset. +     */ +    void copyToFollowingLinks(in nsIFile newParentDir, in AString newName); +    [noscript] void copyToFollowingLinksNative(in nsIFile newParentDir, in ACString newName); + +    /** +     *  moveTo[Native] +     * +     *  A method to move this file or directory to newParentDir. +     *  If a newName is specified, the file or directory will be renamed. +     *  If 'this' is not created we will return an error +     *  (NS_ERROR_FILE_TARGET_DOES_NOT_EXIST). +     *  If 'this' is a file, and the destination file already exists, moveTo +     *  will replace the old file. +     * +     *  moveTo will NOT resolve aliases/shortcuts during the copy. +     *  moveTo will do the right thing and allow copies across volumes. +     *  moveTo will return an error (NS_ERROR_FILE_DIR_NOT_EMPTY) if 'this' is +     *  a directory and the destination directory is not empty. +     *  moveTo will return an error (NS_ERROR_FILE_ACCESS_DENIED) if 'this' is +     *  a directory and the destination directory is not writable. +     * +     *   @param newParentDir +     *       This param is the destination directory. If the +     *       newParentDir is empty, moveTo() will rename the file +     *       within its current directory. If the newParentDir is +     *       not empty and does not name a directory, an error will +     *       be returned (NS_ERROR_FILE_DESTINATION_NOT_DIR).  For  +     *       the |moveToNative| method, the newName must be in the  +     *       native filesystem charset. +     * +     *   @param newName +     *       This param allows you to specify a new name for +     *       the file to be moved. This param may be empty, in +     *       which case the current leaf name will be used. +     */ +    void moveTo(in nsIFile newParentDir, in AString newName); +    [noscript] void moveToNative(in nsIFile newParentDir, in ACString newName); + +    /** +     *  This will try to delete this file.  The 'recursive' flag +     *  must be PR_TRUE to delete directories which are not empty. +     * +     *  This will not resolve any symlinks. +     */ +    void remove(in boolean recursive); + +    /** +     *  Attributes of nsIFile. +     */ + +    attribute unsigned long permissions; +    attribute unsigned long permissionsOfLink; + +    /** +     *  File Times are to be in milliseconds from +     *  midnight (00:00:00), January 1, 1970 Greenwich Mean +     *  Time (GMT). +     */ +    attribute PRInt64 lastModifiedTime; +    attribute PRInt64 lastModifiedTimeOfLink; + +    /** +     *  WARNING!  On the Mac, getting/setting the file size with nsIFile +     *  only deals with the size of the data fork.  If you need to +     *  know the size of the combined data and resource forks use the +     *  GetFileSizeWithResFork() method defined on nsILocalFileMac. +     */ +    attribute PRInt64 fileSize; +    readonly attribute PRInt64 fileSizeOfLink; + +    /** +     *  target & path +     * +     *  Accessor to the string path.  The native version of these +     *  strings are not guaranteed to be a usable path to pass to +     *  NSPR or the C stdlib.  There are problems that affect +     *  platforms on which a path does not fully specify a file +     *  because two volumes can have the same name (e.g., mac). +     *  This is solved by holding "private", native data in the +     *  nsIFile implementation.  This native data is lost when +     *  you convert to a string. +     * +     *      DO NOT PASS TO USE WITH NSPR OR STDLIB! +     * +     *  target +     *      Find out what the symlink points at.  Will give error +     *      (NS_ERROR_FILE_INVALID_PATH) if not a symlink. +     * +     *  path +     *      Find out what the nsIFile points at. +     * +     *  Note that the ACString attributes are returned in the  +     *  native filesystem charset. +     * +     */ +    readonly attribute AString target; +    [noscript] readonly attribute ACString nativeTarget; +    readonly attribute AString path; +    [noscript] readonly attribute ACString nativePath; + +    boolean exists(); +    boolean isWritable(); +    boolean isReadable(); +    boolean isExecutable(); +    boolean isHidden(); +    boolean isDirectory(); +    boolean isFile(); +    boolean isSymlink(); +    /** +     * Not a regular file, not a directory, not a symlink. +     */ +    boolean isSpecial(); + +    /** +     *  createUnique +     *   +     *  This function will create a new file or directory in the +     *  file system. Any nodes that have not been created or +     *  resolved, will be.  If this file already exists, we try +     *  variations on the leaf name "suggestedName" until we find +     *  one that did not already exist. +     * +     *  If the search for nonexistent files takes too long +     *  (thousands of the variants already exist), we give up and +     *  return NS_ERROR_FILE_TOO_BIG. +     * +     *   @param type +     *       This specifies the type of file system object +     *       to be made.  The only two types at this time +     *       are file and directory which are defined above. +     *       If the type is unrecongnized, we will return an +     *       error (NS_ERROR_FILE_UNKNOWN_TYPE). +     * +     *   @param permissions +     *       The unix style octal permissions.  This may +     *       be ignored on systems that do not need to do +     *       permissions. +     */ +    void createUnique(in unsigned long type, in unsigned long permissions); + +    /** +      * clone() +      * +      * This function will allocate and initialize a nsIFile object to the +      * exact location of the |this| nsIFile. +      * +      *   @param file +      *          A nsIFile which this object will be initialize +      *          with. +      * +      */ +    nsIFile clone(); + +    /** +     *  Will determine if the inFile equals this. +     */ +    boolean equals(in nsIFile inFile); + +    /** +     *  Will determine if inFile is a descendant of this file +     *  If |recur| is true, look in subdirectories too +     */ +    boolean contains(in nsIFile inFile, in boolean recur); + +    /** +     *  Parent will be null when this is at the top of the volume. +     */ +    readonly attribute nsIFile parent; +     +    /** +     *  Returns an enumeration of the elements in a directory. Each +     *  element in the enumeration is an nsIFile. +     * +     *   @return NS_ERROR_FILE_NOT_DIRECTORY if the current nsIFile does +     *           not specify a directory. +     */ +    readonly attribute nsISimpleEnumerator directoryEntries; +}; + +%{C++ +#ifdef MOZILLA_INTERNAL_API +#include "nsDirectoryServiceUtils.h" +#endif +%} diff --git a/components/interfaces/nsISimpleEnumerator.idl b/components/interfaces/nsISimpleEnumerator.idl new file mode 100644 index 0000000..3f0efbf --- /dev/null +++ b/components/interfaces/nsISimpleEnumerator.idl @@ -0,0 +1,81 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is mozilla.org code. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either of the GNU General Public License Version 2 or later (the "GPL"), + * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "nsISupports.idl" + +/** + * Used to enumerate over elements defined by its implementor. + * Although hasMoreElements() can be called independently of getNext(), + * getNext() must be pre-ceeded by a call to hasMoreElements(). There is + * no way to "reset" an enumerator, once you obtain one. + * + * @status FROZEN + * @version 1.0 + */ + +[scriptable, uuid(D1899240-F9D2-11D2-BDD6-000064657374)] +interface nsISimpleEnumerator : nsISupports { +  /** +   * Called to determine whether or not the enumerator has +   * any elements that can be returned via getNext(). This method +   * is generally used to determine whether or not to initiate or +   * continue iteration over the enumerator, though it can be +   * called without subsequent getNext() calls. Does not affect +   * internal state of enumerator. +   * +   * @see getNext() +   * @return PR_TRUE if there are remaining elements in the enumerator. +   *         PR_FALSE if there are no more elements in the enumerator. +   */                                             +  boolean hasMoreElements(); + +  /** +   * Called to retrieve the next element in the enumerator. The "next" +   * element is the first element upon the first call. Must be +   * pre-ceeded by a call to hasMoreElements() which returns PR_TRUE. +   * This method is generally called within a loop to iterate over +   * the elements in the enumerator. +   * +   * @see hasMoreElements() +   * @return NS_OK if the call succeeded in returning a non-null +   *               value through the out parameter. +   *         NS_ERROR_FAILURE if there are no more elements +   *                          to enumerate. +   * @return the next element in the enumeration. +   */ +  nsISupports getNext(); +}; diff --git a/components/interfaces/rdIMatchResult.idl b/components/interfaces/rdIMatchResult.idl new file mode 100644 index 0000000..edf13b4 --- /dev/null +++ b/components/interfaces/rdIMatchResult.idl @@ -0,0 +1,17 @@ +/* $Id */
 +#include "nsISupports.idl"
 +
 +[scriptable, uuid(cf89b480-bce3-11de-a0dd-028037ec0200)]
 +interface rdIMatchResult : nsISupports {
 +	
 +	/* Result constants */
 +	const short NO_MATCH = 0;
 +	const short MATCH = 1;
 +	const short DISABLED_MATCH = 2;
 +	const short EXCLUDED_MATCH = 3;
 +
 +	/* Attributes */
 +	attribute wstring redirectTo;	
 +	attribute short result;
 +};
 +
 diff --git a/components/interfaces/rdIRedirect.idl b/components/interfaces/rdIRedirect.idl index 32d8494..76c3960 100644 --- a/components/interfaces/rdIRedirect.idl +++ b/components/interfaces/rdIRedirect.idl @@ -1,8 +1,29 @@  /* $Id */  #include "nsISupports.idl" +#include "rdIMatchResult.idl"  [scriptable, uuid(cb69ddf0-bce1-11de-8251-028037ec0200)]  interface rdIRedirect : nsISupports { -	void test(); +	 +	/* Attributes */ +	attribute wstring exampleUrl;	 +	attribute wstring includePattern; +	attribute wstring excludePattern; +	attribute wstring redirectTo; +	attribute wchar patternType; +	attribute boolean unescapeMatches; +	attribute boolean disabled; +	 +	/* Methods */ +	rdIRedirect clone(); +	void compile(); +	void copyValues(in rdIRedirect other); +	void deserialize(in wstring data); +	boolean equals(in rdIRedirect other); +	rdIMatchResult getMatch(in wstring url);  +	boolean isRegex(); +	boolean isWildcard(); +	wstring serialize(); +	rdIMatchResult test(in wstring url);   }; diff --git a/components/interfaces/rdIRedirector.idl b/components/interfaces/rdIRedirector.idl index d229263..f586dfb 100644 --- a/components/interfaces/rdIRedirector.idl +++ b/components/interfaces/rdIRedirector.idl @@ -1,9 +1,23 @@  /* $Id */  #include "nsISupports.idl" +#include "nsIFile.idl"  #include "rdIRedirect.idl"  [scriptable, uuid(cdf25d91-bce1-11de-aee1-028037ec0200)]  interface rdIRedirector : nsISupports { -	void test(); + +	attribute boolean enabled; +	readonly attribute short redirectCount; +	 +	void addRedirect(in rdIRedirect redirect); +	void debug(in wstring msg); +	void deleteRedirectAt(in short index); +	void exportRedirects(in nsIFile file); +	rdIRedirect getRedirectAt(in short index); +	wstring getRedirectUrl(in wstring url); +	long importRedirects(in nsIFile file); +	void reload(); +	void save(); +	void switchItems(in short index1, in short index2);  }; diff --git a/components/redirector.component.js b/components/redirector.component.js index e5f20f4..73219ad 100644 --- a/components/redirector.component.js +++ b/components/redirector.component.js @@ -8,8 +8,7 @@ const loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSS  var redirector = null;
  function Redirector() {
 -	this.init();
 -	this.wrappedJSObject = this;
 +	this._init();
  }
  try {
 @@ -28,7 +27,7 @@ xpcomInfo.classDescription 	= "Redirector Component";  xpcomInfo.classID 			= Components.ID("{b7a7a54f-0581-47ff-b086-d6920cb7a3f7}");
  xpcomInfo.contractID 		= "@einaregilsson.com/redirector;1";
  xpcomInfo._xpcom_categories = [{category:'content-policy'},{category:'net-channel-event-sinks'}];
 -xpcomInfo.QueryInterface 	= XPCOMUtils.generateQI([Ci.nsIContentPolicy, Ci.nsIChannelEventSink]);
 +xpcomInfo.QueryInterface 	= XPCOMUtils.generateQI([Ci.nsIContentPolicy, Ci.nsIChannelEventSink, Ci.rdIRedirector]);
  xpcomInfo._xpcom_factory 	= {
  	createInstance: function(outer, iid) {
  		if (outer) throw Cr.NS_ERROR_NO_AGGREGATION;
 | 
