summaryrefslogtreecommitdiffstats
path: root/chrome/renderer/resources/extensions/searchbox_api.js
blob: 1b32046ede584bb9e11e52c38039f70e53d1904f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var chrome;
if (!chrome)
  chrome = {};
if (!chrome.searchBox) {
  chrome.searchBox = new function() {
    var safeObjects = {};
    chrome.searchBoxOnWindowReady = function() {
      // |searchBoxOnWindowReady| is used for initializing window context and
      // should be called only once per context.
      safeObjects.ShadowRoot = window.WebKitShadowRoot;
      safeObjects.defineProperty = Object.defineProperty;
      delete window.chrome.searchBoxOnWindowReady;
    };

    // =========================================================================
    //                                  Constants
    // =========================================================================
    var MAX_CLIENT_SUGGESTIONS_TO_DEDUPE = 6;
    var MAX_ALLOWED_DEDUPE_ATTEMPTS = 5;

    var HTTP_REGEX = /^https?:\/\//;

    var WWW_REGEX = /^www\./;

    // =========================================================================
    //                            Private functions
    // =========================================================================
    native function GetQuery();
    native function GetVerbatim();
    native function GetSelectionStart();
    native function GetSelectionEnd();
    native function GetX();
    native function GetY();
    native function GetWidth();
    native function GetHeight();
    native function GetAutocompleteResults();
    native function GetContext();
    native function GetDisplayInstantResults();
    native function GetThemeBackgroundInfo();
    native function GetThemeAreaHeight();
    native function IsKeyCaptureEnabled();
    native function NavigateContentWindow();
    native function SetSuggestions();
    native function SetQuerySuggestion();
    native function SetQuerySuggestionFromAutocompleteResult();
    native function SetQuery();
    native function SetQueryFromAutocompleteResult();
    native function Show();
    native function StartCapturingKeyStrokes();
    native function StopCapturingKeyStrokes();

    // Returns the |restrictedText| wrapped in a ShadowDOM.
    function SafeWrap(restrictedText) {
      var node = document.createElement('div');
      var nodeShadow = new safeObjects.ShadowRoot(node);
      nodeShadow.applyAuthorStyles = true;
      // The fonts specified here are as follows:
      //  Segoe UI - WIndows 7
      //  Chrome Droid Sans - ChromeOS
      //  Arial - fallback for other platforms.
      // This doesn't look right on WInXP, MacOS, and Linux, but rather than
      // try to include all the logic here, the correct value should be passed
      // in from the C++. crbug.com/164496 tracks this task.
      nodeShadow.innerHTML =
          '<div style="width:700px!important;' +
          '            height:22px!important;' +
          '            font-family:\'Segoe UI\',\'Chrome Droid Sans\',' +
          '                        \'Arial\'!important;' +
          '            overflow:hidden!important;' +
          '            text-overflow:ellipsis!important">' +
          '  <nobr>' + restrictedText + '</nobr>' +
          '</div>';
      safeObjects.defineProperty(node, 'webkitShadowRoot', { value: null });
      return node;
    }

    // Wraps the AutocompleteResult query and URL into ShadowDOM nodes so that
    // the JS cannot access them and deletes the raw values.
    function GetAutocompleteResultsWrapper() {
      var autocompleteResults = DedupeAutocompleteResults(
          GetAutocompleteResults());
      var userInput = GetQuery();
      for (var i = 0, result; result = autocompleteResults[i]; ++i) {
        var title = result.contents;
        var url = CleanUrl(result.destination_url, userInput);
        var combinedHtml = '<span class=chrome_url>' + url + '</span>';
        if (title) {
          result.titleNode = SafeWrap(title);
          combinedHtml += '<span class=chrome_separator> &ndash; </span>' +
              '<span class=chrome_title>' + title + '</span>';
        }
        result.urlNode = SafeWrap(url);
        result.combinedNode = SafeWrap(combinedHtml);
        delete result.contents;
        delete result.destination_url;
      }
      return autocompleteResults;
    }

    // TODO(dcblack): Do this in C++ instead of JS.
    function CleanUrl(url, userInput) {
      if (url.indexOf(userInput) == 0) {
        return url;
      }
      url = url.replace(HTTP_REGEX, '');
      if (url.indexOf(userInput) == 0) {
        return url;
      }
      return url.replace(WWW_REGEX, '');
    }

    // TODO(dcblack): Do this in C++ instead of JS.
    function CanonicalizeUrl(url) {
      return url.replace(HTTP_REGEX, '').replace(WWW_REGEX, '');
    }

    // Removes duplicates from AutocompleteResults.
    // TODO(dcblack): Do this in C++ instead of JS.
    function DedupeAutocompleteResults(autocompleteResults) {
      var urlToResultMap = {};
      for (var i = 0, result; result = autocompleteResults[i]; ++i) {
        var url = CanonicalizeUrl(result.destination_url);
        if (url in urlToResultMap) {
          var oldRelevance = urlToResultMap[url].rankingData.relevance;
          var newRelevance = result.rankingData.relevance;
          if (newRelevance > oldRelevance) {
            urlToResultMap[url] = result;
          }
        } else {
          urlToResultMap[url] = result;
        }
      }
      var dedupedResults = [];
      for (url in urlToResultMap) {
        dedupedResults.push(urlToResultMap[url]);
      }
      return dedupedResults;
    }

    var lastPrefixQueriedForDuplicates = '';
    var numDedupeAttempts = 0;

    function DedupeClientSuggestions(clientSuggestions) {
      var userInput = GetQuery();
      if (userInput == lastPrefixQueriedForDuplicates) {
        numDedupeAttempts += 1;
        if (numDedupeAttempts > MAX_ALLOWED_DEDUPE_ATTEMPTS) {
          // Request blocked for privacy reasons.
          // TODO(dcblack): This check is insufficient.  We should have a check
          // such that it's only callable once per onnativesuggestions, not
          // once per prefix.  Also, there is a timing problem where if the user
          // types quickly then the client will (correctly) attempt to render
          // stale results, and end up calling dedupe multiple times when
          // getValue shows the same prefix.  A better solution would be to have
          // the client send up rid ranges to dedupe against and have the
          // binary keep around all the old suggestions ever given to this
          // overlay.  I suspect such an approach would clean up this code quite
          // a bit.
          return false;
        }
      } else {
        lastPrefixQueriedForDuplicates = userInput;
        numDedupeAttempts = 1;
      }

      var autocompleteResults = GetAutocompleteResults();
      var nativeUrls = {};
      for (var i = 0, result; result = autocompleteResults[i]; ++i) {
        var nativeUrl = CanonicalizeUrl(result.destination_url);
        nativeUrls[nativeUrl] = result.rid;
      }
      for (var i = 0; clientSuggestions[i] &&
           i < MAX_CLIENT_SUGGESTIONS_TO_DEDUPE; ++i) {
        var result = clientSuggestions[i];
        if (result.url) {
          var clientUrl = CanonicalizeUrl(result.url);
          if (clientUrl in nativeUrls) {
            result.duplicateOf = nativeUrls[clientUrl];
          }
        }
      }
      return true;
    }

    // =========================================================================
    //                           Exported functions
    // =========================================================================
    this.__defineGetter__('value', GetQuery);
    this.__defineGetter__('verbatim', GetVerbatim);
    this.__defineGetter__('selectionStart', GetSelectionStart);
    this.__defineGetter__('selectionEnd', GetSelectionEnd);
    this.__defineGetter__('x', GetX);
    this.__defineGetter__('y', GetY);
    this.__defineGetter__('width', GetWidth);
    this.__defineGetter__('height', GetHeight);
    this.__defineGetter__('nativeSuggestions', GetAutocompleteResultsWrapper);
    this.__defineGetter__('isKeyCaptureEnabled', IsKeyCaptureEnabled);
    this.__defineGetter__('context', GetContext);
    this.__defineGetter__('displayInstantResults', GetDisplayInstantResults);
    this.__defineGetter__('themeBackgroundInfo', GetThemeBackgroundInfo);
    this.__defineGetter__('themeAreaHeight', GetThemeAreaHeight);
    this.setSuggestions = function(text) {
      SetSuggestions(text);
    };
    this.setAutocompleteText = function(text, behavior) {
      SetQuerySuggestion(text, behavior);
    };
    this.setRestrictedAutocompleteText = function(resultId) {
      SetQuerySuggestionFromAutocompleteResult(resultId);
    };
    this.setValue = function(text, type) {
      SetQuery(text, type);
    };
    this.setRestrictedValue = function(resultId) {
      SetQueryFromAutocompleteResult(resultId);
    };
    this.show = function(reason, height) {
      Show(reason, height);
    };
    this.markDuplicateSuggestions = function(clientSuggestions) {
      return DedupeClientSuggestions(clientSuggestions);
    };
    this.navigateContentWindow = function(destination) {
      return NavigateContentWindow(destination);
    };
    this.startCapturingKeyStrokes = function() {
      StartCapturingKeyStrokes();
    };
    this.stopCapturingKeyStrokes = function() {
      StopCapturingKeyStrokes();
    };
    this.onchange = null;
    this.onsubmit = null;
    this.oncancel = null;
    this.onresize = null;
    this.onautocompleteresults = null;
    this.onkeypress = null;
    this.onkeycapturechange = null;
    this.oncontextchange = null;
  };
}