home *** CD-ROM | disk | FTP | other *** search
/ PCGUIA 2010 Software/Programs / PCGuia_programas.iso / Software / Utils / Advanced SystemCare / asc-setup.exe / {app} / tb / components / ConduitAutoCompleteSearch.js next >
Encoding:
JavaScript  |  2009-12-23  |  20.2 KB  |  626 lines

  1. //Helper functions and objects
  2.  
  3. var AppInfo =
  4. {
  5.     //consts
  6.     WIN: "WIN",
  7.     MAC: "MAC",
  8.     LINUX: "LINUX",
  9.  
  10.     //public properties
  11.     OS: "",
  12.     browserVersion: "",
  13.     isGecko191: null, //FF3.5 and up
  14.     isGecko19: null, //FF3 and up
  15.     isGecko18: null, //FF2 and up
  16.  
  17.     xulRuntime: null,
  18.  
  19.     compareVersions: function(strVer1, strVer2) {
  20.         var oVersionCompare = Components.classes["@mozilla.org/xpcom/version-comparator;1"]
  21.                                         .createInstance(Components.interfaces.nsIVersionComparator);
  22.         return oVersionCompare.compare(strVer1, strVer2);
  23.     },
  24.  
  25.     getOS: function() {
  26.         try {
  27.             var window = getWindow();
  28.             var strUserAgent = window.navigator.userAgent;
  29.             var iStart = strUserAgent.indexOf('(');
  30.             var iEnd = strUserAgent.indexOf(')');
  31.             var strPlatformData = strUserAgent.substring(iStart, iEnd);
  32.             var arrData = strPlatformData.split(';');
  33.             return arrData[2].replace(/\s/g, "");
  34.         }
  35.         catch (e) {
  36.             return "";
  37.         }
  38.     },
  39.  
  40.     isVista: function() {
  41.         var os = this.getOS().toUpperCase();
  42.         if (os.indexOf(this.WIN) == -1)
  43.             return false;
  44.  
  45.         os = os.replace(/\./g, "");
  46.         var ver = os.match(/(\d+)/);
  47.         return parseInt(ver) >= 60
  48.     },
  49.  
  50.     init: function() {
  51.  
  52.         //parse OS type
  53.         try {
  54.             this.xulRuntime = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime);
  55.             var _os = this.xulRuntime.OS.toUpperCase();
  56.             if (_os.indexOf(this.WIN) != -1) {
  57.                 this.OS = this.WIN;
  58.             }
  59.             else if (_os.indexOf(this.MAC) != -1)
  60.                 this.OS = this.MAC;
  61.             else
  62.                 this.OS = this.LINUX;
  63.  
  64.             //set gecko version (1.8.x or 1.9.x)
  65.             var _geckoVer = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo).platformVersion;
  66.             this.browserVersion = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo).version;
  67.  
  68.             var strGeckoVer = "1.9.0.0"; //FF3 gecko version
  69.             var iCompare = this.compareVersions(_geckoVer, strGeckoVer);
  70.             this.isGecko19 = (iCompare >= 0);
  71.  
  72.             strGeckoVer = "1.9.1.0"; //FF3.5 gecko version
  73.             var iCompare = this.compareVersions(_geckoVer, strGeckoVer);
  74.             this.isGecko191 = (iCompare >= 0);
  75.  
  76.             strGeckoVer = "1.8.0.0"; //FF2 gecko version
  77.             iCompare = this.compareVersions(_geckoVer, strGeckoVer);
  78.             this.isGecko18 = (iCompare >= 0);
  79.  
  80.         } catch (e) { Logging.LogToConsole(e) }
  81.     }
  82. };
  83.  
  84. AppInfo.init();
  85.  
  86. var EBServerDataURL = 
  87. {
  88.     ServerRequest : function(strURL,strPostData,strUserName,strPassword,ServerResponseFunction)
  89.     {
  90.         var objIOService    = Components.classes["@mozilla.org/network/io-service;1"].createInstance(Components.interfaces.nsIIOService);
  91.         var objURI            = objIOService.newURI(strURL, null, null);
  92.         
  93.         if(strUserName != null && strPassword != null)
  94.         {
  95.             objURI.username        = strUserName;
  96.             objURI.password        = strPassword;
  97.         }
  98.         
  99.         var objChannel        = objIOService.newChannelFromURI(objURI);
  100.         
  101.         objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).setRequestHeader('PRAGMA','NO-CACHE',false);
  102.         objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).setRequestHeader('CACHE-CONTROL','NO-CACHE',false);
  103.  
  104.         
  105.         if(strPostData != null) 
  106.         {
  107.             var objUploadStream        = Components.classes["@mozilla.org/io/string-input-stream;1"].createInstance(Components.interfaces.nsIStringInputStream);
  108.             objUploadStream.setData(strPostData, strPostData.length);
  109.               
  110.             var objUploadChannel    = objChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
  111.             objUploadChannel.setUploadStream(objUploadStream, "application/x-www-form-urlencoded", -1);
  112.               
  113.             objChannel.QueryInterface(Components.interfaces.nsIHttpChannel).requestMethod = "POST";
  114.             
  115.             
  116.         }
  117.         
  118.         var objObserver = new this.Observer(ServerResponseFunction);
  119.         objChannel.asyncOpen(objObserver, null);
  120.     },
  121.     
  122.     Observer: function(ServerResponseFunction)
  123.     {
  124.         return ({
  125.                     Data : "",
  126.                     
  127.                     onStartRequest: function(aRequest, aContext)
  128.                     {
  129.                         this.Data = "";
  130.                     },
  131.                     
  132.                     onStopRequest: function(aRequest, aContext, aStatus)
  133.                     {
  134.                         if(ServerResponseFunction)
  135.                         {
  136.                             ServerResponseFunction(this.Data, aRequest);
  137.                         }
  138.                     },
  139.                         
  140.                     onDataAvailable: function(aRequest, aContext, aStream, aSourceOffset, aLength)
  141.                     {
  142.                         var objScriptableInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
  143.                         objScriptableInputStream.init(aStream);
  144.                         this.Data += objScriptableInputStream.read(aLength);
  145.                     }
  146.                 });
  147.     }
  148. };
  149.  
  150. if (typeof JSON == "undefined") {
  151.     //FF3.5
  152.     if (AppInfo.isGecko191) {
  153.         //do nothing
  154.     }
  155.     //FF3
  156.     else if (AppInfo.isGecko19) {
  157.         var myJson = Components.classes["@mozilla.org/dom/json;1"].createInstance(Components.interfaces.nsIJSON);
  158.         JSON = {};
  159.         JSON.stringify = function(obj) { return myJson.encode(obj); };
  160.         JSON.parse = function(str) { return myJson.decode(str); };
  161.     }
  162.     //FF2
  163.     else {
  164.         var myJson = {
  165.             stringify: function(aJSObject, aKeysToDrop) {
  166.                 var pieces = [];
  167.  
  168.                 function append_piece(aObj) {
  169.                     if (typeof aObj == "string") {
  170.                         aObj = aObj.replace(/[\\"\x00-\x1F\u0080-\uFFFF]/g, function($0) {
  171.                             switch ($0) {
  172.                                 case "\b": return "\\b";
  173.                                 case "\t": return "\\t";
  174.                                 case "\n": return "\\n";
  175.                                 case "\f": return "\\f";
  176.                                 case "\r": return "\\r";
  177.                                 case '"': return '\\"';
  178.                                 case "\\": return "\\\\";
  179.                             }
  180.                             return "\\u" + ("0000" + $0.charCodeAt(0).toString(16)).slice(-4);
  181.                         });
  182.                         pieces.push('"' + aObj + '"')
  183.                     }
  184.                     else if (typeof aObj == "boolean") {
  185.                         pieces.push(aObj ? "true" : "false");
  186.                     }
  187.                     else if (typeof aObj == "number" && isFinite(aObj)) {
  188.                         pieces.push(aObj.toString());
  189.                     }
  190.                     else if (aObj === null) {
  191.                         pieces.push("null");
  192.                     }
  193.                     else if (aObj instanceof Array ||
  194.                 typeof aObj == "object" && "length" in aObj &&
  195.                 (aObj.length === 0 || aObj[aObj.length - 1] !== undefined)) {
  196.                         pieces.push("[");
  197.                         for (var i = 0; i < aObj.length; i++) {
  198.                             arguments.callee(aObj[i]);
  199.                             pieces.push(",");
  200.                         }
  201.                         if (aObj.length > 0)
  202.                             pieces.pop(); // drop the trailing colon
  203.                         pieces.push("]");
  204.                     }
  205.                     else if (typeof aObj == "object") {
  206.                         pieces.push("{");
  207.                         for (var key in aObj) {
  208.                             // allow callers to pass objects containing private data which
  209.                             // they don't want the JSON string to contain (so they don't
  210.                             // have to manually pre-process the object)
  211.                             if (aKeysToDrop && aKeysToDrop.indexOf(key) != -1)
  212.                                 continue;
  213.  
  214.                             arguments.callee(key.toString());
  215.                             pieces.push(":");
  216.                             arguments.callee(aObj[key]);
  217.                             pieces.push(",");
  218.                         }
  219.                         if (pieces[pieces.length - 1] == ",")
  220.                             pieces.pop(); // drop the trailing colon
  221.                         pieces.push("}");
  222.                     }
  223.                     else {
  224.                         throw new TypeError("No JSON representation for this object!");
  225.                     }
  226.                 }
  227.                 append_piece(aJSObject);
  228.  
  229.                 return pieces.join("");
  230.             },
  231.  
  232.             /**
  233.             * Converts a JSON string into a JavaScript object.
  234.             *
  235.             * @param aJSONString is the string to be converted
  236.             * @return a JavaScript object for the given JSON representation
  237.             */
  238.             parse: function(aJSONString) {
  239.                 if (!this.isMostlyHarmless(aJSONString))
  240.                     throw new SyntaxError("No valid JSON string!");
  241.  
  242.                 var s = new Components.utils.Sandbox("about:blank");
  243.                 return Components.utils.evalInSandbox("(" + aJSONString + ")", s);
  244.             },
  245.  
  246.             /**
  247.             * Checks whether the given string contains potentially harmful
  248.             * content which might be executed during its evaluation
  249.             * (no parser, thus not 100% safe! Best to use a Sandbox for evaluation)
  250.             *
  251.             * @param aString is the string to be tested
  252.             * @return a boolean
  253.             */
  254.             isMostlyHarmless: function(aString) {
  255.                 var maybeHarmful = /[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/;
  256.                 var jsonStrings = /"(\\.|[^"\\\n\r])*"/g;
  257.  
  258.                 return !maybeHarmful.test(aString.replace(jsonStrings, ""));
  259.             }
  260.         }
  261.         JSON = myJson;
  262.     }
  263. };
  264.  
  265. function decodeUtf8(utftext) 
  266. {
  267.     var string = "";
  268.     var i = 0;
  269.     var c = c1 = c2 = 0;
  270.  
  271.     while ( i < utftext.length ) 
  272.     {
  273.  
  274.         c = utftext.charCodeAt(i);
  275.  
  276.         if (c < 128) {
  277.             string += String.fromCharCode(c);
  278.             i++;
  279.         }
  280.         else if((c > 191) && (c < 224)) {
  281.             c2 = utftext.charCodeAt(i+1);
  282.             string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  283.             i += 2;
  284.         }
  285.         else {
  286.             c2 = utftext.charCodeAt(i+1);
  287.             c3 = utftext.charCodeAt(i+2);
  288.             string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  289.             i += 3;
  290.         }
  291.  
  292.     }
  293.  
  294.     return string;
  295. }
  296.  
  297. function setTimeout(objDeligate, iTimeout)
  298. {
  299.     var timer = Components.classes['@mozilla.org/timer;1'].
  300.                     createInstance(Components.interfaces.nsITimer);
  301.     timer.initWithCallback(objDeligate, iTimeout, Components.interfaces.nsITimer.TYPE_ONE_SHOT); 
  302. }
  303.  
  304.  
  305. //XPCOM
  306. function ConduitAutoCompleteSearch() {
  307.     this.commands = [];
  308.     this.txtSuggest = "Suggestions";
  309.     this.txtHistory = "History";
  310.     this.wrappedJSObject = this;
  311. };
  312.  
  313. ConduitAutoCompleteSearch.prototype = {
  314.     lastSuggetTimestamp : '',
  315.     searchString    : '',
  316.     
  317.     setCaptions: function(txtSuggest, txtHistory)
  318.     {
  319.         this.txtSuggest = txtSuggest;
  320.         this.txtHistory = txtHistory;
  321.     },
  322.     
  323.     startSearch: function(searchString, strJsonData, prevResult, listener) {
  324.         this.requestSuggestions(searchString, listener, strJsonData);
  325.     },
  326.  
  327.     stopSearch: function() {},
  328.     
  329.     requestSuggestions : function(searchString, listener, strJSON)
  330.     {
  331.         var objData = JSON.parse(strJSON);
  332.             
  333.         var strSuggestUrl = objData.suggestUrl;
  334.         this.setCaptions(objData.txtSuggest, objData.txtHistory);
  335.         
  336.         //no suggestions for this engine
  337.         this.searchString  = searchString;
  338.         if(!strSuggestUrl || !searchString)
  339.         { 
  340.             //load local history only
  341.             this.setSuggestionsAndHistory(searchString, null, listener);
  342.             return;
  343.         }
  344.         
  345.         //go get suggestions
  346.         var now = Date.parse(Date());
  347.         var arrSuggestUrl           = strSuggestUrl.split('!!');
  348.             strSuggestUrl           = arrSuggestUrl[0];
  349.         var strSearchTermToReplace  = arrSuggestUrl[1];
  350.         
  351.         strSuggestUrl = strSuggestUrl.replace(strSearchTermToReplace,escape(searchString));
  352.         var objFunc     = this;
  353.         
  354.         var oResponse   = function(strJSON)
  355.         {
  356.             objFunc.setSuggestionsAndHistory(searchString,strJSON,listener);
  357.         };
  358.         
  359.         var oRequest = 
  360.         {
  361.             originalSearchString : searchString,
  362.             
  363.             notify : function(oTimer)
  364.             {
  365.                 if(this.originalSearchString == objFunc.searchString)
  366.                     this.execute();
  367.             },
  368.             
  369.             execute : function()
  370.             {
  371.                 EBServerDataURL.ServerRequest(strSuggestUrl,null,null,null,oResponse);
  372.             },
  373.         };
  374.         
  375.         setTimeout(oRequest,300);
  376.     },
  377.  
  378.     setSuggestionsAndHistory: function(searchString, strJSON, listener) {
  379.         
  380.         var dir = null;
  381.         var bLoadHistory = true;
  382.         
  383.         try 
  384.         {
  385.             var dir = Components.classes['@mozilla.org/file/directory_service;1']
  386.                                     .createInstance(Components.interfaces.nsIProperties)
  387.                                     .get('ProfD', Components.interfaces.nsIFile);
  388.         
  389.             var sep = '/';
  390.             var path = dir.path + sep + 'EBSuggestHistory';
  391.             
  392.             try 
  393.             {
  394.                 var ebDir = Components.classes['@mozilla.org/file/local;1']
  395.                             .createInstance(Components.interfaces.nsILocalFile);
  396.                 ebDir.initWithPath(path);
  397.             }
  398.             catch(e) 
  399.             { 
  400.                 sep = '\\';
  401.                 path = dir.path + sep + 'EBSuggestHistory';
  402.                 try 
  403.                 {
  404.                     var ebDir = Components.classes['@mozilla.org/file/local;1']
  405.                                 .createInstance(Components.interfaces.nsILocalFile);
  406.                     ebDir.initWithPath(path);
  407.                 } catch(e) {}
  408.             }
  409.             
  410.             var file = Components.classes['@mozilla.org/file/local;1']
  411.                             .createInstance(Components.interfaces.nsILocalFile);
  412.             
  413.             file.initWithPath(ebDir.path + sep + 'search_history.xml');
  414.             
  415.             var data     = new String();
  416.             
  417.             var fiStream = Components.classes['@mozilla.org/network/file-input-stream;1']
  418.                     .createInstance(Components.interfaces.nsIFileInputStream);
  419.             
  420.             var siStream = Components.classes['@mozilla.org/scriptableinputstream;1']
  421.                     .createInstance(Components.interfaces.nsIScriptableInputStream);
  422.  
  423.             fiStream.init(file, 1, 0, false);
  424.             siStream.init(fiStream);
  425.             data += siStream.read(-1);
  426.             siStream.close();
  427.             fiStream.close();
  428.  
  429.             var uniConv = Components.classes['@mozilla.org/intl/scriptableunicodeconverter']
  430.                     .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
  431.             uniConv.charset = 'UTF-8';
  432.             data = uniConv.ConvertToUnicode(data);
  433.         }
  434.         catch(e) 
  435.         {
  436.             bLoadHistory = false;
  437.         }
  438.         
  439.         if(bLoadHistory)
  440.         {
  441.             var parser = Components.classes['@mozilla.org/xmlextras/domparser;1']
  442.                             .createInstance(Components.interfaces.nsIDOMParser);
  443.             
  444.             var xmlDoc        = parser.parseFromString(data, "text/xml");
  445.             
  446.             var xmlItems    = xmlDoc.documentElement.getElementsByTagName('ITEM');
  447.             
  448.             var result = [];
  449.             
  450.             var nodeValue = '';
  451.             
  452.             for(var i=0; i<xmlItems.length; i++)
  453.             {
  454.                 if(typeof (xmlItems.item(i).childNodes[0]) != "undefined")
  455.                 {
  456.                     nodeValue = xmlItems.item(i).childNodes[0].nodeValue;
  457.                     result[result.length] = nodeValue;
  458.                 }
  459.             }
  460.             
  461.             var commands = Components.classes["@mozilla.org/supports-array;1"].createInstance(Components.interfaces.nsISupportsArray);
  462.             
  463.             for (var i = 0; i < result.length; i++) 
  464.             {
  465.                 var string = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
  466.                 string.data = result[i];
  467.                 commands.AppendElement(string);
  468.             }
  469.             
  470.             var count = commands.Count();
  471.             this.commands = new Array(count);
  472.             for (var i = 0; i < count; i++)
  473.                 this.commands[i] = commands.GetElementAt(i).QueryInterface(Components.interfaces.nsISupportsString).data;
  474.             
  475.         }
  476.         
  477.         var arrSuggest = null;
  478.         
  479.         if (strJSON && strJSON.length > 0)
  480.             arrSuggest = JSON.parse(strJSON);
  481.             
  482.         var result = new AutoCompleteResult(searchString, this.commands, arrSuggest, this.txtSuggest, this.txtHistory);
  483.         
  484.         listener.onSearchResult(this, result);
  485.     },
  486.     
  487.     QueryInterface: function (uuid) {
  488.         if (uuid.equals(Components.interfaces.nsIConduitAutoCompleteSearch) ||
  489.             uuid.equals(Components.interfaces.nsIAutoCompleteSearch) ||
  490.             uuid.equals(Components.interfaces.nsISupports)) {
  491.             return this;
  492.         }
  493.         
  494.         Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  495.         return null;
  496.     }
  497. }
  498.  
  499. function AutoCompleteResult(search, commands, arrSuggest, txtSuggest, txtHistory) 
  500. {
  501.     var IsContains = function(arrArray, strString)
  502.     {
  503.         for(var i=0; i<arrArray.length; i++)
  504.             if(arrArray[i] == strString)
  505.                 return true;
  506.             
  507.         return false;
  508.     };
  509.     
  510.     this.search = search;
  511.     this.commands = [];
  512.     this.txtSuggest = txtSuggest;
  513.     this.txtHistory = txtHistory;
  514.     
  515.     var lsearch = search.toLowerCase();
  516.     
  517.     if(commands.length > 0)
  518.     {
  519.         for (var i = 0; i < commands.length; i++) 
  520.         {
  521.             if (commands[i].toLowerCase().indexOf(lsearch) == 0)
  522.                 this.commands.push(commands[i]);
  523.         }
  524.     }
  525.     
  526.     this.HistoryStartIndex = this.commands.length;
  527.     
  528.     if(arrSuggest && search == decodeUtf8(arrSuggest[0]) && arrSuggest[1].length > 0)
  529.     {
  530.         for(var i=0; i<arrSuggest[1].length; i++)
  531.         {
  532.             if(!IsContains(this.commands ,arrSuggest[1][i])) 
  533.                 this.commands.push(decodeUtf8(arrSuggest[1][i]));
  534.         }
  535.     }
  536. }
  537.  
  538. AutoCompleteResult.prototype = {
  539.     get defaultIndex() { return 0; },
  540.     get errorDescription() { return ''; },
  541.     get matchCount() { return this.commands.length; },
  542.     get searchResult() {
  543.         return Components.interfaces.nsIAutoCompleteResult.RESULT_SUCCESS;
  544.     },
  545.     get searchString() { return this.search; },
  546.     getCommentAt: function(index) {
  547.         if(index == this.HistoryStartIndex)
  548.             return this.txtSuggest;
  549.         else if(index == 0)
  550.             return this.txtHistory;
  551.         else
  552.             return '';
  553.     },
  554.     getStyleAt: function(index) {
  555.         if (!this.commands[index])
  556.            return null;  // not a category label, so no special styling
  557.      
  558.          if (index == 0)
  559.            return "suggestfirst";  // category label on first line of results
  560.      
  561.          if(index == this.HistoryStartIndex)
  562.              return "suggesthint";
  563.          
  564.          return '';
  565.     },
  566.     getValueAt: function(index) {
  567.         return this.commands[index];
  568.     },
  569.     
  570.     removeValueAt: function(rowIndex, removeFromDb) {
  571.     },
  572.     
  573.     getImageAt: function(index) {
  574.          return "";
  575.      },
  576.      
  577.     QueryInterface: function (uuid) {
  578.         if (uuid.equals(Components.interfaces.nsIAutoCompleteResult) ||
  579.             uuid.equals(Components.interfaces.nsISupports)) {
  580.             return this;
  581.         }
  582.         Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  583.         return null;
  584.     }
  585. };
  586.  
  587. const COMPONENT_ID = Components.ID("{FDE25E06-0242-4b4f-A202-5B0DA44243B9}");
  588.  
  589. var ConduitAutoCompleteModule = {
  590.     registerSelf: function (compMgr, fileSpec, location, type) {
  591.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  592.         compMgr.registerFactoryLocation(COMPONENT_ID,
  593.                                         "Conduit Auto Complete with Suggest",
  594.                                         "@mozilla.org/autocomplete/search;1?name=conduit-auto-complete-with-suggest3",
  595.                                         fileSpec,
  596.                                         location,
  597.                                         type);
  598.     },
  599.  
  600.     getClassObject: function (compMgr, cid, iid) {
  601.         if (!cid.equals(COMPONENT_ID))
  602.             throw Components.results.NS_ERROR_NO_INTERFACE;
  603.         if (!iid.equals(Components.interfaces.nsIFactory))
  604.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  605.  
  606.         return ConduitAutoCompleteFactory;
  607.     },
  608.  
  609.     canUnload: function(compMgr) {
  610.         return true;
  611.     }
  612. };
  613.  
  614. var ConduitAutoCompleteFactory = {
  615.     createInstance: function (outer, iid) {
  616.         if (outer != null)
  617.             throw Components.results.NS_ERROR_NO_AGGREGATION;
  618.         return new ConduitAutoCompleteSearch().QueryInterface(iid);
  619.     }
  620. };
  621.  
  622. function NSGetModule(compMgr, fileSpec) {
  623.     return ConduitAutoCompleteModule;
  624. };
  625.  
  626.