home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 127 / PC Guia 127.iso / Software / Utils / Fasterfox / Bin / fasterfox-1.0.3-fx.xpi / chrome / fasterfox.jar / content / fasterfox / fasterfoxOverlay.js < prev    next >
Encoding:
JavaScript  |  2006-01-16  |  11.2 KB  |  324 lines

  1. /* ***** BEGIN LICENSE BLOCK *****
  2.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  3.  *
  4.  * The contents of this file are subject to the Mozilla Public License Version
  5.  * 1.1 (the "License"); you may not use this file except in compliance with
  6.  * the License. You may obtain a copy of the License at
  7.  * http://www.mozilla.org/MPL/
  8.  *
  9.  * Software distributed under the License is distributed on an "AS IS" basis,
  10.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  11.  * for the specific language governing rights and limitations under the
  12.  * License.
  13.  *
  14.  * The Original Code is Fasterfox.
  15.  *
  16.  * The Initial Developer of the Original Code is
  17.  * Tony Gentilcore.
  18.  * Portions created by the Initial Developer are Copyright (C) 2005
  19.  * the Initial Developer. All Rights Reserved.
  20.  *
  21.  * Contributor(s):
  22.  *  See readme.txt
  23.  *
  24.  * Alternatively, the contents of this file may be used under the terms of
  25.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  26.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  27.  * in which case the provisions of the GPL or the LGPL are applicable instead
  28.  * of those above. If you wish to allow use of your version of this file only
  29.  * under the terms of either the GPL or the LGPL, and not to allow others to
  30.  * use your version of this file under the terms of the MPL, indicate your
  31.  * decision by deleting the provisions above and replace them with the notice
  32.  * and other provisions required by the GPL or the LGPL. If you do not delete
  33.  * the provisions above, a recipient may use your version of this file under
  34.  * the terms of any one of the MPL, the GPL or the LGPL.
  35.  *
  36.  * ***** END LICENSE BLOCK ***** */
  37.  
  38. // local references to XPCOM services
  39. var PrefetchService = Components.classes["@mozilla.org/prefetch-service;1"].getService(Components.interfaces.nsIPrefetchService);
  40. var PreferencesService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  41.  
  42. // Timer global variables
  43. var StartTime;
  44. var StopTime;
  45. var Finished;
  46.  
  47. // Robots.txt cache
  48. var robotsCacheMax = 64;
  49. var robotsCacheTop = 0;
  50. var robotsCache = new Array(robotsCacheMax);
  51. var optOut = new Array(robotsCacheMax);
  52.  
  53. // Setup the extension core
  54. function FF_init() {    
  55.  
  56.     // because of the nature of overlays and the panel selection code,
  57.     // this is reproduced from chrome://browser/content/pref/pref.xul, and
  58.     // refocuses the prefsCategories window in order to ensure a clean and
  59.     // correct selection of the right panel
  60.     var prefsCategories = document.getElementById("prefsCategories");
  61.     if (prefsCategories) {
  62.          var lastPanel = 0, button;
  63.         try {
  64.              lastPanel = PreferencesService.getIntPref("browser.preferences.lastpanel");
  65.         } 
  66.         catch (e) {}
  67.  
  68.         prefsCategories.focus();
  69.         button = prefsCategories.childNodes[lastPanel];
  70.         if (button) {
  71.             document.getElementById("panelFrame").setAttribute("src", button.getAttribute("url"));
  72.             button.checked = true;
  73.         }
  74.     }
  75.         
  76.     // Register the web progress listener for the page load timer
  77.     gBrowser.addProgressListener(ffListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
  78.     
  79.     // show or hide the timer
  80.     if(PreferencesService.getBoolPref("extensions.fasterfox.pageLoadTimer", true)) {
  81.         document.getElementById("fasterfox-statusbar").setAttribute("hidden", "false");
  82.     } else {
  83.         document.getElementById("fasterfox-statusbar").setAttribute("hidden", "true");
  84.     }
  85.  
  86.       return true;
  87. }
  88.  
  89. // Tear down the extension
  90. function FF_uninit() {
  91.     gBrowser.removeProgressListener(ffListener);
  92. }
  93.  
  94. // GetAbsoluteURL
  95. function getAbsoluteUrl(url, docUrl) { 
  96.     if(url && url.indexOf('://')>0) return url;
  97.     docUrl=(docUrl)? docUrl.substring(0,docUrl.lastIndexOf('/')+1):dynapi.documentPath;
  98.     url=url.replace(/^(.\/)*/,'');
  99.     docUrl=docUrl.replace(/(\?.*)$/,'').replace(/(#.*)*$/,'').replace(/[^\/]*$/,'');
  100.     if (url.indexOf('/')==0) return docUrl.substring(0,docUrl.indexOf('/',docUrl.indexOf('//')+2))+url;
  101.     else while(url.indexOf('../')==0){
  102.         url=url.replace(/^..\//,'');
  103.         docUrl=docUrl.replace(/([^\/]+[\/][^\/]*)$/,'');
  104.     };
  105.     return docUrl+url;
  106. }
  107.  
  108. // Gets the base url
  109. function getBaseURL(url) {
  110.     var startPos = url.indexOf("://")+3;
  111.     var endPos = url.indexOf('/', startPos);
  112.     if (endPos < 0) endPos = url.length;
  113.     var baseUrl = url.substring(0, endPos);
  114.     return baseUrl;
  115. }
  116.  
  117. // Checks a given site's robots.txt file to see if they wish to opt-out of prefetching
  118. function isSiteOptOut(url, aEvent, pos) {
  119.     var fileName = getBaseURL(url) + "/robots.txt";
  120.     
  121.     // load from cache if possible
  122.     var i;
  123.     for(i = 0; i < robotsCacheMax; i++) {
  124.         if(fileName == robotsCache[i]) {
  125.             return optOut[i];
  126.         }
  127.     }
  128.     
  129.     // it is not cached, so load it
  130.     var req = new XMLHttpRequest();
  131.     req.open("GET", fileName, true); 
  132.     req.onreadystatechange = function () {
  133.         if (req.readyState == 4) {
  134.             if (req.status == 200) {
  135.                 var result = (req.responseText.toLowerCase().indexOf("fasterfox")>=0);
  136.                 robotsCacheTop = (robotsCacheTop+1) % robotsCacheMax;
  137.                 robotsCache[robotsCacheTop] = fileName;
  138.                 optOut[robotsCacheTop] = result;
  139.                 //doEnhancedPrefetch(aEvent, pos);
  140.             }
  141.         }
  142.     };
  143.     req.send(null);
  144.         
  145.     return -1;
  146. }
  147.  
  148. // Converts a string URL into a URI object
  149. function makeURI(aURL) {
  150.     var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
  151.     return ioService.newURI(aURL, null, null);
  152. }
  153.  
  154. // Iterates through all the <a> links on a page and adds 
  155. // them to the queue to be prefetched.
  156. function doEnhancedPrefetch(aEvent, pos) {
  157.  
  158.     // exit if enhanced prefetching is turned off
  159.     // or if the site has opted out of prefetching
  160.     if(!PreferencesService.getBoolPref("extensions.fasterfox.enhancedPrefetching")) return;
  161.     
  162.     // doc is document that triggered "onload" event
  163.     var doc = aEvent.originalTarget; 
  164.     
  165.     // if this isn't an http:// page, retun
  166.     if (doc.location.href.indexOf("http://") != 0) return;
  167.         
  168.     // load whitelist
  169.     var whitelist = PreferencesService.getCharPref("extensions.fasterfox.whitelist").split(",");
  170.     var whitelistLen = whitelist.length;
  171.     
  172.     // find all links
  173.     var a = doc.getElementsByTagName('a');
  174.     var href, numLinksToPrefetch, i, j;
  175.     
  176.     // prefetch a max of 100 links
  177.     numLinksToPrefetch = (a.length>100) ? 100 : a.length;
  178.  
  179.     // if its the first time, set the pos to 0,
  180.     // if a pos was passed in, we'll start the for loop there instead
  181.     if (pos == null || pos <=0) pos = 0;
  182.     
  183.     // iterate through the links
  184.     mainLinkLoop: 
  185.     for (i=pos; i<numLinksToPrefetch; i++) {
  186.         href = a[i].getAttribute('href').toLowerCase();
  187.         
  188.         // make sure there is a link
  189.         if(href && href.length > 4) {
  190.  
  191.             // Don't prefetch links w/ query strings
  192.             // or the same page we are on
  193.             if(href.indexOf('?')>=0 || href == doc.location.href) continue;
  194.             
  195.             // Don't prefetch things that look like a logout link
  196.             // Special thanks to b1naryb0y and Kai Risku for this bug fix
  197.             if(href.indexOf('logout')>=0 || href.indexOf('logoff')>=0) continue;
  198.             
  199.             // Only prefetch static content, this causes dynamic pages to be ignored
  200.             fileExtensionStartPos = href.length-4;
  201.             if(!(href.indexOf('.htm') == fileExtensionStartPos 
  202.               || href.indexOf('.html') == fileExtensionStartPos-1
  203.               || href.indexOf('.jpg') == fileExtensionStartPos
  204.               || href.indexOf('.gif') == fileExtensionStartPos
  205.               || href.indexOf('.png') == fileExtensionStartPos
  206.               || href.indexOf('.jpeg') == fileExtensionStartPos-1
  207.               || href.indexOf('.txt') == fileExtensionStartPos
  208.               || href.indexOf('.text') == fileExtensionStartPos-1
  209.               || href.indexOf('.xml') == fileExtensionStartPos
  210.               || href.indexOf('.pdf') == fileExtensionStartPos)) continue;
  211.               
  212.             // Don't prefetch whitelist links
  213.             href = getAbsoluteUrl(href, doc.location.href);
  214.             for(j=0; j<whitelistLen; j++) {
  215.                 if(whitelist[j].length > 0 && href.indexOf(whitelist[j]) >= 0) continue mainLinkLoop;                
  216.             }
  217.             
  218.             // test if site is opting out of prefetching
  219.             var shouldOptOut = isSiteOptOut(href, aEvent, i);
  220.             if(shouldOptOut) {
  221.                 continue;
  222.             } else if (shouldOptOut == -1) {
  223.                 return;
  224.             }
  225.             
  226.             try {
  227.                 PrefetchService.prefetchURI(makeURI(getAbsoluteUrl(a[i].getAttribute('href'), doc.location.href)), makeURI(doc.location.href), true);
  228.                } catch(e) { 
  229.                 //if(e.name != "NS_ERROR_ABORT") alert(getAbsoluteUrl(href, doc.location.href) + '\n' + e.toString()); 
  230.             }
  231.         }
  232.     }
  233.  
  234. }
  235.  
  236. // Converts a Delta date into an english string
  237. // showMilliseconds = true, gives fractions of seconds
  238. // showMilliseconds = false, gives whole seconds
  239. function TimeStr(delta, showMilliseconds) {
  240.  
  241.     // Calc seconds and milliseconds
  242.     var mseconds = delta % 1000;
  243.     delta = (delta - mseconds) / 1000;
  244.     var seconds = delta.toString(); 
  245.     
  246.     if(showMilliseconds) {
  247.         mseconds = mseconds.toString(); 
  248.         var pd = ''; var i;
  249.         if (3 > mseconds.length) { 
  250.                for (i = 0; i < (3-mseconds.length); i++) { 
  251.                 pd += '0'; 
  252.             } 
  253.         } 
  254.         mseconds = mseconds + pd;
  255.     } else {
  256.         mseconds = "000";
  257.     }
  258.     
  259.     return(seconds + "." + mseconds + "s");
  260. }
  261.  
  262. // Updates the display of the page load timer
  263. function ff_updateTimer() {
  264.     var Delta;
  265.     if (!Finished) {
  266.         CurrentTime = new Date();
  267.         Delta = CurrentTime.getTime() - StartTime.getTime();
  268.         document.getElementById("fasterfox-label").value = TimeStr(Delta, false);
  269.         setTimeout('ff_updateTimer()',1000);
  270.     } else {
  271.         Delta = StopTime.getTime() - StartTime.getTime();
  272.         document.getElementById("fasterfox-label").value = TimeStr(Delta, true);
  273.     }
  274. }
  275.  
  276. // Ends page load timer
  277. function ff_stopTimer() {
  278.     // Stop timer
  279.     StopTime = new Date();
  280.     Finished = true;
  281.     ff_updateTimer();    
  282. }
  283.  
  284. // Starts page load timer
  285. function ff_startTimer() {
  286.     // Start timer  
  287.     StartTime = new Date();
  288.     Finished = false;
  289.     ff_updateTimer();    
  290. }
  291.  
  292. // Show or hide the page load timer
  293. // if show = true, it will be displayed
  294. // if show = false, it will be hidden
  295. function ff_showTimer(show) {
  296.     PreferencesService.setBoolPref("extensions.fasterfox.pageLoadTimer", show);    
  297.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  298.                        .getService(Components.interfaces.nsIWindowMediator);
  299.     var win = wm.getMostRecentWindow("navigator:browser");
  300.     if (win) {
  301.         win.document.getElementById("fasterfox-statusbar").setAttribute("collapsed", !show);
  302.         win.document.getElementById("fasterfox-label").value = "Fasterfox";
  303.    }
  304. }
  305.  
  306. // Clears the browser disk and memory cache
  307. function ff_clearCache() {
  308.     var cacheService = Components.classes["@mozilla.org/network/cache-service;1"]
  309.                                  .getService(Components.interfaces.nsICacheService);
  310.         cacheService.evictEntries(Components.interfaces.nsICache.STORE_ON_DISK);
  311.         cacheService.evictEntries(Components.interfaces.nsICache.STORE_IN_MEMORY);
  312. }
  313.  
  314. // Shows the Fasterfox options pane
  315. function ff_openOptions() {
  316.     var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
  317.                        .getService(Components.interfaces.nsIWindowMediator);
  318.     var win = wm.getMostRecentWindow("Fasterfox:Options");
  319.     if (win) {
  320.         win.focus();
  321.     } else {
  322.         openDialog("chrome://fasterfox/content/pref-fasterfox.xul", "", "chrome,titlebar,toolbar,centerscreen,modal");
  323.     }
  324. }