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_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"
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
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())
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) {
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)
72 if (!base::StringToInt(tokens[0], &view_id) || view_id != render_view_id)
74 return base::StringToInt(tokens[1], id);
77 bool GetRestrictedIDFromFaviconUrl(int render_view_id,
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, chrome::FAVICON, &parsed))
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
111 std::string id_part = raw_path.substr(parsed.path_index);
112 InstantRestrictedID id;
113 if (!GetInstantRestrictedIDFromPath(render_view_id, id_part, &id))
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
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,
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),
148 is_input_in_progress_(false),
149 is_key_capture_enabled_(false),
150 display_instant_results_(false),
151 most_visited_items_cache_(kMaxInstantMostVisitedItemCacheSize),
157 SearchBox::~SearchBox() {
160 void SearchBox::LogEvent(NTPLoggingEventType event) {
161 render_view()->Send(new ChromeViewHostMsg_LogEvent(
162 render_view()->GetRoutingID(), render_view()->GetPageId(), event));
165 void SearchBox::CheckIsUserSignedInToChromeAs(const string16& identity) {
166 render_view()->Send(new ChromeViewHostMsg_ChromeIdentityCheck(
167 render_view()->GetRoutingID(), render_view()->GetPageId(), identity));
170 void SearchBox::DeleteMostVisitedItem(
171 InstantRestrictedID most_visited_item_id) {
172 render_view()->Send(new ChromeViewHostMsg_SearchBoxDeleteMostVisitedItem(
173 render_view()->GetRoutingID(), render_view()->GetPageId(),
174 GetURLForMostVisitedItem(most_visited_item_id)));
177 bool SearchBox::GenerateFaviconURLFromTransientURL(const GURL& transient_url,
179 std::string favicon_params;
180 InstantRestrictedID rid = -1;
181 bool success = internal::GetRestrictedIDFromFaviconUrl(
182 render_view()->GetRoutingID(), transient_url, &favicon_params, &rid);
186 InstantMostVisitedItem item;
187 std::string item_url;
188 if (rid != -1 && GetMostVisitedItemWithID(rid, &item))
189 item_url = item.url.spec();
191 *url = GURL(base::StringPrintf("chrome-search://favicon/%s%s",
192 favicon_params.c_str(),
197 bool SearchBox::GenerateThumbnailURLFromTransientURL(const GURL& transient_url,
199 InstantRestrictedID rid = 0;
200 if (!internal::GetRestrictedIDFromThumbnailUrl(render_view()->GetRoutingID(),
201 transient_url, &rid)) {
205 GURL most_visited_item_url(GetURLForMostVisitedItem(rid));
206 if (most_visited_item_url.is_empty())
208 *url = GURL(base::StringPrintf("chrome-search://thumb/%s",
209 most_visited_item_url.spec().c_str()));
213 void SearchBox::GetMostVisitedItems(
214 std::vector<InstantMostVisitedItemIDPair>* items) const {
215 return most_visited_items_cache_.GetCurrentItems(items);
218 bool SearchBox::GetMostVisitedItemWithID(
219 InstantRestrictedID most_visited_item_id,
220 InstantMostVisitedItem* item) const {
221 return most_visited_items_cache_.GetItemWithRestrictedID(most_visited_item_id,
225 const ThemeBackgroundInfo& SearchBox::GetThemeBackgroundInfo() {
229 void SearchBox::Focus() {
230 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
231 render_view()->GetRoutingID(), render_view()->GetPageId(),
232 OMNIBOX_FOCUS_VISIBLE));
235 void SearchBox::NavigateToURL(const GURL& url,
236 WindowOpenDisposition disposition,
237 bool is_most_visited_item_url) {
238 render_view()->Send(new ChromeViewHostMsg_SearchBoxNavigate(
239 render_view()->GetRoutingID(), render_view()->GetPageId(), url,
240 disposition, is_most_visited_item_url));
243 void SearchBox::Paste(const string16& text) {
244 render_view()->Send(new ChromeViewHostMsg_PasteAndOpenDropdown(
245 render_view()->GetRoutingID(), render_view()->GetPageId(), text));
248 void SearchBox::SetVoiceSearchSupported(bool supported) {
249 render_view()->Send(new ChromeViewHostMsg_SetVoiceSearchSupported(
250 render_view()->GetRoutingID(), render_view()->GetPageId(), supported));
253 void SearchBox::StartCapturingKeyStrokes() {
254 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
255 render_view()->GetRoutingID(), render_view()->GetPageId(),
256 OMNIBOX_FOCUS_INVISIBLE));
259 void SearchBox::StopCapturingKeyStrokes() {
260 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
261 render_view()->GetRoutingID(), render_view()->GetPageId(),
262 OMNIBOX_FOCUS_NONE));
265 void SearchBox::UndoAllMostVisitedDeletions() {
267 new ChromeViewHostMsg_SearchBoxUndoAllMostVisitedDeletions(
268 render_view()->GetRoutingID(), render_view()->GetPageId()));
271 void SearchBox::UndoMostVisitedDeletion(
272 InstantRestrictedID most_visited_item_id) {
273 render_view()->Send(new ChromeViewHostMsg_SearchBoxUndoMostVisitedDeletion(
274 render_view()->GetRoutingID(), render_view()->GetPageId(),
275 GetURLForMostVisitedItem(most_visited_item_id)));
278 bool SearchBox::OnMessageReceived(const IPC::Message& message) {
280 IPC_BEGIN_MESSAGE_MAP(SearchBox, message)
281 IPC_MESSAGE_HANDLER(ChromeViewMsg_ChromeIdentityCheckResult,
282 OnChromeIdentityCheckResult)
283 IPC_MESSAGE_HANDLER(ChromeViewMsg_DetermineIfPageSupportsInstant,
284 OnDetermineIfPageSupportsInstant)
285 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFocusChanged, OnFocusChanged)
286 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMarginChange, OnMarginChange)
287 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMostVisitedItemsChanged,
288 OnMostVisitedChanged)
289 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxPromoInformation,
290 OnPromoInformationReceived)
291 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetDisplayInstantResults,
292 OnSetDisplayInstantResults)
293 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetInputInProgress,
294 OnSetInputInProgress)
295 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetSuggestionToPrefetch,
296 OnSetSuggestionToPrefetch)
297 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSubmit, OnSubmit)
298 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxThemeChanged,
300 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch,
302 IPC_MESSAGE_UNHANDLED(handled = false)
303 IPC_END_MESSAGE_MAP()
307 void SearchBox::OnChromeIdentityCheckResult(const string16& identity,
308 bool identity_match) {
309 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
310 extensions_v8::SearchBoxExtension::DispatchChromeIdentityCheckResult(
311 render_view()->GetWebView()->mainFrame(), identity, identity_match);
315 void SearchBox::OnDetermineIfPageSupportsInstant() {
316 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
317 bool result = extensions_v8::SearchBoxExtension::PageSupportsInstant(
318 render_view()->GetWebView()->mainFrame());
319 DVLOG(1) << render_view() << " PageSupportsInstant: " << result;
320 render_view()->Send(new ChromeViewHostMsg_InstantSupportDetermined(
321 render_view()->GetRoutingID(), render_view()->GetPageId(), result));
325 void SearchBox::OnFocusChanged(OmniboxFocusState new_focus_state,
326 OmniboxFocusChangeReason reason) {
327 bool key_capture_enabled = new_focus_state == OMNIBOX_FOCUS_INVISIBLE;
328 if (key_capture_enabled != is_key_capture_enabled_) {
329 // Tell the page if the key capture mode changed unless the focus state
330 // changed because of TYPING. This is because in that case, the browser
331 // hasn't really stopped capturing key strokes.
333 // (More practically, if we don't do this check, the page would receive
334 // onkeycapturechange before the corresponding onchange, and the page would
335 // have no way of telling whether the keycapturechange happened because of
336 // some actual user action or just because they started typing.)
337 if (reason != OMNIBOX_FOCUS_CHANGE_TYPING &&
338 render_view()->GetWebView() &&
339 render_view()->GetWebView()->mainFrame()) {
340 is_key_capture_enabled_ = key_capture_enabled;
341 DVLOG(1) << render_view() << " OnKeyCaptureChange";
342 extensions_v8::SearchBoxExtension::DispatchKeyCaptureChange(
343 render_view()->GetWebView()->mainFrame());
346 bool is_focused = new_focus_state == OMNIBOX_FOCUS_VISIBLE;
347 if (is_focused != is_focused_) {
348 is_focused_ = is_focused;
349 DVLOG(1) << render_view() << " OnFocusChange";
350 if (render_view()->GetWebView() &&
351 render_view()->GetWebView()->mainFrame()) {
352 extensions_v8::SearchBoxExtension::DispatchFocusChange(
353 render_view()->GetWebView()->mainFrame());
358 void SearchBox::OnMarginChange(int margin, int width) {
359 start_margin_ = margin;
361 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
362 extensions_v8::SearchBoxExtension::DispatchMarginChange(
363 render_view()->GetWebView()->mainFrame());
367 void SearchBox::OnMostVisitedChanged(
368 const std::vector<InstantMostVisitedItem>& items) {
369 std::vector<InstantMostVisitedItemIDPair> last_known_items;
370 GetMostVisitedItems(&last_known_items);
372 if (AreMostVisitedItemsEqual(last_known_items, items))
373 return; // Do not send duplicate onmostvisitedchange events.
375 most_visited_items_cache_.AddItems(items);
376 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
377 extensions_v8::SearchBoxExtension::DispatchMostVisitedChanged(
378 render_view()->GetWebView()->mainFrame());
382 void SearchBox::OnPromoInformationReceived(bool is_app_launcher_enabled) {
383 app_launcher_enabled_ = is_app_launcher_enabled;
386 void SearchBox::OnSetDisplayInstantResults(bool display_instant_results) {
387 display_instant_results_ = display_instant_results;
390 void SearchBox::OnSetInputInProgress(bool is_input_in_progress) {
391 if (is_input_in_progress_ != is_input_in_progress) {
392 is_input_in_progress_ = is_input_in_progress;
393 DVLOG(1) << render_view() << " OnSetInputInProgress";
394 if (render_view()->GetWebView() &&
395 render_view()->GetWebView()->mainFrame()) {
396 if (is_input_in_progress_) {
397 extensions_v8::SearchBoxExtension::DispatchInputStart(
398 render_view()->GetWebView()->mainFrame());
400 extensions_v8::SearchBoxExtension::DispatchInputCancel(
401 render_view()->GetWebView()->mainFrame());
407 void SearchBox::OnSetSuggestionToPrefetch(const InstantSuggestion& suggestion) {
408 suggestion_ = suggestion;
409 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
410 DVLOG(1) << render_view() << " OnSetSuggestionToPrefetch";
411 extensions_v8::SearchBoxExtension::DispatchSuggestionChange(
412 render_view()->GetWebView()->mainFrame());
416 void SearchBox::OnSubmit(const string16& query) {
418 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
419 DVLOG(1) << render_view() << " OnSubmit";
420 extensions_v8::SearchBoxExtension::DispatchSubmit(
421 render_view()->GetWebView()->mainFrame());
427 void SearchBox::OnThemeChanged(const ThemeBackgroundInfo& theme_info) {
428 // Do not send duplicate notifications.
429 if (theme_info_ == theme_info)
432 theme_info_ = theme_info;
433 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
434 extensions_v8::SearchBoxExtension::DispatchThemeChange(
435 render_view()->GetWebView()->mainFrame());
439 void SearchBox::OnToggleVoiceSearch() {
440 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
441 extensions_v8::SearchBoxExtension::DispatchToggleVoiceSearch(
442 render_view()->GetWebView()->mainFrame());
446 GURL SearchBox::GetURLForMostVisitedItem(InstantRestrictedID item_id) const {
447 InstantMostVisitedItem item;
448 return GetMostVisitedItemWithID(item_id, &item) ? item.url : GURL();
451 void SearchBox::Reset() {
453 suggestion_ = InstantSuggestion();
457 is_key_capture_enabled_ = false;
458 theme_info_ = ThemeBackgroundInfo();