home *** CD-ROM | disk | FTP | other *** search
/ PC World 2006 December / PCWorld_2006-12_cd.bin / komunikace / netscape / nsb-install-8-1-2.exe / chrome / browser.jar / content / browser / search.js < prev    next >
Text File  |  2006-01-06  |  30KB  |  807 lines

  1. var search = {
  2.  
  3.     // Set this to false to disable debug output
  4.     SEARCH_DEBUG : true,    
  5.  
  6.     // Constants
  7.     MAX_HISTORY_SIZE : 10,
  8.     SEARCH_PLUGINS_FOLDER : "searchplugins",
  9.     SEARCH_PROVIDER_RDF_FILE : "search-providers.rdf",
  10.     SEARCH_HISTORY_FILE : "search-history.txt",
  11.     SEARCH_TAG : "search:",
  12.  
  13.     // File open flags (from prio.h) 
  14.     PR_RDONLY : 1,
  15.     PR_WRONLY : 2,
  16.     PR_TRUNCATE : 4,
  17.  
  18.     // RDF Predicates
  19.     SPUI_NS : "http://home.netscape.com/NC-spui#",
  20.     RES_NAME : null,
  21.     RES_ICON : null,
  22.     RES_SRC : null,
  23.  
  24.     // Globals
  25.     profileDir : null,
  26.     ioService : null,
  27.     prefService : null,
  28.     RDFService : null,
  29.     httpService : null, 
  30.     localRDFLoadObserver : null,
  31.     remoteRDFLoadObserver : null,
  32.     remoteRDFFetchURL : null,
  33.     searchProviderList : new Array(),
  34.     mRemoteLoadError : false,
  35.     mRemoteLoadErrorCount : null,
  36.  
  37.  
  38.     Init : function() {
  39.         this.mRemoteLoadErrorCount = 10;
  40.         this.mRemoteLoadError = false;
  41.         this.debug('Init()');
  42.  
  43.         // Get the user's profile directory
  44.         if (!this.profileDir) {
  45.             this.profileDir = Components.classes["@mozilla.org/file/directory_service;1"]
  46.                                         .getService(Components.interfaces.nsIProperties)
  47.                                         .get("ProfD", Components.interfaces.nsILocalFile);
  48.         }
  49.         this.debug('profileDir: '+this.profileDir.path);
  50.  
  51.         // IO Service
  52.         if (!this.ioService) {
  53.             this.ioService = Components.classes["@mozilla.org/network/io-service;1"]
  54.                                        .getService(Components.interfaces.nsIIOService);
  55.         }
  56.  
  57.         // Pref Service
  58.         if (!this.prefService) {
  59.             this.prefService = Components.classes["@mozilla.org/preferences-service;1"]
  60.                                          .getService(Components.interfaces.nsIPrefBranch);
  61.         }
  62.  
  63.         // RDF Service
  64.         if (!this.RDFService) {
  65.             this.RDFService = Components.classes["@mozilla.org/rdf/rdf-service;1"]
  66.                                         .getService(Components.interfaces.nsIRDFService);
  67.         }
  68.  
  69.         // HTTP Service
  70.         if (!this.httpService) {
  71.             this.httpService = Components.classes["@mozilla.org/network/protocol;1?name=http"]
  72.                                          .getService(Components.interfaces.nsIHttpProtocolHandler);
  73.         }
  74.  
  75.         // RDF Predicates
  76.         this.RES_NAME = this.RDFService.GetResource(this.SPUI_NS+'name');
  77.         this.RES_ICON = this.RDFService.GetResource(this.SPUI_NS+'icon');
  78.         this.RES_SRC = this.RDFService.GetResource(this.SPUI_NS+'src');
  79.  
  80.         // Local RDF Load Observer
  81.         // ... watches loading of the *local* search-providers.rdf file
  82.         if (!this.localRDFLoadObserver) {
  83.             this.debug(' instanciating local RDF load observer');
  84.             this.localRDFLoadObserver = {
  85.                 onBeginLoad : function(sink){},
  86.                 onInterrupt : function(sink){},
  87.                 onResume : function(sink){},
  88.                 onError : function(sink,status,msg){},
  89.                 onEndLoad : function(sink) {
  90.                     this.debug('onEndLoad()');
  91.                     // Load datasource
  92.                     sink.removeXMLSinkObserver(this);
  93.                     sink.QueryInterface(Components.interfaces.nsIRDFDataSource);
  94.                     this.debug(' loaded local datasource: '+sink.URI);
  95.                     // Parse the datasource
  96.                     this.parent.ParseDataSource(sink);
  97.                     // Get the current search provider list to compare against the remote list
  98.                     this.parent.GetCurrentSearchProviderList(sink);
  99.                     // Now update from the server
  100.                     this.parent.LoadRemoteSearchProviders();
  101.                 },
  102.                 debug : function(msg) {
  103.                     this.parent.debug('localRDFLoadObserver: '+msg);
  104.                 }
  105.             };
  106.             this.localRDFLoadObserver.parent = this;
  107.         }
  108.  
  109.         // Remote RDF Load Observer
  110.         // ... watches loading of the *remote* search-providers.rdf file
  111.         if (!this.remoteRDFLoadObserver) {
  112.             this.debug(' instanciating remote RDF load observer');
  113.             this.remoteRDFLoadObserver = {
  114.                 onBeginLoad : function(sink){},
  115.                 onInterrupt : function(sink){},
  116.                 onResume : function(sink){},
  117.                 onError : function(sink,status,msg)
  118.                 {
  119.                     this.parent.mRemoteLoadError = true; 
  120.                     this.parent.mRemoteLoadErrorCount = this.parent.mRemoteLoadErrorCount - 1; 
  121.                     this.debug("remoteLoad Error: " + msg);
  122.                 },
  123.                 onEndLoad : function(sink) {
  124.                     if (!this.parent.mRemoteLoadError){
  125.                         this.debug('onEndLoad()');
  126.                         // Load datasource
  127.                         sink.removeXMLSinkObserver(this);
  128.                         sink.QueryInterface(Components.interfaces.nsIRDFDataSource);
  129.                         this.debug(' loaded remote datasource: '+sink.URI);
  130.                         // Copy over top of the local file
  131.                         var localFile = this.parent.GetLocalSearchProviderRDFFile();
  132.                         this.debug(' saving a local copy of the RDF file');
  133.                         var localFileURI = this.parent.ioService.newFileURI(localFile);
  134.                         sink.QueryInterface(Components.interfaces.nsIRDFRemoteDataSource);
  135.                         sink.FlushTo(localFileURI.spec);
  136.                         // Parse the datasource
  137.                         this.parent.ParseDataSource(sink);
  138.                     }
  139.                     else if (this.parent.mRemoteLoadErrorCount)
  140.                     {
  141.                         this.parent.mRemoteLoadError = false; 
  142.                         sink.removeXMLSinkObserver(this);
  143.                       this.parent.LoadRemoteSearchProviders();
  144.                     }
  145.                 },
  146.                 debug : function(msg) {
  147.                     this.parent.debug('remoteRDFLoadObserver: '+msg);
  148.                 }
  149.             };
  150.             this.remoteRDFLoadObserver.parent = this;
  151.         }
  152.  
  153.         // Construct URL to fetch the remote search provider RDF file
  154.         if (!this.remoteRDFFetchURL) {
  155.             var user_guid = this.prefService.getCharPref("browser.info.guid");
  156.             var partnerId;
  157.             try {
  158.                 partnerId = this.prefService.getCharPref("browser.partnerId");
  159.             } catch (ex) {
  160.                 partnerId = 'chapera';
  161.             }
  162.             this.remoteRDFFetchURL =
  163.                 this.prefService.getCharPref("browser.search.providers.url");
  164.                 // + "?guid="+user_guid + "&partnerId="+partnerId;
  165.             this.debug(' remote RDF URL: '+this.remoteRDFFetchURL);
  166.         }
  167.  
  168.         this.LoadLocalSearchProviders();
  169.     },
  170.     
  171.     
  172.     // returns the array position if item is found in the list, otherwise returns -1
  173.     ExistsInList : function(list, name, bIgnoreCase) {
  174.         for (var idx = 0; idx < list.length; idx++) {
  175.             var item1 = list[idx];
  176.             var item2 = name;
  177.             if (bIgnoreCase) {
  178.                 item1 = item1.toLowerCase();
  179.                 item2 = item2.toLowerCase();
  180.             }
  181.             if (item1 == item2)
  182.                 return idx;
  183.         }
  184.         return -1;
  185.     },
  186.     
  187.     
  188.     GetCurrentSearchProviderList : function(datasource) {
  189.         if (!this.searchProviderList)
  190.             this.searchProviderList = new Array();
  191.         
  192.         var pluginsFolder = this.EnsureSearchPluginsFolderExists();
  193.         var entries = pluginsFolder.directoryEntries;
  194.         while (entries.hasMoreElements()) {
  195.             var entry = entries.getNext();
  196.             entry.QueryInterface(Components.interfaces.nsILocalFile);
  197.             var fileName = entry.leafName;
  198.             var idx = fileName.lastIndexOf(".");
  199.             if (idx >= 0)
  200.                 fileName = fileName.substring(0, idx);
  201.             if (fileName.length > 0 && this.ExistsInList(this.searchProviderList, fileName, true) < 0) {
  202.                 this.debug(' Adding to the search provider list: ' + fileName);
  203.                 this.searchProviderList[this.searchProviderList.length] = fileName;
  204.             }
  205.         }
  206.     },
  207.     
  208.  
  209.     LoadLocalSearchProviders : function() {
  210.         this.debug('RefreshLocalSearchProviders()');
  211.         var file = this.GetLocalSearchProviderRDFFile();
  212.         var fileURI = this.ioService.newFileURI(file);
  213.         try {
  214.             // Start loading local RDF file of search providers
  215.             var ds = this.RDFService.GetDataSource(fileURI.spec);
  216.             // Register a listener to pick things up when the file is done
  217.             // loading.  (Control will go to the onEndLoad function...)
  218.             ds.QueryInterface(Components.interfaces.nsIRDFXMLSink);
  219.             ds.addXMLSinkObserver(this.localRDFLoadObserver);
  220.         } catch (ex) {
  221.             // If there was a problem loading the local file, just go
  222.             // directly to the online one
  223.             this.debug(' problem loading local '+this.SEARCH_PROVIDER_RDF_FILE);
  224.             this.LoadRemoteSearchProviders();
  225.         }
  226.     },
  227.  
  228.  
  229.     LoadRemoteSearchProviders : function() {
  230.         this.debug('RefreshRemoteSearchProviders()');
  231.         try {
  232.             ds = this.RDFService.GetDataSourceNoCache(this.remoteRDFFetchURL);
  233.             ds.QueryInterface(Components.interfaces.nsIRDFXMLSink);
  234.             ds.addXMLSinkObserver(this.remoteRDFLoadObserver);
  235.         } catch (ex) {
  236.             this.debug(' problem loading remote search providers file');
  237.         }
  238.     },
  239.  
  240.  
  241.     ParseDataSource : function(datasource) {
  242.         // Remove existing search providers that are not in the datasource
  243.         this.ScrubSearchProviderDirectory(datasource);
  244.         
  245.         // Iterate through resources
  246.         var resources = datasource.GetAllResources();
  247.         var res;
  248.         while (resources.hasMoreElements()) {
  249.             res = resources.getNext();
  250.             res.QueryInterface(Components.interfaces.nsIRDFResource);
  251.             this.LoadSingleProviderResource(datasource, res);
  252.             this.RDFService.UnregisterResource(res);
  253.         }
  254.         this.RDFService.UnregisterDataSource(datasource);
  255.     },
  256.  
  257.  
  258.     ScrubSearchProviderDirectory : function(datasource)    {
  259.         if (!this.searchProviderList)
  260.             return;
  261.  
  262.         if (this.prefService.getPrefType('browser.search.providers.preserve') &&
  263.             this.prefService.getBoolPref('browser.search.providers.preserve')) {
  264.             this.searchProviderList = null;
  265.             return;
  266.         }
  267.             
  268.         if (datasource)
  269.         {
  270.             // Iterate through resources
  271.             var resources = datasource.GetAllResources();
  272.             while (resources.hasMoreElements()) {
  273.                 var res = resources.getNext();
  274.                 res.QueryInterface(Components.interfaces.nsIRDFResource);
  275.                 var resVal = res.Value;
  276.                 if (!resVal)
  277.                     continue;
  278.                 if (resVal.indexOf(this.SEARCH_TAG) < 0)
  279.                     continue;
  280.                     
  281.                 resVal = resVal.substring(this.SEARCH_TAG.length);
  282.                 this.debug('ScrubSearchProoviderDirectory: resVal: ' + resVal);
  283.                 
  284.                 var idx = this.ExistsInList(this.searchProviderList, resVal, true);
  285.                 if (idx > -1) {
  286.                     this.debug('ScrubSearchProoviderDirectory: Val: ' + resVal + ', InList: ' + this.searchProviderList[idx]);
  287.                     this.searchProviderList.splice(idx, 1);
  288.                 }
  289.             }
  290.             
  291.             for (var idx = 0; idx < this.searchProviderList.length; idx++)
  292.                 this.RemoveSearchProvider(this.searchProviderList[idx]);
  293.         }
  294.         
  295.         this.searchProviderList = null;
  296.     },
  297.  
  298.  
  299.     RemoveSearchProvider : function(searchProvider) {
  300.         if (!searchProvider)
  301.             return;
  302.  
  303.         var pluginsFolder = this.EnsureSearchPluginsFolderExists();
  304.  
  305.         const SearchProviderExt = [".src", ".gif", ".jpg", ".bmp", ".png"];
  306.         for (var idx = 0; idx < SearchProviderExt.length; idx++) {
  307.             var filename = searchProvider + SearchProviderExt[idx];
  308.             var spFile = pluginsFolder.clone();
  309.             spFile.append(filename);
  310.             if (spFile.exists()) {
  311.                 this.debug('(remove pre-existing file: '+spFile.path+')');
  312.                 spFile.remove(false);
  313.             }
  314.         }
  315.     },
  316.  
  317.  
  318.     LoadSingleProviderResource : function(datasource, resource) {
  319.         this.debug('LoadSingleProviderResource('+resource.Value+')');
  320.         // See if this resource specifies an actual search provider
  321.         if (datasource.hasArcOut(resource, this.RES_NAME) &&
  322.             datasource.hasArcOut(resource, this.RES_ICON) &&
  323.             datasource.hasArcOut(resource, this.RES_SRC))
  324.         {
  325.             var name = datasource.GetTarget(resource, this.RES_NAME, true);
  326.             name.QueryInterface(Components.interfaces.nsIRDFLiteral);
  327.             this.debug(' name: '+name.Value);
  328.             var icon = datasource.GetTarget(resource, this.RES_ICON, true);
  329.             icon.QueryInterface(Components.interfaces.nsIRDFLiteral);
  330.             this.debug(' icon: '+icon.Value);
  331.             var src = datasource.GetTarget(resource, this.RES_SRC, true);
  332.             src.QueryInterface(Components.interfaces.nsIRDFLiteral);
  333.             this.debug(' src: '+src.Value);
  334.             // Create the searchplugins folder if it doesn't exist
  335.             var pluginsFolder = this.EnsureSearchPluginsFolderExists();
  336.             // Download the icon and src files and stick them in the
  337.             // searchplugins folder
  338.             this.DownloadToSearchPluginsFolder(icon.Value, ["gif", "jpg", "bmp", "png"]);
  339.             this.DownloadToSearchPluginsFolder(src.Value);
  340.         }
  341.     },
  342.  
  343.  
  344.     DownloadToSearchPluginsFolder : function(urlSpec, clearFiles) {
  345.         this.debug('DownloadToSearchPluginsFolder('+urlSpec+')');
  346.  
  347.         // Create URL object
  348.         var remoteURL = Components.classes["@mozilla.org/network/standard-url;1"]
  349.                                   .createInstance(Components.interfaces.nsIStandardURL);
  350.         remoteURL.init(Components.interfaces.nsIStandardURL.URLTYPE_STANDARD,
  351.                        null, urlSpec, null, null);
  352.         remoteURL.QueryInterface(Components.interfaces.nsIURL);
  353.         this.debug(' filename is: '+remoteURL.fileName);
  354.  
  355.         // Download
  356.         var downloadObserver = {
  357.             QueryInterface : function(iid) {
  358.                 if (!iid.equals(nsIDownloadObserver) &&
  359.                     !iid.equals(nsISupports))
  360.                     throw Components.results.NS_ERROR_NO_INTERFACE;
  361.                 return this;
  362.             },
  363.             onDownloadComplete : function(downloader, request, ctxt, status, file) {
  364.                 // file.path now references a temporary cached copy of the file,
  365.                 // so copy it to the searchplugins folder
  366.                 this.debug('file is at: '+file.path);
  367.                 var pluginsFolder = this.parent.GetSearchPluginsFolder();
  368.                 this.debug('copying to: '+pluginsFolder.path+' '+this.fileName);
  369.                 
  370.                 // BLT 152031 fix: replace the existing icon files
  371.                 if(!clearFiles) {
  372.                     clearFiles = [""];
  373.                 }
  374.                 
  375.                 for(var i in clearFiles) {
  376.                     var ext = clearFiles[i];
  377.                     var destFname = this.fileName;
  378.                     if(ext != "") {
  379.                         var ind = destFname.lastIndexOf(".");
  380.                         if(ind >= 0) {
  381.                             destFname = destFname.substring(0, ind);
  382.                         }
  383.                         destFname += "." + ext;
  384.                     }
  385.                     // Test if the file already exists
  386.                     var destinationFile = pluginsFolder.clone();
  387.                     destinationFile.append(destFname);
  388.                     if (destinationFile.exists()) {
  389.                         this.debug(' (removing pre-existing file: '+destFname+')');
  390.                         destinationFile.remove(false);
  391.                         file.copyTo(pluginsFolder, destFname);  
  392.                     }    
  393.                     else if(this.fileName == destFname) {          
  394.                         file.copyTo(pluginsFolder, destFname); 
  395.                     }
  396.                 }
  397.             },
  398.             debug : function(msg) {
  399.                 this.parent.debug('downloadObserver: '+msg);
  400.             }
  401.         };
  402.         downloadObserver.parent = this;
  403.         downloadObserver.fileName = remoteURL.fileName;
  404.         var channel = this.ioService.newChannel(remoteURL.spec, null, null);
  405.         var downloader = Components.classes["@mozilla.org/network/downloader;1"]
  406.                                    .createInstance(Components.interfaces.nsIDownloader);
  407.         downloader.init(downloadObserver, null);
  408.         channel.asyncOpen(downloader, null);
  409.     },
  410.  
  411.  
  412.     GetSearchPluginsFolder : function() {
  413.         this.debug('GetSearchPluginsFolder()');
  414.         // Create file descriptor
  415.         var folder = this.profileDir.clone();
  416.         folder.append(this.SEARCH_PLUGINS_FOLDER);
  417.         return folder; // returns nsILocalFile
  418.     },
  419.  
  420.  
  421.     EnsureSearchPluginsFolderExists : function() {
  422.         this.debug('EnsureSearchPluginsFolderExists()');
  423.         var folder = this.GetSearchPluginsFolder();
  424.         if (!folder.exists()) {
  425.             folder.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0);
  426.         }
  427.         return folder; // returns nsILocalFile
  428.     },
  429.  
  430.  
  431.     GetLocalSearchProviderRDFFile : function() {
  432.         this.debug('GetLocalSearchProviderRDFFile(): '+this.SEARCH_PROVIDER_RDF_FILE);
  433.         // Create file descriptor
  434.         var file = this.profileDir.clone();
  435.         file.append(this.SEARCH_PROVIDER_RDF_FILE);
  436.         return file; // returns nsILocalFile
  437.     },
  438.  
  439.  
  440.     GetSearchHistoryFile : function() {
  441.         this.debug('GetSearchHistoryFile(): '+this.SEARCH_HISTORY_FILE);
  442.         // Create file descriptor
  443.         var file = this.profileDir.clone();
  444.         file.append(this.SEARCH_HISTORY_FILE);
  445.         return file; // returns nsILocalFile
  446.     },
  447.  
  448.  
  449.     EnsureSearchHistoryFileExists : function() {
  450.         this.debug('EnsureSearchHistoryFileExists()');
  451.         var file = this.GetSearchHistoryFile();
  452.         if (!file.exists()) {
  453.             this.debug(' creating file: '+this.SEARCH_HISTORY_FILE);
  454.             file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0);
  455.         }
  456.         return file; // returns nsILocalFile
  457.     },
  458.  
  459.  
  460.     ReadSearchHistory : function() {
  461.         this.debug('ReadSearchHistory()');
  462.  
  463.         var file = this.EnsureSearchHistoryFileExists();
  464.  
  465.         // Init the file input stream
  466.         var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
  467.                             .createInstance(Components.interfaces.nsIFileInputStream);
  468.         fis.init(file, this.PR_RDONLY, 0, 0);
  469.  
  470.         // Init a scriptable input stream
  471.         var sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
  472.                             .createInstance(Components.interfaces.nsIScriptableInputStream);
  473.         sis.init(fis);
  474.  
  475.         // Read the file
  476.         var fileContents = sis.read(sis.available());
  477.  
  478.         // Close file
  479.         fis.close();
  480.  
  481.         // Return the lines as an array
  482.         return fileContents.split('\n');
  483.     },
  484.  
  485.  
  486.     PopulateHistoryPopup : function(evt) {
  487.         this.debug('PopulateHistoryPopup()');
  488.  
  489.         // Purge the history menu
  490.         var popup = evt.target;
  491.         while (popup.lastChild)
  492.             popup.removeChild(popup.lastChild);
  493.  
  494.         // Load in the fresh history items
  495.         var entries = this.ReadSearchHistory();
  496.         for (var i = 0; i < entries.length; i++) {
  497.             if (!entries[i].length) continue;
  498.             var newItem = document.createElement('menuitem');
  499.             newItem.setAttribute('label', entries[i]);
  500.             newItem.setAttribute('oncommand', 'search.HistoryCommand("'+entries[i]+'");');
  501.             popup.appendChild(newItem);
  502.         }
  503.  
  504.         // Only add the separator if there were history items
  505.         if (popup.lastChild)
  506.             popup.appendChild(document.createElement('menuseparator'));
  507.  
  508.         // Always add the 'clear history' menu item
  509.         var clearHist = document.createElement('menuitem');
  510.         clearHist.setAttribute('label', 'Clear Search History');
  511.         clearHist.setAttribute('oncommand', 'search.ClearSearchHistory();');
  512.  
  513.         // ... but if there were no history items, then make it disabled
  514.         if (!popup.lastChild)
  515.             clearHist.setAttribute('disabled','true');
  516.         popup.appendChild(clearHist);
  517.     },
  518.  
  519.  
  520.     HistoryCommand : function(value) {
  521.         this.debug('HistoryCommand("'+value+'")');
  522.         var searchbar = document.getElementById('searchbar');
  523.         if (searchbar) {
  524.             // Put the value into the text box
  525.             searchbar.mTextbox.value = value;
  526.             // Execute search
  527.             searchbar.mTextbox.onTextEntered();
  528.         }
  529.     },
  530.  
  531.  
  532.     AddToHistory : function(value) {
  533.         this.debug('AddToHistory("'+value+'")');
  534.  
  535.         // If it's whitespace, don't bother
  536.         if (!this.trim(value).length) return;
  537.  
  538.         // Create the new list
  539.         var oldList = this.ReadSearchHistory();
  540.         var newList = new Array();
  541.         newList[0] = value;
  542.         for (var i = 0; i < oldList.length; i++) {
  543.             if (oldList[i] != value)
  544.                 newList[newList.length] = oldList[i];
  545.             if (newList.length >= this.MAX_HISTORY_SIZE)
  546.                 break;
  547.         }
  548.  
  549.         // Open the history file for writing
  550.         var file = this.GetSearchHistoryFile();
  551.         file.remove(false);
  552.         file = this.EnsureSearchHistoryFileExists();
  553.         var fos = Components.classes["@mozilla.org/network/file-output-stream;1"]
  554.                             .createInstance(Components.interfaces.nsIFileOutputStream);
  555.         fos.init(file, this.PR_WRONLY, 0, 0);
  556.         var contents = newList.join('\n');
  557.         this.debug(' - writing contents:\n'+contents+'\n\n');
  558.         fos.write(contents, contents.length);
  559.         fos.close();
  560.     },
  561.  
  562.  
  563.     ClearSearchHistory : function() {
  564.         this.debug('ClearSearchHistory()');
  565.         var file = this.GetSearchHistoryFile();
  566.         if (file.exists()) {
  567.             // Init the file input stream
  568.             var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
  569.                                 .createInstance(Components.interfaces.nsIFileInputStream);
  570.             fis.init(file, this.PR_RDONLY, 0,
  571.                      Components.interfaces.nsIFileInputStream.DELETE_ON_CLOSE);
  572.             fis.close();
  573.         }
  574.         // MERC (rpaul) clear the searchbar text
  575.         var searchbar = document.getElementById('searchbar');    
  576.         if (searchbar)
  577.             searchbar.clear();
  578.                 
  579.       // <input name=q> is the entries stored for search engine forms.  Clear them. 
  580.       var formHistSvc = Components.classes["@mozilla.org/satchel/form-history;1"]
  581.                              .getService(Components.interfaces.nsIFormHistory);
  582.     formHistSvc.removeEntriesForName("q");
  583.     
  584.     },
  585.  
  586.  
  587.     debug : function(msg) {
  588.         if (this.SEARCH_DEBUG)
  589.         {
  590.             dump('search.js: '+msg+'\n');
  591.         }
  592.     },
  593.     
  594.     
  595.  
  596.  
  597.     trim : function(str) {
  598.         if (!str) return "";
  599.         str = str.replace(/^\s+/, "");
  600.         return str.replace(/\s+$/, "");
  601.     },
  602.     
  603.     /* MERC - RTOMASELLI
  604.         Method to populate the search provider list    
  605.     */
  606.     PopulateEnginePopup : function(evt) {
  607.                     
  608.              var DESKTOP_SEARCH_ID = "DesktopSearch";
  609.              var popup = evt.target;
  610.              
  611.              while (popup.lastChild)
  612.                 popup.removeChild(popup.lastChild);                                  
  613.         var ds = this.RDFService.GetDataSource("rdf:internetsearch");
  614.         var kNC_Root = this.RDFService.GetResource("NC:SearchEngineRoot");
  615.         var kNC_child = this.RDFService.GetResource("http://home.netscape.com/NC-rdf#child");
  616.         var kNC_Name = this.RDFService.GetResource("http://home.netscape.com/NC-rdf#Name");
  617.         var kNC_Icon = this.RDFService.GetResource("http://home.netscape.com/NC-rdf#Icon");
  618.         var kNC_Version = this.RDFService.GetResource("http://home.netscape.com/NC-rdf#Version");
  619.         var kNC_Description = this.RDFService.GetResource("http://home.netscape.com/NC-rdf#Description");
  620.                                                                                               
  621.         var arcs =ds.GetTargets(kNC_Root, kNC_child, true);
  622.                  // BC: Loading Search engine from a pref
  623.                 // Get preferences
  624.                 var prefServ = Components.classes["@mozilla.org/preferences-service;1"]
  625.                                     .getService(Components.interfaces.nsIPrefBranch);
  626.                 
  627.         
  628.         while (arcs.hasMoreElements()) {
  629.           var engine = arcs.getNext().QueryInterface(Components.interfaces.nsIRDFResource);           
  630.           var name = ds.GetTarget(engine, kNC_Name,true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;                            
  631.           var icon = ds.GetTarget(engine, kNC_Icon,true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  632.           var ver = ds.GetTarget(engine, kNC_Version,true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  633.           var desc = ds.GetTarget(engine, kNC_Description,true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  634.           var engineValue =  engine.Value;                                                                                                    
  635.                                                                                
  636.               var newEngineItem = document.createElement('menuitem');                                          
  637.               var childBox = document.createElement('hbox');
  638.               var searchIcon = document.createElement('image');
  639.               var labelText = document.createElement('label');
  640.               var checkboxContainer = document.createElement('hbox');
  641.                   var checkbox = document.createElement('image');
  642.               newEngineItem.setAttribute('id', engineValue);
  643.               newEngineItem.setAttribute('value', engineValue);
  644.               //newEngineItem.setAttribute('label', name);
  645.                  newEngineItem.setAttribute('type', 'checkbox');
  646.               newEngineItem.setAttribute('desc', desc);
  647.               newEngineItem.setAttribute('ver', ver);              
  648.               newEngineItem.setAttribute('src', icon);
  649.               
  650.               // Set the icon for the search provider         
  651.               searchIcon.setAttribute('src', icon);
  652.  
  653.                         // Set the text for the label
  654.                         labelText.setAttribute('value', name);
  655.                         labelText.setAttribute('class', 'searchbar-menu-iconic-text');
  656.               
  657.               // Set the checked attribute
  658.               checkboxContainer.setAttribute('class', 'searchbar-menu-iconic-left');
  659.               checkbox.setAttribute('class', 'searchbar-menu-iconic-icon');
  660.  
  661.                         // BC: If this element is the same as the saved pref, check it.
  662.                         // check that the pref exists
  663.                         if (prefServ.prefHasUserValue("browser.searchbar.lastSelectedEngine")) {
  664.                             loadedPref = prefServ.getCharPref("browser.searchbar.lastSelectedEngine");
  665.                             // if the loadedPref setting is the same as the current engine value, lets check it
  666.                             if(loadedPref == engineValue) {
  667.                                 checkbox.setAttribute('checked', 'true');
  668.                             }
  669.                         }
  670.               
  671.                  checkboxContainer.appendChild(checkbox);
  672.                  newEngineItem.appendChild(searchIcon);
  673.                  newEngineItem.appendChild(labelText);
  674.                  newEngineItem.appendChild(checkboxContainer);
  675.                 popup.appendChild(newEngineItem);            
  676.                                                   
  677.         }            
  678.  
  679.  
  680.                 // 10.5.2005 NAJ : The following if statement was removed to expose desktop search
  681.                 // regardles of it's installed/uninstalled state per CCv3.  A handler for the lack of
  682.                 // an installed Copernic will be required, this will be atached to the oncommand
  683.                 // in the UI.
  684.                 
  685.                 // if (desktopSearch.isDesktopSearchAvailable()) {
  686.                     
  687.                     if (popup.lastChild)                  
  688.                     popup.appendChild(document.createElement('menuseparator'));
  689.         
  690.             var desktopSearchItem = document.createElement('menuitem');
  691.             desktopSearchItem.setAttribute('id', DESKTOP_SEARCH_ID);  
  692.             desktopSearchItem.setAttribute('value', DESKTOP_SEARCH_ID);                   
  693.             desktopSearchItem.setAttribute('type', 'checkbox');     
  694.             desktopSearchItem.setAttribute('label', 'Desktop Search');        
  695.             desktopSearchItem.setAttribute('src', 'chrome://browser/skin/search/copernic.png');                        
  696.             popup.appendChild(desktopSearchItem);     
  697.             
  698.           //}
  699.             
  700.                               
  701.     },
  702.     /* MERC - BCharan
  703.      * @param - ID of the selected element
  704.      */
  705.     saveSelectionToPref : function(element) {
  706.                  // BC: Saving Search into a pref
  707.                 // Get preferences
  708.                 var prefServ = Components.classes["@mozilla.org/preferences-service;1"]
  709.                                     .getService(Components.interfaces.nsIPrefBranch);
  710.                 
  711.                 // Check if the pref exists first
  712.                 if (prefServ.prefHasUserValue("browser.searchbar.lastSelectedEngine")) {
  713.                     // Get the stored pref
  714.                     storedPref = prefServ.getCharPref("browser.searchbar.lastSelectedEngine");
  715.                     // If the pref exists, then compare it to the current pref,
  716.                     // Overwrite if they are not equal
  717.                     if (storedPref != element.getAttribute('id')) {
  718.                         prefServ.setCharPref("browser.searchbar.lastSelectedEngine", element.getAttribute('id'));
  719.                     } 
  720.                 } else {
  721.                         prefServ.setCharPref("browser.searchbar.lastSelectedEngine", element.getAttribute('id'));
  722.                 }                    
  723.     }, 
  724.     
  725.     /* MERC - RTOMASELLI
  726.     This method is called when 'Web    Search' is selected from the 'Tools' 
  727.     menu. Loop through the list of web providers and if one of them 
  728.     matches the browser default search provider then use it otherwise
  729.     use any other web search provider. This also handles the case if the
  730.     default provider is the desktop search.         
  731. */ 
  732.  OnWebSearchSelected : function(){
  733.                     
  734.         var prefbranch = Components.classes["@mozilla.org/preferences-service;1"]
  735.                            .getService(Components.interfaces.nsIPrefBranch);
  736.         var defaultName = prefbranch.getComplexValue("browser.search.defaultenginename",
  737.                                              Components.interfaces.nsIPrefLocalizedString).data;
  738.                                              
  739.     var rdf = Components.classes["@mozilla.org/rdf/rdf-service;1"]
  740.                              .getService(Components.interfaces.nsIRDFService);   
  741.     var ds = rdf.GetDataSource("rdf:internetsearch");
  742.         var kNC_Root = rdf.GetResource("NC:SearchEngineRoot");
  743.         var kNC_child = rdf.GetResource("http://home.netscape.com/NC-rdf#child");
  744.         var kNC_Name = rdf.GetResource("http://home.netscape.com/NC-rdf#Name");
  745.         var kNC_Icon = rdf.GetResource("http://home.netscape.com/NC-rdf#Icon");        
  746.         var arcs =ds.GetTargets(kNC_Root, kNC_child, true);
  747.         var engine;
  748.         var name;
  749.         var icon;
  750.                     
  751.     var foundDefault = false;
  752.     while (arcs.hasMoreElements() && !foundDefault) {
  753.       engine = arcs.getNext().QueryInterface(Components.interfaces.nsIRDFResource);           
  754.       name = ds.GetTarget(engine, kNC_Name,true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;                            
  755.       icon = ds.GetTarget(engine, kNC_Icon,true).QueryInterface(Components.interfaces.nsIRDFLiteral).Value;
  756.       
  757.             if (name == defaultName){foundDefault = true;}
  758.         }
  759.         
  760.         if (engine) {
  761.             var broadcaster = window.top.document.getElementById('searchEngineBroadcaster');
  762.             broadcaster.setAttribute("src",icon);
  763.             broadcaster.setAttribute("searchengine", engine.Value);         
  764.         }         
  765.         
  766.         focusSearchBar();         
  767.         
  768. },
  769.  
  770.     /* MERC - RTOMASELLI 
  771.     This method is called when 'Desktop Search' is selected from the 'Tools' menu        */
  772.     OnDesktopSearchSelected: function(){
  773.     
  774.         var broadcaster = window.top.document.getElementById('searchEngineBroadcaster');     
  775.         broadcaster.setAttribute("src","chrome://browser/skin/search/copernic.png");
  776.         broadcaster.setAttribute("searchengine", "DesktopSearch");         
  777.     },
  778.     
  779.     
  780.         logError : function(exceptionObject, optionalAdditionalText) {    
  781.         // logs (or otherwise handles) errors
  782.     // do logging ?!
  783.     // for now, just alert
  784.     var output;
  785.     var errSource = this.logError.caller;    //Source function from the error
  786.  
  787.     output = "Function: " + errSource.name ;
  788.  
  789.     if (errSource.arity > 0){
  790.         output +=    "\nArguments: \n"
  791.         for (i=0; i < errSource.arity; i++){
  792.             output += "   (" + i + ") " + errSource.arguments[i] ;
  793.         }
  794.     }
  795.     output += "\nException: " + exceptionObject.message ;
  796.  
  797.     if (optionalAdditionalText != null) {
  798.         output += "\nNotes: " + optionalAdditionalText;
  799.     }
  800.     this.debug("\n" + output);   
  801.     alert (output);
  802.    
  803. }
  804.  
  805. };
  806.  
  807.