Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / chrome / renderer / searchbox / searchbox.cc
blobf639bfc9c5933efc96709349d321850188b13b92
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.
5 #include "chrome/renderer/searchbox/searchbox.h"
7 #include <string>
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_url_parser.h"
14 #include "chrome/common/omnibox_focus_state.h"
15 #include "chrome/common/render_messages.h"
16 #include "chrome/common/url_constants.h"
17 #include "chrome/renderer/searchbox/searchbox_extension.h"
18 #include "components/favicon_base/favicon_types.h"
19 #include "content/public/renderer/render_view.h"
20 #include "net/base/escape.h"
21 #include "third_party/WebKit/public/web/WebDocument.h"
22 #include "third_party/WebKit/public/web/WebFrame.h"
23 #include "third_party/WebKit/public/web/WebView.h"
24 #include "url/gurl.h"
26 namespace {
28 // The size of the InstantMostVisitedItem cache.
29 const size_t kMaxInstantMostVisitedItemCacheSize = 100;
31 // Returns true if items stored in |old_item_id_pairs| and |new_items| are
32 // equal.
33 bool AreMostVisitedItemsEqual(
34 const std::vector<InstantMostVisitedItemIDPair>& old_item_id_pairs,
35 const std::vector<InstantMostVisitedItem>& new_items) {
36 if (old_item_id_pairs.size() != new_items.size())
37 return false;
39 for (size_t i = 0; i < new_items.size(); ++i) {
40 if (new_items[i].url != old_item_id_pairs[i].second.url ||
41 new_items[i].title != old_item_id_pairs[i].second.title) {
42 return false;
45 return true;
48 } // namespace
50 namespace internal { // for testing
52 // Parses |path| and fills in |id| with the InstantRestrictedID obtained from
53 // the |path|. |render_view_id| is the ID of the associated RenderView.
55 // |path| is a pair of |render_view_id| and |restricted_id|, and it is
56 // contained in Instant Extended URLs. A valid |path| is in the form:
57 // <render_view_id>/<restricted_id>
59 // If the |path| is valid, returns true and fills in |id| with restricted_id
60 // value. If the |path| is invalid, returns false and |id| is not set.
61 bool GetInstantRestrictedIDFromPath(int render_view_id,
62 const std::string& path,
63 InstantRestrictedID* id) {
64 // Check that the path is of Most visited item ID form.
65 std::vector<std::string> tokens;
66 if (Tokenize(path, "/", &tokens) != 2)
67 return false;
69 int view_id = 0;
70 if (!base::StringToInt(tokens[0], &view_id) || view_id != render_view_id)
71 return false;
72 return base::StringToInt(tokens[1], id);
75 bool GetRestrictedIDFromFaviconUrl(int render_view_id,
76 const GURL& url,
77 std::string* favicon_params,
78 InstantRestrictedID* rid) {
79 // Strip leading slash.
80 std::string raw_path = url.path();
81 DCHECK_GT(raw_path.length(), (size_t) 0);
82 DCHECK_EQ(raw_path[0], '/');
83 raw_path = raw_path.substr(1);
85 chrome::ParsedFaviconPath parsed;
86 if (!chrome::ParseFaviconPath(raw_path, favicon_base::FAVICON, &parsed))
87 return false;
89 // The part of the URL which details the favicon parameters should be returned
90 // so the favicon URL can be reconstructed, by replacing the restricted_id
91 // with the actual URL from which the favicon is being requested.
92 *favicon_params = raw_path.substr(0, parsed.path_index);
94 // The part of the favicon URL which is supposed to contain the URL from
95 // which the favicon is being requested (i.e., the page's URL) actually
96 // contains a pair in the format "<view_id>/<restricted_id>". If the page's
97 // URL is not in the expected format then the execution must be stopped,
98 // returning |true|, indicating that the favicon URL should be translated
99 // without the page's URL part, to prevent search providers from spoofing
100 // the user's browsing history. For example, the following favicon URL
101 // "chrome-search://favicon/http://www.secretsite.com" it is not in the
102 // expected format "chrome-search://favicon/<view_id>/<restricted_id>" so
103 // the pages's URL part ("http://www.secretsite.com") should be removed
104 // entirely from the translated URL otherwise the search engine would know
105 // if the user has visited that page (by verifying whether the favicon URL
106 // returns an image for a particular page's URL); the translated URL in this
107 // case would be "chrome-search://favicon/" which would simply return the
108 // default favicon.
109 std::string id_part = raw_path.substr(parsed.path_index);
110 InstantRestrictedID id;
111 if (!GetInstantRestrictedIDFromPath(render_view_id, id_part, &id))
112 return true;
114 *rid = id;
115 return true;
118 // Parses a thumbnail |url| and fills in |id| with the InstantRestrictedID
119 // obtained from the |url|. |render_view_id| is the ID of the associated
120 // RenderView.
122 // Valid |url| forms:
123 // chrome-search://thumb/<view_id>/<restricted_id>
125 // If the |url| is valid, returns true and fills in |id| with restricted_id
126 // value. If the |url| is invalid, returns false and |id| is not set.
127 bool GetRestrictedIDFromThumbnailUrl(int render_view_id,
128 const GURL& url,
129 InstantRestrictedID* id) {
130 // Strip leading slash.
131 std::string path = url.path();
132 DCHECK_GT(path.length(), (size_t) 0);
133 DCHECK_EQ(path[0], '/');
134 path = path.substr(1);
136 return GetInstantRestrictedIDFromPath(render_view_id, path, id);
139 } // namespace internal
141 SearchBox::SearchBox(content::RenderView* render_view)
142 : content::RenderViewObserver(render_view),
143 content::RenderViewObserverTracker<SearchBox>(render_view),
144 page_seq_no_(0),
145 app_launcher_enabled_(false),
146 is_focused_(false),
147 is_input_in_progress_(false),
148 is_key_capture_enabled_(false),
149 display_instant_results_(false),
150 most_visited_items_cache_(kMaxInstantMostVisitedItemCacheSize),
151 query_(),
152 start_margin_(0) {
155 SearchBox::~SearchBox() {
158 void SearchBox::LogEvent(NTPLoggingEventType event) {
159 render_view()->Send(new ChromeViewHostMsg_LogEvent(
160 render_view()->GetRoutingID(), page_seq_no_, event));
163 void SearchBox::LogMostVisitedImpression(int position,
164 const base::string16& provider) {
165 render_view()->Send(new ChromeViewHostMsg_LogMostVisitedImpression(
166 render_view()->GetRoutingID(), page_seq_no_, position, provider));
169 void SearchBox::LogMostVisitedNavigation(int position,
170 const base::string16& provider) {
171 render_view()->Send(new ChromeViewHostMsg_LogMostVisitedNavigation(
172 render_view()->GetRoutingID(), page_seq_no_, position, provider));
175 void SearchBox::CheckIsUserSignedInToChromeAs(const base::string16& identity) {
176 render_view()->Send(new ChromeViewHostMsg_ChromeIdentityCheck(
177 render_view()->GetRoutingID(), page_seq_no_, identity));
180 void SearchBox::DeleteMostVisitedItem(
181 InstantRestrictedID most_visited_item_id) {
182 render_view()->Send(new ChromeViewHostMsg_SearchBoxDeleteMostVisitedItem(
183 render_view()->GetRoutingID(),
184 page_seq_no_,
185 GetURLForMostVisitedItem(most_visited_item_id)));
188 bool SearchBox::GenerateFaviconURLFromTransientURL(const GURL& transient_url,
189 GURL* url) const {
190 std::string favicon_params;
191 InstantRestrictedID rid = -1;
192 bool success = internal::GetRestrictedIDFromFaviconUrl(
193 render_view()->GetRoutingID(), transient_url, &favicon_params, &rid);
194 if (!success)
195 return false;
197 InstantMostVisitedItem item;
198 std::string item_url;
199 if (rid != -1 && GetMostVisitedItemWithID(rid, &item))
200 item_url = item.url.spec();
202 *url = GURL(base::StringPrintf("chrome-search://favicon/%s%s",
203 favicon_params.c_str(),
204 item_url.c_str()));
205 return true;
208 bool SearchBox::GenerateThumbnailURLFromTransientURL(const GURL& transient_url,
209 GURL* url) const {
210 InstantRestrictedID rid = 0;
211 if (!internal::GetRestrictedIDFromThumbnailUrl(render_view()->GetRoutingID(),
212 transient_url, &rid)) {
213 return false;
216 GURL most_visited_item_url(GetURLForMostVisitedItem(rid));
217 if (most_visited_item_url.is_empty())
218 return false;
219 *url = GURL(base::StringPrintf("chrome-search://thumb/%s",
220 most_visited_item_url.spec().c_str()));
221 return true;
224 void SearchBox::GetMostVisitedItems(
225 std::vector<InstantMostVisitedItemIDPair>* items) const {
226 return most_visited_items_cache_.GetCurrentItems(items);
229 bool SearchBox::GetMostVisitedItemWithID(
230 InstantRestrictedID most_visited_item_id,
231 InstantMostVisitedItem* item) const {
232 return most_visited_items_cache_.GetItemWithRestrictedID(most_visited_item_id,
233 item);
236 const ThemeBackgroundInfo& SearchBox::GetThemeBackgroundInfo() {
237 return theme_info_;
240 const EmbeddedSearchRequestParams& SearchBox::GetEmbeddedSearchRequestParams() {
241 return embedded_search_request_params_;
244 void SearchBox::Focus() {
245 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
246 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_VISIBLE));
249 void SearchBox::NavigateToURL(const GURL& url,
250 WindowOpenDisposition disposition,
251 bool is_most_visited_item_url) {
252 render_view()->Send(new ChromeViewHostMsg_SearchBoxNavigate(
253 render_view()->GetRoutingID(), page_seq_no_, url,
254 disposition, is_most_visited_item_url));
257 void SearchBox::Paste(const base::string16& text) {
258 render_view()->Send(new ChromeViewHostMsg_PasteAndOpenDropdown(
259 render_view()->GetRoutingID(), page_seq_no_, text));
262 void SearchBox::SetVoiceSearchSupported(bool supported) {
263 render_view()->Send(new ChromeViewHostMsg_SetVoiceSearchSupported(
264 render_view()->GetRoutingID(), page_seq_no_, supported));
267 void SearchBox::StartCapturingKeyStrokes() {
268 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
269 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_INVISIBLE));
272 void SearchBox::StopCapturingKeyStrokes() {
273 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
274 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_NONE));
277 void SearchBox::UndoAllMostVisitedDeletions() {
278 render_view()->Send(
279 new ChromeViewHostMsg_SearchBoxUndoAllMostVisitedDeletions(
280 render_view()->GetRoutingID(), page_seq_no_));
283 void SearchBox::UndoMostVisitedDeletion(
284 InstantRestrictedID most_visited_item_id) {
285 render_view()->Send(new ChromeViewHostMsg_SearchBoxUndoMostVisitedDeletion(
286 render_view()->GetRoutingID(), page_seq_no_,
287 GetURLForMostVisitedItem(most_visited_item_id)));
290 bool SearchBox::OnMessageReceived(const IPC::Message& message) {
291 bool handled = true;
292 IPC_BEGIN_MESSAGE_MAP(SearchBox, message)
293 IPC_MESSAGE_HANDLER(ChromeViewMsg_SetPageSequenceNumber,
294 OnSetPageSequenceNumber)
295 IPC_MESSAGE_HANDLER(ChromeViewMsg_ChromeIdentityCheckResult,
296 OnChromeIdentityCheckResult)
297 IPC_MESSAGE_HANDLER(ChromeViewMsg_DetermineIfPageSupportsInstant,
298 OnDetermineIfPageSupportsInstant)
299 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFocusChanged, OnFocusChanged)
300 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMarginChange, OnMarginChange)
301 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMostVisitedItemsChanged,
302 OnMostVisitedChanged)
303 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxPromoInformation,
304 OnPromoInformationReceived)
305 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetDisplayInstantResults,
306 OnSetDisplayInstantResults)
307 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetInputInProgress,
308 OnSetInputInProgress)
309 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetSuggestionToPrefetch,
310 OnSetSuggestionToPrefetch)
311 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSubmit, OnSubmit)
312 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxThemeChanged,
313 OnThemeChanged)
314 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch,
315 OnToggleVoiceSearch)
316 IPC_MESSAGE_UNHANDLED(handled = false)
317 IPC_END_MESSAGE_MAP()
318 return handled;
321 void SearchBox::OnSetPageSequenceNumber(int page_seq_no) {
322 page_seq_no_ = page_seq_no;
325 void SearchBox::OnChromeIdentityCheckResult(const base::string16& identity,
326 bool identity_match) {
327 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
328 extensions_v8::SearchBoxExtension::DispatchChromeIdentityCheckResult(
329 render_view()->GetWebView()->mainFrame(), identity, identity_match);
333 void SearchBox::OnDetermineIfPageSupportsInstant() {
334 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
335 bool result = extensions_v8::SearchBoxExtension::PageSupportsInstant(
336 render_view()->GetWebView()->mainFrame());
337 DVLOG(1) << render_view() << " PageSupportsInstant: " << result;
338 render_view()->Send(new ChromeViewHostMsg_InstantSupportDetermined(
339 render_view()->GetRoutingID(), page_seq_no_, result));
343 void SearchBox::OnFocusChanged(OmniboxFocusState new_focus_state,
344 OmniboxFocusChangeReason reason) {
345 bool key_capture_enabled = new_focus_state == OMNIBOX_FOCUS_INVISIBLE;
346 if (key_capture_enabled != is_key_capture_enabled_) {
347 // Tell the page if the key capture mode changed unless the focus state
348 // changed because of TYPING. This is because in that case, the browser
349 // hasn't really stopped capturing key strokes.
351 // (More practically, if we don't do this check, the page would receive
352 // onkeycapturechange before the corresponding onchange, and the page would
353 // have no way of telling whether the keycapturechange happened because of
354 // some actual user action or just because they started typing.)
355 if (reason != OMNIBOX_FOCUS_CHANGE_TYPING &&
356 render_view()->GetWebView() &&
357 render_view()->GetWebView()->mainFrame()) {
358 is_key_capture_enabled_ = key_capture_enabled;
359 DVLOG(1) << render_view() << " OnKeyCaptureChange";
360 extensions_v8::SearchBoxExtension::DispatchKeyCaptureChange(
361 render_view()->GetWebView()->mainFrame());
364 bool is_focused = new_focus_state == OMNIBOX_FOCUS_VISIBLE;
365 if (is_focused != is_focused_) {
366 is_focused_ = is_focused;
367 DVLOG(1) << render_view() << " OnFocusChange";
368 if (render_view()->GetWebView() &&
369 render_view()->GetWebView()->mainFrame()) {
370 extensions_v8::SearchBoxExtension::DispatchFocusChange(
371 render_view()->GetWebView()->mainFrame());
376 void SearchBox::OnMarginChange(int margin) {
377 start_margin_ = margin;
378 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
379 extensions_v8::SearchBoxExtension::DispatchMarginChange(
380 render_view()->GetWebView()->mainFrame());
384 void SearchBox::OnMostVisitedChanged(
385 const std::vector<InstantMostVisitedItem>& items) {
386 std::vector<InstantMostVisitedItemIDPair> last_known_items;
387 GetMostVisitedItems(&last_known_items);
389 if (AreMostVisitedItemsEqual(last_known_items, items))
390 return; // Do not send duplicate onmostvisitedchange events.
392 most_visited_items_cache_.AddItems(items);
393 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
394 extensions_v8::SearchBoxExtension::DispatchMostVisitedChanged(
395 render_view()->GetWebView()->mainFrame());
399 void SearchBox::OnPromoInformationReceived(bool is_app_launcher_enabled) {
400 app_launcher_enabled_ = is_app_launcher_enabled;
403 void SearchBox::OnSetDisplayInstantResults(bool display_instant_results) {
404 display_instant_results_ = display_instant_results;
407 void SearchBox::OnSetInputInProgress(bool is_input_in_progress) {
408 if (is_input_in_progress_ != is_input_in_progress) {
409 is_input_in_progress_ = is_input_in_progress;
410 DVLOG(1) << render_view() << " OnSetInputInProgress";
411 if (render_view()->GetWebView() &&
412 render_view()->GetWebView()->mainFrame()) {
413 if (is_input_in_progress_) {
414 extensions_v8::SearchBoxExtension::DispatchInputStart(
415 render_view()->GetWebView()->mainFrame());
416 } else {
417 extensions_v8::SearchBoxExtension::DispatchInputCancel(
418 render_view()->GetWebView()->mainFrame());
424 void SearchBox::OnSetSuggestionToPrefetch(const InstantSuggestion& suggestion) {
425 suggestion_ = suggestion;
426 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
427 DVLOG(1) << render_view() << " OnSetSuggestionToPrefetch";
428 extensions_v8::SearchBoxExtension::DispatchSuggestionChange(
429 render_view()->GetWebView()->mainFrame());
433 void SearchBox::OnSubmit(const base::string16& query,
434 const EmbeddedSearchRequestParams& params) {
435 query_ = query;
436 embedded_search_request_params_ = params;
437 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
438 DVLOG(1) << render_view() << " OnSubmit";
439 extensions_v8::SearchBoxExtension::DispatchSubmit(
440 render_view()->GetWebView()->mainFrame());
442 if (!query.empty())
443 Reset();
446 void SearchBox::OnThemeChanged(const ThemeBackgroundInfo& theme_info) {
447 // Do not send duplicate notifications.
448 if (theme_info_ == theme_info)
449 return;
451 theme_info_ = theme_info;
452 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
453 extensions_v8::SearchBoxExtension::DispatchThemeChange(
454 render_view()->GetWebView()->mainFrame());
458 void SearchBox::OnToggleVoiceSearch() {
459 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
460 extensions_v8::SearchBoxExtension::DispatchToggleVoiceSearch(
461 render_view()->GetWebView()->mainFrame());
465 GURL SearchBox::GetURLForMostVisitedItem(InstantRestrictedID item_id) const {
466 InstantMostVisitedItem item;
467 return GetMostVisitedItemWithID(item_id, &item) ? item.url : GURL();
470 void SearchBox::Reset() {
471 query_.clear();
472 embedded_search_request_params_ = EmbeddedSearchRequestParams();
473 suggestion_ = InstantSuggestion();
474 start_margin_ = 0;
475 is_focused_ = false;
476 is_key_capture_enabled_ = false;
477 theme_info_ = ThemeBackgroundInfo();