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"
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"
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
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())
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
) {
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)
70 if (!base::StringToInt(tokens
[0], &view_id
) || view_id
!= render_view_id
)
72 return base::StringToInt(tokens
[1], id
);
75 bool GetRestrictedIDFromFaviconUrl(int render_view_id
,
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
))
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
109 std::string id_part
= raw_path
.substr(parsed
.path_index
);
110 InstantRestrictedID id
;
111 if (!GetInstantRestrictedIDFromPath(render_view_id
, id_part
, &id
))
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
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
,
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
),
145 app_launcher_enabled_(false),
147 is_input_in_progress_(false),
148 is_key_capture_enabled_(false),
149 display_instant_results_(false),
150 most_visited_items_cache_(kMaxInstantMostVisitedItemCacheSize
),
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(),
190 GetURLForMostVisitedItem(most_visited_item_id
)));
193 bool SearchBox::GenerateFaviconURLFromTransientURL(const GURL
& transient_url
,
195 std::string favicon_params
;
196 InstantRestrictedID rid
= -1;
197 bool success
= internal::GetRestrictedIDFromFaviconUrl(
198 render_view()->GetRoutingID(), transient_url
, &favicon_params
, &rid
);
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(),
213 bool SearchBox::GenerateThumbnailURLFromTransientURL(const GURL
& transient_url
,
215 InstantRestrictedID rid
= 0;
216 if (!internal::GetRestrictedIDFromThumbnailUrl(render_view()->GetRoutingID(),
217 transient_url
, &rid
)) {
221 GURL
most_visited_item_url(GetURLForMostVisitedItem(rid
));
222 if (most_visited_item_url
.is_empty())
224 *url
= GURL(base::StringPrintf("chrome-search://thumb/%s",
225 most_visited_item_url
.spec().c_str()));
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
,
241 const ThemeBackgroundInfo
& SearchBox::GetThemeBackgroundInfo() {
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() {
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
) {
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
,
321 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch
,
323 IPC_MESSAGE_UNHANDLED(handled
= false)
324 IPC_END_MESSAGE_MAP()
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());
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
) {
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());
460 void SearchBox::OnThemeChanged(const ThemeBackgroundInfo
& theme_info
) {
461 // Do not send duplicate notifications.
462 if (theme_info_
== theme_info
)
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() {
486 embedded_search_request_params_
= EmbeddedSearchRequestParams();
487 suggestion_
= InstantSuggestion();
490 is_key_capture_enabled_
= false;
491 theme_info_
= ThemeBackgroundInfo();