Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / renderer / searchbox / searchbox.cc
blob6d0d42ce2b97c7bcdc9496f2330157e95158b982
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 "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"
28 namespace {
30 // The size of the InstantMostVisitedItem cache.
31 const size_t kMaxInstantMostVisitedItemCacheSize = 100;
33 // Returns true if items stored in |old_item_id_pairs| and |new_items| are
34 // equal.
35 bool 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;
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;
47 return true;
50 } // namespace
52 namespace internal { // for testing
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.
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>
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.
63 bool 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;
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);
77 bool 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);
87 chrome::ParsedFaviconPath parsed;
88 if (!chrome::ParseFaviconPath(raw_path, favicon_base::FAVICON, &parsed))
89 return false;
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);
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;
116 *rid = id;
117 return true;
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.
124 // Valid |url| forms:
125 // chrome-search://thumb/<view_id>/<restricted_id>
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.
129 bool 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);
138 return GetInstantRestrictedIDFromPath(render_view_id, path, id);
141 } // namespace internal
143 SearchBox::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) {
156 SearchBox::~SearchBox() {
159 void SearchBox::LogEvent(NTPLoggingEventType event) {
160 render_view()->Send(new ChromeViewHostMsg_LogEvent(
161 render_view()->GetRoutingID(), render_view()->GetPageId(), event));
164 void SearchBox::LogMostVisitedImpression(int position,
165 const base::string16& provider) {
166 render_view()->Send(new ChromeViewHostMsg_LogMostVisitedImpression(
167 render_view()->GetRoutingID(), render_view()->GetPageId(), position,
168 provider));
171 void SearchBox::LogMostVisitedNavigation(int position,
172 const base::string16& provider) {
173 render_view()->Send(new ChromeViewHostMsg_LogMostVisitedNavigation(
174 render_view()->GetRoutingID(), render_view()->GetPageId(), position,
175 provider));
178 void SearchBox::CheckIsUserSignedInToChromeAs(const base::string16& identity) {
179 render_view()->Send(new ChromeViewHostMsg_ChromeIdentityCheck(
180 render_view()->GetRoutingID(), render_view()->GetPageId(), identity));
183 void SearchBox::DeleteMostVisitedItem(
184 InstantRestrictedID most_visited_item_id) {
185 render_view()->Send(new ChromeViewHostMsg_SearchBoxDeleteMostVisitedItem(
186 render_view()->GetRoutingID(), render_view()->GetPageId(),
187 GetURLForMostVisitedItem(most_visited_item_id)));
190 bool SearchBox::GenerateFaviconURLFromTransientURL(const GURL& transient_url,
191 GURL* url) const {
192 std::string favicon_params;
193 InstantRestrictedID rid = -1;
194 bool success = internal::GetRestrictedIDFromFaviconUrl(
195 render_view()->GetRoutingID(), transient_url, &favicon_params, &rid);
196 if (!success)
197 return false;
199 InstantMostVisitedItem item;
200 std::string item_url;
201 if (rid != -1 && GetMostVisitedItemWithID(rid, &item))
202 item_url = item.url.spec();
204 *url = GURL(base::StringPrintf("chrome-search://favicon/%s%s",
205 favicon_params.c_str(),
206 item_url.c_str()));
207 return true;
210 bool SearchBox::GenerateThumbnailURLFromTransientURL(const GURL& transient_url,
211 GURL* url) const {
212 InstantRestrictedID rid = 0;
213 if (!internal::GetRestrictedIDFromThumbnailUrl(render_view()->GetRoutingID(),
214 transient_url, &rid)) {
215 return false;
218 GURL most_visited_item_url(GetURLForMostVisitedItem(rid));
219 if (most_visited_item_url.is_empty())
220 return false;
221 *url = GURL(base::StringPrintf("chrome-search://thumb/%s",
222 most_visited_item_url.spec().c_str()));
223 return true;
226 void SearchBox::GetMostVisitedItems(
227 std::vector<InstantMostVisitedItemIDPair>* items) const {
228 return most_visited_items_cache_.GetCurrentItems(items);
231 bool SearchBox::GetMostVisitedItemWithID(
232 InstantRestrictedID most_visited_item_id,
233 InstantMostVisitedItem* item) const {
234 return most_visited_items_cache_.GetItemWithRestrictedID(most_visited_item_id,
235 item);
238 const ThemeBackgroundInfo& SearchBox::GetThemeBackgroundInfo() {
239 return theme_info_;
242 void SearchBox::Focus() {
243 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
244 render_view()->GetRoutingID(), render_view()->GetPageId(),
245 OMNIBOX_FOCUS_VISIBLE));
248 void SearchBox::NavigateToURL(const GURL& url,
249 WindowOpenDisposition disposition,
250 bool is_most_visited_item_url) {
251 render_view()->Send(new ChromeViewHostMsg_SearchBoxNavigate(
252 render_view()->GetRoutingID(), render_view()->GetPageId(), url,
253 disposition, is_most_visited_item_url));
256 void SearchBox::Paste(const base::string16& text) {
257 render_view()->Send(new ChromeViewHostMsg_PasteAndOpenDropdown(
258 render_view()->GetRoutingID(), render_view()->GetPageId(), text));
261 void SearchBox::SetVoiceSearchSupported(bool supported) {
262 render_view()->Send(new ChromeViewHostMsg_SetVoiceSearchSupported(
263 render_view()->GetRoutingID(), render_view()->GetPageId(), supported));
266 void SearchBox::StartCapturingKeyStrokes() {
267 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
268 render_view()->GetRoutingID(), render_view()->GetPageId(),
269 OMNIBOX_FOCUS_INVISIBLE));
272 void SearchBox::StopCapturingKeyStrokes() {
273 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
274 render_view()->GetRoutingID(), render_view()->GetPageId(),
275 OMNIBOX_FOCUS_NONE));
278 void SearchBox::UndoAllMostVisitedDeletions() {
279 render_view()->Send(
280 new ChromeViewHostMsg_SearchBoxUndoAllMostVisitedDeletions(
281 render_view()->GetRoutingID(), render_view()->GetPageId()));
284 void SearchBox::UndoMostVisitedDeletion(
285 InstantRestrictedID most_visited_item_id) {
286 render_view()->Send(new ChromeViewHostMsg_SearchBoxUndoMostVisitedDeletion(
287 render_view()->GetRoutingID(), render_view()->GetPageId(),
288 GetURLForMostVisitedItem(most_visited_item_id)));
291 bool SearchBox::OnMessageReceived(const IPC::Message& message) {
292 bool handled = true;
293 IPC_BEGIN_MESSAGE_MAP(SearchBox, message)
294 IPC_MESSAGE_HANDLER(ChromeViewMsg_ChromeIdentityCheckResult,
295 OnChromeIdentityCheckResult)
296 IPC_MESSAGE_HANDLER(ChromeViewMsg_DetermineIfPageSupportsInstant,
297 OnDetermineIfPageSupportsInstant)
298 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFocusChanged, OnFocusChanged)
299 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMarginChange, OnMarginChange)
300 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMostVisitedItemsChanged,
301 OnMostVisitedChanged)
302 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxPromoInformation,
303 OnPromoInformationReceived)
304 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetDisplayInstantResults,
305 OnSetDisplayInstantResults)
306 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetInputInProgress,
307 OnSetInputInProgress)
308 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetSuggestionToPrefetch,
309 OnSetSuggestionToPrefetch)
310 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSubmit, OnSubmit)
311 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxThemeChanged,
312 OnThemeChanged)
313 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch,
314 OnToggleVoiceSearch)
315 IPC_MESSAGE_UNHANDLED(handled = false)
316 IPC_END_MESSAGE_MAP()
317 return handled;
320 void SearchBox::OnChromeIdentityCheckResult(const base::string16& identity,
321 bool identity_match) {
322 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
323 extensions_v8::SearchBoxExtension::DispatchChromeIdentityCheckResult(
324 render_view()->GetWebView()->mainFrame(), identity, identity_match);
328 void SearchBox::OnDetermineIfPageSupportsInstant() {
329 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
330 bool result = extensions_v8::SearchBoxExtension::PageSupportsInstant(
331 render_view()->GetWebView()->mainFrame());
332 DVLOG(1) << render_view() << " PageSupportsInstant: " << result;
333 render_view()->Send(new ChromeViewHostMsg_InstantSupportDetermined(
334 render_view()->GetRoutingID(), render_view()->GetPageId(), result));
338 void SearchBox::OnFocusChanged(OmniboxFocusState new_focus_state,
339 OmniboxFocusChangeReason reason) {
340 bool key_capture_enabled = new_focus_state == OMNIBOX_FOCUS_INVISIBLE;
341 if (key_capture_enabled != is_key_capture_enabled_) {
342 // Tell the page if the key capture mode changed unless the focus state
343 // changed because of TYPING. This is because in that case, the browser
344 // hasn't really stopped capturing key strokes.
346 // (More practically, if we don't do this check, the page would receive
347 // onkeycapturechange before the corresponding onchange, and the page would
348 // have no way of telling whether the keycapturechange happened because of
349 // some actual user action or just because they started typing.)
350 if (reason != OMNIBOX_FOCUS_CHANGE_TYPING &&
351 render_view()->GetWebView() &&
352 render_view()->GetWebView()->mainFrame()) {
353 is_key_capture_enabled_ = key_capture_enabled;
354 DVLOG(1) << render_view() << " OnKeyCaptureChange";
355 extensions_v8::SearchBoxExtension::DispatchKeyCaptureChange(
356 render_view()->GetWebView()->mainFrame());
359 bool is_focused = new_focus_state == OMNIBOX_FOCUS_VISIBLE;
360 if (is_focused != is_focused_) {
361 is_focused_ = is_focused;
362 DVLOG(1) << render_view() << " OnFocusChange";
363 if (render_view()->GetWebView() &&
364 render_view()->GetWebView()->mainFrame()) {
365 extensions_v8::SearchBoxExtension::DispatchFocusChange(
366 render_view()->GetWebView()->mainFrame());
371 void SearchBox::OnMarginChange(int margin) {
372 start_margin_ = margin;
373 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
374 extensions_v8::SearchBoxExtension::DispatchMarginChange(
375 render_view()->GetWebView()->mainFrame());
379 void SearchBox::OnMostVisitedChanged(
380 const std::vector<InstantMostVisitedItem>& items) {
381 std::vector<InstantMostVisitedItemIDPair> last_known_items;
382 GetMostVisitedItems(&last_known_items);
384 if (AreMostVisitedItemsEqual(last_known_items, items))
385 return; // Do not send duplicate onmostvisitedchange events.
387 most_visited_items_cache_.AddItems(items);
388 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
389 extensions_v8::SearchBoxExtension::DispatchMostVisitedChanged(
390 render_view()->GetWebView()->mainFrame());
394 void SearchBox::OnPromoInformationReceived(bool is_app_launcher_enabled) {
395 app_launcher_enabled_ = is_app_launcher_enabled;
398 void SearchBox::OnSetDisplayInstantResults(bool display_instant_results) {
399 display_instant_results_ = display_instant_results;
402 void SearchBox::OnSetInputInProgress(bool is_input_in_progress) {
403 if (is_input_in_progress_ != is_input_in_progress) {
404 is_input_in_progress_ = is_input_in_progress;
405 DVLOG(1) << render_view() << " OnSetInputInProgress";
406 if (render_view()->GetWebView() &&
407 render_view()->GetWebView()->mainFrame()) {
408 if (is_input_in_progress_) {
409 extensions_v8::SearchBoxExtension::DispatchInputStart(
410 render_view()->GetWebView()->mainFrame());
411 } else {
412 extensions_v8::SearchBoxExtension::DispatchInputCancel(
413 render_view()->GetWebView()->mainFrame());
419 void SearchBox::OnSetSuggestionToPrefetch(const InstantSuggestion& suggestion) {
420 suggestion_ = suggestion;
421 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
422 DVLOG(1) << render_view() << " OnSetSuggestionToPrefetch";
423 extensions_v8::SearchBoxExtension::DispatchSuggestionChange(
424 render_view()->GetWebView()->mainFrame());
428 void SearchBox::OnSubmit(const base::string16& query) {
429 query_ = query;
430 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
431 DVLOG(1) << render_view() << " OnSubmit";
432 extensions_v8::SearchBoxExtension::DispatchSubmit(
433 render_view()->GetWebView()->mainFrame());
435 if (!query.empty())
436 Reset();
439 void SearchBox::OnThemeChanged(const ThemeBackgroundInfo& theme_info) {
440 // Do not send duplicate notifications.
441 if (theme_info_ == theme_info)
442 return;
444 theme_info_ = theme_info;
445 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
446 extensions_v8::SearchBoxExtension::DispatchThemeChange(
447 render_view()->GetWebView()->mainFrame());
451 void SearchBox::OnToggleVoiceSearch() {
452 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
453 extensions_v8::SearchBoxExtension::DispatchToggleVoiceSearch(
454 render_view()->GetWebView()->mainFrame());
458 GURL SearchBox::GetURLForMostVisitedItem(InstantRestrictedID item_id) const {
459 InstantMostVisitedItem item;
460 return GetMostVisitedItemWithID(item_id, &item) ? item.url : GURL();
463 void SearchBox::Reset() {
464 query_.clear();
465 suggestion_ = InstantSuggestion();
466 start_margin_ = 0;
467 is_focused_ = false;
468 is_key_capture_enabled_ = false;
469 theme_info_ = ThemeBackgroundInfo();