searchbox.cc revision 1e9bf3e0803691d0a228da41fc608347b6db4340
1// Copyright 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/renderer/searchbox/searchbox.h"
6
7#include <string>
8
9#include "base/strings/string_number_conversions.h"
10#include "base/strings/string_util.h"
11#include "base/strings/utf_string_conversions.h"
12#include "chrome/common/chrome_switches.h"
13#include "chrome/common/favicon/favicon_types.h"
14#include "chrome/common/favicon/favicon_url_parser.h"
15#include "chrome/common/omnibox_focus_state.h"
16#include "chrome/common/render_messages.h"
17#include "chrome/common/url_constants.h"
18#include "chrome/renderer/searchbox/searchbox_extension.h"
19#include "content/public/renderer/render_view.h"
20#include "grit/renderer_resources.h"
21#include "net/base/escape.h"
22#include "third_party/WebKit/public/web/WebDocument.h"
23#include "third_party/WebKit/public/web/WebFrame.h"
24#include "third_party/WebKit/public/web/WebView.h"
25#include "ui/base/resource/resource_bundle.h"
26#include "url/gurl.h"
27
28namespace {
29
30// The size of the InstantMostVisitedItem cache.
31const size_t kMaxInstantMostVisitedItemCacheSize = 100;
32
33// Returns true if items stored in |old_item_id_pairs| and |new_items| are
34// equal.
35bool AreMostVisitedItemsEqual(
36    const std::vector<InstantMostVisitedItemIDPair>& old_item_id_pairs,
37    const std::vector<InstantMostVisitedItem>& new_items) {
38  if (old_item_id_pairs.size() != new_items.size())
39    return false;
40
41  for (size_t i = 0; i < new_items.size(); ++i) {
42    if (new_items[i].url != old_item_id_pairs[i].second.url ||
43        new_items[i].title != old_item_id_pairs[i].second.title) {
44      return false;
45    }
46  }
47  return true;
48}
49
50}  // namespace
51
52namespace internal {  // for testing
53
54// Parses |path| and fills in |id| with the InstantRestrictedID obtained from
55// the |path|. |render_view_id| is the ID of the associated RenderView.
56//
57// |path| is a pair of |render_view_id| and |restricted_id|, and it is
58// contained in Instant Extended URLs. A valid |path| is in the form:
59// <render_view_id>/<restricted_id>
60//
61// If the |path| is valid, returns true and fills in |id| with restricted_id
62// value. If the |path| is invalid, returns false and |id| is not set.
63bool GetInstantRestrictedIDFromPath(int render_view_id,
64                                    const std::string& path,
65                                    InstantRestrictedID* id) {
66  // Check that the path is of Most visited item ID form.
67  std::vector<std::string> tokens;
68  if (Tokenize(path, "/", &tokens) != 2)
69    return false;
70
71  int view_id = 0;
72  if (!base::StringToInt(tokens[0], &view_id) || view_id != render_view_id)
73    return false;
74  return base::StringToInt(tokens[1], id);
75}
76
77bool GetRestrictedIDFromFaviconUrl(int render_view_id,
78                                   const GURL& url,
79                                   std::string* favicon_params,
80                                   InstantRestrictedID* rid) {
81  // Strip leading slash.
82  std::string raw_path = url.path();
83  DCHECK_GT(raw_path.length(), (size_t) 0);
84  DCHECK_EQ(raw_path[0], '/');
85  raw_path = raw_path.substr(1);
86
87  chrome::ParsedFaviconPath parsed;
88  if (!chrome::ParseFaviconPath(raw_path, chrome::FAVICON, &parsed))
89    return false;
90
91  // The part of the URL which details the favicon parameters should be returned
92  // so the favicon URL can be reconstructed, by replacing the restricted_id
93  // with the actual URL from which the favicon is being requested.
94  *favicon_params = raw_path.substr(0, parsed.path_index);
95
96  // The part of the favicon URL which is supposed to contain the URL from
97  // which the favicon is being requested (i.e., the page's URL) actually
98  // contains a pair in the format "<view_id>/<restricted_id>". If the page's
99  // URL is not in the expected format then the execution must be stopped,
100  // returning |true|, indicating that the favicon URL should be translated
101  // without the page's URL part, to prevent search providers from spoofing
102  // the user's browsing history. For example, the following favicon URL
103  // "chrome-search://favicon/http://www.secretsite.com" it is not in the
104  // expected format "chrome-search://favicon/<view_id>/<restricted_id>" so
105  // the pages's URL part ("http://www.secretsite.com") should be removed
106  // entirely from the translated URL otherwise the search engine would know
107  // if the user has visited that page (by verifying whether the favicon URL
108  // returns an image for a particular page's URL); the translated URL in this
109  // case would be "chrome-search://favicon/" which would simply return the
110  // default favicon.
111  std::string id_part = raw_path.substr(parsed.path_index);
112  InstantRestrictedID id;
113  if (!GetInstantRestrictedIDFromPath(render_view_id, id_part, &id))
114    return true;
115
116  *rid = id;
117  return true;
118}
119
120// Parses a thumbnail |url| and fills in |id| with the InstantRestrictedID
121// obtained from the |url|. |render_view_id| is the ID of the associated
122// RenderView.
123//
124// Valid |url| forms:
125// chrome-search://thumb/<view_id>/<restricted_id>
126//
127// If the |url| is valid, returns true and fills in |id| with restricted_id
128// value. If the |url| is invalid, returns false and |id| is not set.
129bool GetRestrictedIDFromThumbnailUrl(int render_view_id,
130                                     const GURL& url,
131                                     InstantRestrictedID* id) {
132  // Strip leading slash.
133  std::string path = url.path();
134  DCHECK_GT(path.length(), (size_t) 0);
135  DCHECK_EQ(path[0], '/');
136  path = path.substr(1);
137
138  return GetInstantRestrictedIDFromPath(render_view_id, path, id);
139}
140
141}  // namespace internal
142
143SearchBox::SearchBox(content::RenderView* render_view)
144    : content::RenderViewObserver(render_view),
145      content::RenderViewObserverTracker<SearchBox>(render_view),
146    app_launcher_enabled_(false),
147    is_focused_(false),
148    is_input_in_progress_(false),
149    is_key_capture_enabled_(false),
150    display_instant_results_(false),
151    most_visited_items_cache_(kMaxInstantMostVisitedItemCacheSize),
152    query_(),
153    start_margin_(0),
154    width_(0) {
155}
156
157SearchBox::~SearchBox() {
158}
159
160void SearchBox::LogEvent(NTPLoggingEventType event) {
161  render_view()->Send(new ChromeViewHostMsg_LogEvent(
162      render_view()->GetRoutingID(), render_view()->GetPageId(), event));
163}
164
165void SearchBox::DeleteMostVisitedItem(
166    InstantRestrictedID most_visited_item_id) {
167  render_view()->Send(new ChromeViewHostMsg_SearchBoxDeleteMostVisitedItem(
168      render_view()->GetRoutingID(), render_view()->GetPageId(),
169      GetURLForMostVisitedItem(most_visited_item_id)));
170}
171
172bool SearchBox::GenerateFaviconURLFromTransientURL(const GURL& transient_url,
173                                                   GURL* url) const {
174  std::string favicon_params;
175  InstantRestrictedID rid = -1;
176  bool success = internal::GetRestrictedIDFromFaviconUrl(
177      render_view()->GetRoutingID(), transient_url, &favicon_params, &rid);
178  if (!success)
179    return false;
180
181  InstantMostVisitedItem item;
182  std::string item_url;
183  if (rid != -1 && GetMostVisitedItemWithID(rid, &item))
184    item_url = item.url.spec();
185
186  *url = GURL(base::StringPrintf("chrome-search://favicon/%s%s",
187                                 favicon_params.c_str(),
188                                 item_url.c_str()));
189  return true;
190}
191
192bool SearchBox::GenerateThumbnailURLFromTransientURL(const GURL& transient_url,
193                                                     GURL* url) const {
194  InstantRestrictedID rid = 0;
195  if (!internal::GetRestrictedIDFromThumbnailUrl(render_view()->GetRoutingID(),
196                                                 transient_url, &rid)) {
197    return false;
198  }
199
200  GURL most_visited_item_url(GetURLForMostVisitedItem(rid));
201  if (most_visited_item_url.is_empty())
202    return false;
203  *url = GURL(base::StringPrintf("chrome-search://thumb/%s",
204                                 most_visited_item_url.spec().c_str()));
205  return true;
206}
207
208void SearchBox::GetMostVisitedItems(
209    std::vector<InstantMostVisitedItemIDPair>* items) const {
210  return most_visited_items_cache_.GetCurrentItems(items);
211}
212
213bool SearchBox::GetMostVisitedItemWithID(
214    InstantRestrictedID most_visited_item_id,
215    InstantMostVisitedItem* item) const {
216  return most_visited_items_cache_.GetItemWithRestrictedID(most_visited_item_id,
217                                                           item);
218}
219
220const ThemeBackgroundInfo& SearchBox::GetThemeBackgroundInfo() {
221  return theme_info_;
222}
223
224void SearchBox::Focus() {
225  render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
226      render_view()->GetRoutingID(), render_view()->GetPageId(),
227      OMNIBOX_FOCUS_VISIBLE));
228}
229
230void SearchBox::NavigateToURL(const GURL& url,
231                              WindowOpenDisposition disposition,
232                              bool is_most_visited_item_url) {
233  render_view()->Send(new ChromeViewHostMsg_SearchBoxNavigate(
234      render_view()->GetRoutingID(), render_view()->GetPageId(), url,
235      disposition, is_most_visited_item_url));
236}
237
238void SearchBox::Paste(const string16& text) {
239  render_view()->Send(new ChromeViewHostMsg_PasteAndOpenDropdown(
240      render_view()->GetRoutingID(), render_view()->GetPageId(), text));
241}
242
243void SearchBox::SetVoiceSearchSupported(bool supported) {
244  render_view()->Send(new ChromeViewHostMsg_SetVoiceSearchSupported(
245      render_view()->GetRoutingID(), render_view()->GetPageId(), supported));
246}
247
248void SearchBox::StartCapturingKeyStrokes() {
249  render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
250      render_view()->GetRoutingID(), render_view()->GetPageId(),
251      OMNIBOX_FOCUS_INVISIBLE));
252}
253
254void SearchBox::StopCapturingKeyStrokes() {
255  render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
256      render_view()->GetRoutingID(), render_view()->GetPageId(),
257      OMNIBOX_FOCUS_NONE));
258}
259
260void SearchBox::UndoAllMostVisitedDeletions() {
261  render_view()->Send(
262      new ChromeViewHostMsg_SearchBoxUndoAllMostVisitedDeletions(
263      render_view()->GetRoutingID(), render_view()->GetPageId()));
264}
265
266void SearchBox::UndoMostVisitedDeletion(
267    InstantRestrictedID most_visited_item_id) {
268  render_view()->Send(new ChromeViewHostMsg_SearchBoxUndoMostVisitedDeletion(
269      render_view()->GetRoutingID(), render_view()->GetPageId(),
270      GetURLForMostVisitedItem(most_visited_item_id)));
271}
272
273bool SearchBox::OnMessageReceived(const IPC::Message& message) {
274  bool handled = true;
275  IPC_BEGIN_MESSAGE_MAP(SearchBox, message)
276    IPC_MESSAGE_HANDLER(ChromeViewMsg_DetermineIfPageSupportsInstant,
277                        OnDetermineIfPageSupportsInstant)
278    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFocusChanged, OnFocusChanged)
279    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMarginChange, OnMarginChange)
280    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMostVisitedItemsChanged,
281                        OnMostVisitedChanged)
282    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxPromoInformation,
283                        OnPromoInformationReceived)
284    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetDisplayInstantResults,
285                        OnSetDisplayInstantResults)
286    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetInputInProgress,
287                        OnSetInputInProgress)
288    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetSuggestionToPrefetch,
289                        OnSetSuggestionToPrefetch)
290    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSubmit, OnSubmit)
291    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxThemeChanged,
292                        OnThemeChanged)
293    IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch,
294                        OnToggleVoiceSearch)
295    IPC_MESSAGE_UNHANDLED(handled = false)
296  IPC_END_MESSAGE_MAP()
297  return handled;
298}
299
300void SearchBox::OnDetermineIfPageSupportsInstant() {
301  if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
302    bool result = extensions_v8::SearchBoxExtension::PageSupportsInstant(
303        render_view()->GetWebView()->mainFrame());
304    DVLOG(1) << render_view() << " PageSupportsInstant: " << result;
305    render_view()->Send(new ChromeViewHostMsg_InstantSupportDetermined(
306        render_view()->GetRoutingID(), render_view()->GetPageId(), result));
307  }
308}
309
310void SearchBox::OnFocusChanged(OmniboxFocusState new_focus_state,
311                               OmniboxFocusChangeReason reason) {
312  bool key_capture_enabled = new_focus_state == OMNIBOX_FOCUS_INVISIBLE;
313  if (key_capture_enabled != is_key_capture_enabled_) {
314    // Tell the page if the key capture mode changed unless the focus state
315    // changed because of TYPING. This is because in that case, the browser
316    // hasn't really stopped capturing key strokes.
317    //
318    // (More practically, if we don't do this check, the page would receive
319    // onkeycapturechange before the corresponding onchange, and the page would
320    // have no way of telling whether the keycapturechange happened because of
321    // some actual user action or just because they started typing.)
322    if (reason != OMNIBOX_FOCUS_CHANGE_TYPING &&
323        render_view()->GetWebView() &&
324        render_view()->GetWebView()->mainFrame()) {
325      is_key_capture_enabled_ = key_capture_enabled;
326      DVLOG(1) << render_view() << " OnKeyCaptureChange";
327      extensions_v8::SearchBoxExtension::DispatchKeyCaptureChange(
328          render_view()->GetWebView()->mainFrame());
329    }
330  }
331  bool is_focused = new_focus_state == OMNIBOX_FOCUS_VISIBLE;
332  if (is_focused != is_focused_) {
333    is_focused_ = is_focused;
334    DVLOG(1) << render_view() << " OnFocusChange";
335    if (render_view()->GetWebView() &&
336        render_view()->GetWebView()->mainFrame()) {
337      extensions_v8::SearchBoxExtension::DispatchFocusChange(
338          render_view()->GetWebView()->mainFrame());
339    }
340  }
341}
342
343void SearchBox::OnMarginChange(int margin, int width) {
344  start_margin_ = margin;
345  width_ = width;
346  if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
347    extensions_v8::SearchBoxExtension::DispatchMarginChange(
348        render_view()->GetWebView()->mainFrame());
349  }
350}
351
352void SearchBox::OnMostVisitedChanged(
353    const std::vector<InstantMostVisitedItem>& items) {
354  std::vector<InstantMostVisitedItemIDPair> last_known_items;
355  GetMostVisitedItems(&last_known_items);
356
357  if (AreMostVisitedItemsEqual(last_known_items, items))
358    return;  // Do not send duplicate onmostvisitedchange events.
359
360  most_visited_items_cache_.AddItems(items);
361  if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
362    extensions_v8::SearchBoxExtension::DispatchMostVisitedChanged(
363        render_view()->GetWebView()->mainFrame());
364  }
365}
366
367void SearchBox::OnPromoInformationReceived(bool is_app_launcher_enabled) {
368  app_launcher_enabled_ = is_app_launcher_enabled;
369}
370
371void SearchBox::OnSetDisplayInstantResults(bool display_instant_results) {
372  display_instant_results_ = display_instant_results;
373}
374
375void SearchBox::OnSetInputInProgress(bool is_input_in_progress) {
376  if (is_input_in_progress_ != is_input_in_progress) {
377    is_input_in_progress_ = is_input_in_progress;
378    DVLOG(1) << render_view() << " OnSetInputInProgress";
379    if (render_view()->GetWebView() &&
380        render_view()->GetWebView()->mainFrame()) {
381      if (is_input_in_progress_) {
382        extensions_v8::SearchBoxExtension::DispatchInputStart(
383            render_view()->GetWebView()->mainFrame());
384      } else {
385        extensions_v8::SearchBoxExtension::DispatchInputCancel(
386            render_view()->GetWebView()->mainFrame());
387      }
388    }
389  }
390}
391
392void SearchBox::OnSetSuggestionToPrefetch(const InstantSuggestion& suggestion) {
393  suggestion_ = suggestion;
394  if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
395    DVLOG(1) << render_view() << " OnSetSuggestionToPrefetch";
396    extensions_v8::SearchBoxExtension::DispatchSuggestionChange(
397        render_view()->GetWebView()->mainFrame());
398  }
399}
400
401void SearchBox::OnSubmit(const string16& query) {
402  query_ = query;
403  if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
404    DVLOG(1) << render_view() << " OnSubmit";
405    extensions_v8::SearchBoxExtension::DispatchSubmit(
406        render_view()->GetWebView()->mainFrame());
407  }
408  if (!query.empty())
409    Reset();
410}
411
412void SearchBox::OnThemeChanged(const ThemeBackgroundInfo& theme_info) {
413  // Do not send duplicate notifications.
414  if (theme_info_ == theme_info)
415    return;
416
417  theme_info_ = theme_info;
418  if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
419    extensions_v8::SearchBoxExtension::DispatchThemeChange(
420        render_view()->GetWebView()->mainFrame());
421  }
422}
423
424void SearchBox::OnToggleVoiceSearch() {
425  if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
426    extensions_v8::SearchBoxExtension::DispatchToggleVoiceSearch(
427        render_view()->GetWebView()->mainFrame());
428  }
429}
430
431GURL SearchBox::GetURLForMostVisitedItem(InstantRestrictedID item_id) const {
432  InstantMostVisitedItem item;
433  return GetMostVisitedItemWithID(item_id, &item) ? item.url : GURL();
434}
435
436void SearchBox::Reset() {
437  query_.clear();
438  suggestion_ = InstantSuggestion();
439  start_margin_ = 0;
440  width_ = 0;
441  is_focused_ = false;
442  is_key_capture_enabled_ = false;
443  theme_info_ = ThemeBackgroundInfo();
444}
445