Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / chrome / renderer / searchbox / searchbox.cc
blob9adce8536714bf97658937ee385048a46db5c780
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::CheckIsUserSyncingHistory() {
181 render_view()->Send(new ChromeViewHostMsg_HistorySyncCheck(
182 render_view()->GetRoutingID(), page_seq_no_));
185 void SearchBox::DeleteMostVisitedItem(
186 InstantRestrictedID most_visited_item_id) {
187 render_view()->Send(new ChromeViewHostMsg_SearchBoxDeleteMostVisitedItem(
188 render_view()->GetRoutingID(),
189 page_seq_no_,
190 GetURLForMostVisitedItem(most_visited_item_id)));
193 bool SearchBox::GenerateFaviconURLFromTransientURL(const GURL& transient_url,
194 GURL* url) const {
195 std::string favicon_params;
196 InstantRestrictedID rid = -1;
197 bool success = internal::GetRestrictedIDFromFaviconUrl(
198 render_view()->GetRoutingID(), transient_url, &favicon_params, &rid);
199 if (!success)
200 return false;
202 InstantMostVisitedItem item;
203 std::string item_url;
204 if (rid != -1 && GetMostVisitedItemWithID(rid, &item))
205 item_url = item.url.spec();
207 *url = GURL(base::StringPrintf("chrome-search://favicon/%s%s",
208 favicon_params.c_str(),
209 item_url.c_str()));
210 return true;
213 bool SearchBox::GenerateThumbnailURLFromTransientURL(const GURL& transient_url,
214 GURL* url) const {
215 InstantRestrictedID rid = 0;
216 if (!internal::GetRestrictedIDFromThumbnailUrl(render_view()->GetRoutingID(),
217 transient_url, &rid)) {
218 return false;
221 GURL most_visited_item_url(GetURLForMostVisitedItem(rid));
222 if (most_visited_item_url.is_empty())
223 return false;
224 *url = GURL(base::StringPrintf("chrome-search://thumb/%s",
225 most_visited_item_url.spec().c_str()));
226 return true;
229 void SearchBox::GetMostVisitedItems(
230 std::vector<InstantMostVisitedItemIDPair>* items) const {
231 return most_visited_items_cache_.GetCurrentItems(items);
234 bool SearchBox::GetMostVisitedItemWithID(
235 InstantRestrictedID most_visited_item_id,
236 InstantMostVisitedItem* item) const {
237 return most_visited_items_cache_.GetItemWithRestrictedID(most_visited_item_id,
238 item);
241 const ThemeBackgroundInfo& SearchBox::GetThemeBackgroundInfo() {
242 return theme_info_;
245 const EmbeddedSearchRequestParams& SearchBox::GetEmbeddedSearchRequestParams() {
246 return embedded_search_request_params_;
249 void SearchBox::Focus() {
250 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
251 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_VISIBLE));
254 void SearchBox::NavigateToURL(const GURL& url,
255 WindowOpenDisposition disposition,
256 bool is_most_visited_item_url) {
257 render_view()->Send(new ChromeViewHostMsg_SearchBoxNavigate(
258 render_view()->GetRoutingID(), page_seq_no_, url,
259 disposition, is_most_visited_item_url));
262 void SearchBox::Paste(const base::string16& text) {
263 render_view()->Send(new ChromeViewHostMsg_PasteAndOpenDropdown(
264 render_view()->GetRoutingID(), page_seq_no_, text));
267 void SearchBox::SetVoiceSearchSupported(bool supported) {
268 render_view()->Send(new ChromeViewHostMsg_SetVoiceSearchSupported(
269 render_view()->GetRoutingID(), page_seq_no_, supported));
272 void SearchBox::StartCapturingKeyStrokes() {
273 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
274 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_INVISIBLE));
277 void SearchBox::StopCapturingKeyStrokes() {
278 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
279 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_NONE));
282 void SearchBox::UndoAllMostVisitedDeletions() {
283 render_view()->Send(
284 new ChromeViewHostMsg_SearchBoxUndoAllMostVisitedDeletions(
285 render_view()->GetRoutingID(), page_seq_no_));
288 void SearchBox::UndoMostVisitedDeletion(
289 InstantRestrictedID most_visited_item_id) {
290 render_view()->Send(new ChromeViewHostMsg_SearchBoxUndoMostVisitedDeletion(
291 render_view()->GetRoutingID(), page_seq_no_,
292 GetURLForMostVisitedItem(most_visited_item_id)));
295 bool SearchBox::OnMessageReceived(const IPC::Message& message) {
296 bool handled = true;
297 IPC_BEGIN_MESSAGE_MAP(SearchBox, message)
298 IPC_MESSAGE_HANDLER(ChromeViewMsg_SetPageSequenceNumber,
299 OnSetPageSequenceNumber)
300 IPC_MESSAGE_HANDLER(ChromeViewMsg_ChromeIdentityCheckResult,
301 OnChromeIdentityCheckResult)
302 IPC_MESSAGE_HANDLER(ChromeViewMsg_DetermineIfPageSupportsInstant,
303 OnDetermineIfPageSupportsInstant)
304 IPC_MESSAGE_HANDLER(ChromeViewMsg_HistorySyncCheckResult,
305 OnHistorySyncCheckResult)
306 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFocusChanged, OnFocusChanged)
307 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMarginChange, OnMarginChange)
308 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMostVisitedItemsChanged,
309 OnMostVisitedChanged)
310 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxPromoInformation,
311 OnPromoInformationReceived)
312 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetDisplayInstantResults,
313 OnSetDisplayInstantResults)
314 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetInputInProgress,
315 OnSetInputInProgress)
316 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetSuggestionToPrefetch,
317 OnSetSuggestionToPrefetch)
318 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSubmit, OnSubmit)
319 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxThemeChanged,
320 OnThemeChanged)
321 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch,
322 OnToggleVoiceSearch)
323 IPC_MESSAGE_UNHANDLED(handled = false)
324 IPC_END_MESSAGE_MAP()
325 return handled;
328 void SearchBox::OnSetPageSequenceNumber(int page_seq_no) {
329 page_seq_no_ = page_seq_no;
332 void SearchBox::OnChromeIdentityCheckResult(const base::string16& identity,
333 bool identity_match) {
334 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
335 extensions_v8::SearchBoxExtension::DispatchChromeIdentityCheckResult(
336 render_view()->GetWebView()->mainFrame(), identity, identity_match);
340 void SearchBox::OnDetermineIfPageSupportsInstant() {
341 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
342 bool result = extensions_v8::SearchBoxExtension::PageSupportsInstant(
343 render_view()->GetWebView()->mainFrame());
344 DVLOG(1) << render_view() << " PageSupportsInstant: " << result;
345 render_view()->Send(new ChromeViewHostMsg_InstantSupportDetermined(
346 render_view()->GetRoutingID(), page_seq_no_, result));
350 void SearchBox::OnFocusChanged(OmniboxFocusState new_focus_state,
351 OmniboxFocusChangeReason reason) {
352 bool key_capture_enabled = new_focus_state == OMNIBOX_FOCUS_INVISIBLE;
353 if (key_capture_enabled != is_key_capture_enabled_) {
354 // Tell the page if the key capture mode changed unless the focus state
355 // changed because of TYPING. This is because in that case, the browser
356 // hasn't really stopped capturing key strokes.
358 // (More practically, if we don't do this check, the page would receive
359 // onkeycapturechange before the corresponding onchange, and the page would
360 // have no way of telling whether the keycapturechange happened because of
361 // some actual user action or just because they started typing.)
362 if (reason != OMNIBOX_FOCUS_CHANGE_TYPING &&
363 render_view()->GetWebView() &&
364 render_view()->GetWebView()->mainFrame()) {
365 is_key_capture_enabled_ = key_capture_enabled;
366 DVLOG(1) << render_view() << " OnKeyCaptureChange";
367 extensions_v8::SearchBoxExtension::DispatchKeyCaptureChange(
368 render_view()->GetWebView()->mainFrame());
371 bool is_focused = new_focus_state == OMNIBOX_FOCUS_VISIBLE;
372 if (is_focused != is_focused_) {
373 is_focused_ = is_focused;
374 DVLOG(1) << render_view() << " OnFocusChange";
375 if (render_view()->GetWebView() &&
376 render_view()->GetWebView()->mainFrame()) {
377 extensions_v8::SearchBoxExtension::DispatchFocusChange(
378 render_view()->GetWebView()->mainFrame());
383 void SearchBox::OnHistorySyncCheckResult(bool sync_history) {
384 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
385 extensions_v8::SearchBoxExtension::DispatchHistorySyncCheckResult(
386 render_view()->GetWebView()->mainFrame(), sync_history);
390 void SearchBox::OnMarginChange(int margin) {
391 start_margin_ = margin;
392 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
393 extensions_v8::SearchBoxExtension::DispatchMarginChange(
394 render_view()->GetWebView()->mainFrame());
398 void SearchBox::OnMostVisitedChanged(
399 const std::vector<InstantMostVisitedItem>& items) {
400 std::vector<InstantMostVisitedItemIDPair> last_known_items;
401 GetMostVisitedItems(&last_known_items);
403 if (AreMostVisitedItemsEqual(last_known_items, items))
404 return; // Do not send duplicate onmostvisitedchange events.
406 most_visited_items_cache_.AddItems(items);
407 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
408 extensions_v8::SearchBoxExtension::DispatchMostVisitedChanged(
409 render_view()->GetWebView()->mainFrame());
413 void SearchBox::OnPromoInformationReceived(bool is_app_launcher_enabled) {
414 app_launcher_enabled_ = is_app_launcher_enabled;
417 void SearchBox::OnSetDisplayInstantResults(bool display_instant_results) {
418 display_instant_results_ = display_instant_results;
421 void SearchBox::OnSetInputInProgress(bool is_input_in_progress) {
422 if (is_input_in_progress_ != is_input_in_progress) {
423 is_input_in_progress_ = is_input_in_progress;
424 DVLOG(1) << render_view() << " OnSetInputInProgress";
425 if (render_view()->GetWebView() &&
426 render_view()->GetWebView()->mainFrame()) {
427 if (is_input_in_progress_) {
428 extensions_v8::SearchBoxExtension::DispatchInputStart(
429 render_view()->GetWebView()->mainFrame());
430 } else {
431 extensions_v8::SearchBoxExtension::DispatchInputCancel(
432 render_view()->GetWebView()->mainFrame());
438 void SearchBox::OnSetSuggestionToPrefetch(const InstantSuggestion& suggestion) {
439 suggestion_ = suggestion;
440 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
441 DVLOG(1) << render_view() << " OnSetSuggestionToPrefetch";
442 extensions_v8::SearchBoxExtension::DispatchSuggestionChange(
443 render_view()->GetWebView()->mainFrame());
447 void SearchBox::OnSubmit(const base::string16& query,
448 const EmbeddedSearchRequestParams& params) {
449 query_ = query;
450 embedded_search_request_params_ = params;
451 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
452 DVLOG(1) << render_view() << " OnSubmit";
453 extensions_v8::SearchBoxExtension::DispatchSubmit(
454 render_view()->GetWebView()->mainFrame());
456 if (!query.empty())
457 Reset();
460 void SearchBox::OnThemeChanged(const ThemeBackgroundInfo& theme_info) {
461 // Do not send duplicate notifications.
462 if (theme_info_ == theme_info)
463 return;
465 theme_info_ = theme_info;
466 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
467 extensions_v8::SearchBoxExtension::DispatchThemeChange(
468 render_view()->GetWebView()->mainFrame());
472 void SearchBox::OnToggleVoiceSearch() {
473 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
474 extensions_v8::SearchBoxExtension::DispatchToggleVoiceSearch(
475 render_view()->GetWebView()->mainFrame());
479 GURL SearchBox::GetURLForMostVisitedItem(InstantRestrictedID item_id) const {
480 InstantMostVisitedItem item;
481 return GetMostVisitedItemWithID(item_id, &item) ? item.url : GURL();
484 void SearchBox::Reset() {
485 query_.clear();
486 embedded_search_request_params_ = EmbeddedSearchRequestParams();
487 suggestion_ = InstantSuggestion();
488 start_margin_ = 0;
489 is_focused_ = false;
490 is_key_capture_enabled_ = false;
491 theme_info_ = ThemeBackgroundInfo();