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.
4
5 #include "chrome/renderer/searchbox/searchbox.h"
6
7 #include <string>
8
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"
27
28 namespace {
29
30 // The size of the InstantMostVisitedItem cache.
31 const size_t kMaxInstantMostVisitedItemCacheSize = 100;
32
33 // Returns true if items stored in |old_item_id_pairs| and |new_items| are
34 // equal.
AreMostVisitedItemsEqual(const std::vector<InstantMostVisitedItemIDPair> & old_item_id_pairs,const std::vector<InstantMostVisitedItem> & new_items)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;
40
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;
45 }
46 }
47 return true;
48 }
49
50 } // namespace
51
52 namespace internal { // for testing
53
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.
56 //
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>
60 //
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.
GetInstantRestrictedIDFromPath(int render_view_id,const std::string & path,InstantRestrictedID * id)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;
70
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);
75 }
76
GetRestrictedIDFromFaviconUrl(int render_view_id,const GURL & url,std::string * favicon_params,InstantRestrictedID * rid)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);
86
87 chrome::ParsedFaviconPath parsed;
88 if (!chrome::ParseFaviconPath(raw_path, favicon_base::FAVICON, &parsed))
89 return false;
90
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);
95
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;
115
116 *rid = id;
117 return true;
118 }
119
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.
123 //
124 // Valid |url| forms:
125 // chrome-search://thumb/<view_id>/<restricted_id>
126 //
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.
GetRestrictedIDFromThumbnailUrl(int render_view_id,const GURL & url,InstantRestrictedID * id)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);
137
138 return GetInstantRestrictedIDFromPath(render_view_id, path, id);
139 }
140
141 } // namespace internal
142
SearchBox(content::RenderView * render_view)143 SearchBox::SearchBox(content::RenderView* render_view)
144 : content::RenderViewObserver(render_view),
145 content::RenderViewObserverTracker<SearchBox>(render_view),
146 page_seq_no_(0),
147 app_launcher_enabled_(false),
148 is_focused_(false),
149 is_input_in_progress_(false),
150 is_key_capture_enabled_(false),
151 display_instant_results_(false),
152 most_visited_items_cache_(kMaxInstantMostVisitedItemCacheSize),
153 query_(),
154 start_margin_(0) {
155 }
156
~SearchBox()157 SearchBox::~SearchBox() {
158 }
159
LogEvent(NTPLoggingEventType event)160 void SearchBox::LogEvent(NTPLoggingEventType event) {
161 render_view()->Send(new ChromeViewHostMsg_LogEvent(
162 render_view()->GetRoutingID(), page_seq_no_, event));
163 }
164
LogMostVisitedImpression(int position,const base::string16 & provider)165 void SearchBox::LogMostVisitedImpression(int position,
166 const base::string16& provider) {
167 render_view()->Send(new ChromeViewHostMsg_LogMostVisitedImpression(
168 render_view()->GetRoutingID(), page_seq_no_, position, provider));
169 }
170
LogMostVisitedNavigation(int position,const base::string16 & provider)171 void SearchBox::LogMostVisitedNavigation(int position,
172 const base::string16& provider) {
173 render_view()->Send(new ChromeViewHostMsg_LogMostVisitedNavigation(
174 render_view()->GetRoutingID(), page_seq_no_, position, provider));
175 }
176
CheckIsUserSignedInToChromeAs(const base::string16 & identity)177 void SearchBox::CheckIsUserSignedInToChromeAs(const base::string16& identity) {
178 render_view()->Send(new ChromeViewHostMsg_ChromeIdentityCheck(
179 render_view()->GetRoutingID(), page_seq_no_, identity));
180 }
181
DeleteMostVisitedItem(InstantRestrictedID most_visited_item_id)182 void SearchBox::DeleteMostVisitedItem(
183 InstantRestrictedID most_visited_item_id) {
184 render_view()->Send(new ChromeViewHostMsg_SearchBoxDeleteMostVisitedItem(
185 render_view()->GetRoutingID(),
186 page_seq_no_,
187 GetURLForMostVisitedItem(most_visited_item_id)));
188 }
189
GenerateFaviconURLFromTransientURL(const GURL & transient_url,GURL * url) const190 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;
198
199 InstantMostVisitedItem item;
200 std::string item_url;
201 if (rid != -1 && GetMostVisitedItemWithID(rid, &item))
202 item_url = item.url.spec();
203
204 *url = GURL(base::StringPrintf("chrome-search://favicon/%s%s",
205 favicon_params.c_str(),
206 item_url.c_str()));
207 return true;
208 }
209
GenerateThumbnailURLFromTransientURL(const GURL & transient_url,GURL * url) const210 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;
216 }
217
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;
224 }
225
GetMostVisitedItems(std::vector<InstantMostVisitedItemIDPair> * items) const226 void SearchBox::GetMostVisitedItems(
227 std::vector<InstantMostVisitedItemIDPair>* items) const {
228 return most_visited_items_cache_.GetCurrentItems(items);
229 }
230
GetMostVisitedItemWithID(InstantRestrictedID most_visited_item_id,InstantMostVisitedItem * item) const231 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);
236 }
237
GetThemeBackgroundInfo()238 const ThemeBackgroundInfo& SearchBox::GetThemeBackgroundInfo() {
239 return theme_info_;
240 }
241
Focus()242 void SearchBox::Focus() {
243 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
244 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_VISIBLE));
245 }
246
NavigateToURL(const GURL & url,WindowOpenDisposition disposition,bool is_most_visited_item_url)247 void SearchBox::NavigateToURL(const GURL& url,
248 WindowOpenDisposition disposition,
249 bool is_most_visited_item_url) {
250 render_view()->Send(new ChromeViewHostMsg_SearchBoxNavigate(
251 render_view()->GetRoutingID(), page_seq_no_, url,
252 disposition, is_most_visited_item_url));
253 }
254
Paste(const base::string16 & text)255 void SearchBox::Paste(const base::string16& text) {
256 render_view()->Send(new ChromeViewHostMsg_PasteAndOpenDropdown(
257 render_view()->GetRoutingID(), page_seq_no_, text));
258 }
259
SetVoiceSearchSupported(bool supported)260 void SearchBox::SetVoiceSearchSupported(bool supported) {
261 render_view()->Send(new ChromeViewHostMsg_SetVoiceSearchSupported(
262 render_view()->GetRoutingID(), page_seq_no_, supported));
263 }
264
StartCapturingKeyStrokes()265 void SearchBox::StartCapturingKeyStrokes() {
266 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
267 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_INVISIBLE));
268 }
269
StopCapturingKeyStrokes()270 void SearchBox::StopCapturingKeyStrokes() {
271 render_view()->Send(new ChromeViewHostMsg_FocusOmnibox(
272 render_view()->GetRoutingID(), page_seq_no_, OMNIBOX_FOCUS_NONE));
273 }
274
UndoAllMostVisitedDeletions()275 void SearchBox::UndoAllMostVisitedDeletions() {
276 render_view()->Send(
277 new ChromeViewHostMsg_SearchBoxUndoAllMostVisitedDeletions(
278 render_view()->GetRoutingID(), page_seq_no_));
279 }
280
UndoMostVisitedDeletion(InstantRestrictedID most_visited_item_id)281 void SearchBox::UndoMostVisitedDeletion(
282 InstantRestrictedID most_visited_item_id) {
283 render_view()->Send(new ChromeViewHostMsg_SearchBoxUndoMostVisitedDeletion(
284 render_view()->GetRoutingID(), page_seq_no_,
285 GetURLForMostVisitedItem(most_visited_item_id)));
286 }
287
OnMessageReceived(const IPC::Message & message)288 bool SearchBox::OnMessageReceived(const IPC::Message& message) {
289 bool handled = true;
290 IPC_BEGIN_MESSAGE_MAP(SearchBox, message)
291 IPC_MESSAGE_HANDLER(ChromeViewMsg_SetPageSequenceNumber,
292 OnSetPageSequenceNumber)
293 IPC_MESSAGE_HANDLER(ChromeViewMsg_ChromeIdentityCheckResult,
294 OnChromeIdentityCheckResult)
295 IPC_MESSAGE_HANDLER(ChromeViewMsg_DetermineIfPageSupportsInstant,
296 OnDetermineIfPageSupportsInstant)
297 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxFocusChanged, OnFocusChanged)
298 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMarginChange, OnMarginChange)
299 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxMostVisitedItemsChanged,
300 OnMostVisitedChanged)
301 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxPromoInformation,
302 OnPromoInformationReceived)
303 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetDisplayInstantResults,
304 OnSetDisplayInstantResults)
305 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetInputInProgress,
306 OnSetInputInProgress)
307 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSetSuggestionToPrefetch,
308 OnSetSuggestionToPrefetch)
309 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxSubmit, OnSubmit)
310 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxThemeChanged,
311 OnThemeChanged)
312 IPC_MESSAGE_HANDLER(ChromeViewMsg_SearchBoxToggleVoiceSearch,
313 OnToggleVoiceSearch)
314 IPC_MESSAGE_UNHANDLED(handled = false)
315 IPC_END_MESSAGE_MAP()
316 return handled;
317 }
318
OnSetPageSequenceNumber(int page_seq_no)319 void SearchBox::OnSetPageSequenceNumber(int page_seq_no) {
320 page_seq_no_ = page_seq_no;
321 }
322
OnChromeIdentityCheckResult(const base::string16 & identity,bool identity_match)323 void SearchBox::OnChromeIdentityCheckResult(const base::string16& identity,
324 bool identity_match) {
325 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
326 extensions_v8::SearchBoxExtension::DispatchChromeIdentityCheckResult(
327 render_view()->GetWebView()->mainFrame(), identity, identity_match);
328 }
329 }
330
OnDetermineIfPageSupportsInstant()331 void SearchBox::OnDetermineIfPageSupportsInstant() {
332 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
333 bool result = extensions_v8::SearchBoxExtension::PageSupportsInstant(
334 render_view()->GetWebView()->mainFrame());
335 DVLOG(1) << render_view() << " PageSupportsInstant: " << result;
336 render_view()->Send(new ChromeViewHostMsg_InstantSupportDetermined(
337 render_view()->GetRoutingID(), page_seq_no_, result));
338 }
339 }
340
OnFocusChanged(OmniboxFocusState new_focus_state,OmniboxFocusChangeReason reason)341 void SearchBox::OnFocusChanged(OmniboxFocusState new_focus_state,
342 OmniboxFocusChangeReason reason) {
343 bool key_capture_enabled = new_focus_state == OMNIBOX_FOCUS_INVISIBLE;
344 if (key_capture_enabled != is_key_capture_enabled_) {
345 // Tell the page if the key capture mode changed unless the focus state
346 // changed because of TYPING. This is because in that case, the browser
347 // hasn't really stopped capturing key strokes.
348 //
349 // (More practically, if we don't do this check, the page would receive
350 // onkeycapturechange before the corresponding onchange, and the page would
351 // have no way of telling whether the keycapturechange happened because of
352 // some actual user action or just because they started typing.)
353 if (reason != OMNIBOX_FOCUS_CHANGE_TYPING &&
354 render_view()->GetWebView() &&
355 render_view()->GetWebView()->mainFrame()) {
356 is_key_capture_enabled_ = key_capture_enabled;
357 DVLOG(1) << render_view() << " OnKeyCaptureChange";
358 extensions_v8::SearchBoxExtension::DispatchKeyCaptureChange(
359 render_view()->GetWebView()->mainFrame());
360 }
361 }
362 bool is_focused = new_focus_state == OMNIBOX_FOCUS_VISIBLE;
363 if (is_focused != is_focused_) {
364 is_focused_ = is_focused;
365 DVLOG(1) << render_view() << " OnFocusChange";
366 if (render_view()->GetWebView() &&
367 render_view()->GetWebView()->mainFrame()) {
368 extensions_v8::SearchBoxExtension::DispatchFocusChange(
369 render_view()->GetWebView()->mainFrame());
370 }
371 }
372 }
373
OnMarginChange(int margin)374 void SearchBox::OnMarginChange(int margin) {
375 start_margin_ = margin;
376 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
377 extensions_v8::SearchBoxExtension::DispatchMarginChange(
378 render_view()->GetWebView()->mainFrame());
379 }
380 }
381
OnMostVisitedChanged(const std::vector<InstantMostVisitedItem> & items)382 void SearchBox::OnMostVisitedChanged(
383 const std::vector<InstantMostVisitedItem>& items) {
384 std::vector<InstantMostVisitedItemIDPair> last_known_items;
385 GetMostVisitedItems(&last_known_items);
386
387 if (AreMostVisitedItemsEqual(last_known_items, items))
388 return; // Do not send duplicate onmostvisitedchange events.
389
390 most_visited_items_cache_.AddItems(items);
391 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
392 extensions_v8::SearchBoxExtension::DispatchMostVisitedChanged(
393 render_view()->GetWebView()->mainFrame());
394 }
395 }
396
OnPromoInformationReceived(bool is_app_launcher_enabled)397 void SearchBox::OnPromoInformationReceived(bool is_app_launcher_enabled) {
398 app_launcher_enabled_ = is_app_launcher_enabled;
399 }
400
OnSetDisplayInstantResults(bool display_instant_results)401 void SearchBox::OnSetDisplayInstantResults(bool display_instant_results) {
402 display_instant_results_ = display_instant_results;
403 }
404
OnSetInputInProgress(bool is_input_in_progress)405 void SearchBox::OnSetInputInProgress(bool is_input_in_progress) {
406 if (is_input_in_progress_ != is_input_in_progress) {
407 is_input_in_progress_ = is_input_in_progress;
408 DVLOG(1) << render_view() << " OnSetInputInProgress";
409 if (render_view()->GetWebView() &&
410 render_view()->GetWebView()->mainFrame()) {
411 if (is_input_in_progress_) {
412 extensions_v8::SearchBoxExtension::DispatchInputStart(
413 render_view()->GetWebView()->mainFrame());
414 } else {
415 extensions_v8::SearchBoxExtension::DispatchInputCancel(
416 render_view()->GetWebView()->mainFrame());
417 }
418 }
419 }
420 }
421
OnSetSuggestionToPrefetch(const InstantSuggestion & suggestion)422 void SearchBox::OnSetSuggestionToPrefetch(const InstantSuggestion& suggestion) {
423 suggestion_ = suggestion;
424 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
425 DVLOG(1) << render_view() << " OnSetSuggestionToPrefetch";
426 extensions_v8::SearchBoxExtension::DispatchSuggestionChange(
427 render_view()->GetWebView()->mainFrame());
428 }
429 }
430
OnSubmit(const base::string16 & query)431 void SearchBox::OnSubmit(const base::string16& query) {
432 query_ = query;
433 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
434 DVLOG(1) << render_view() << " OnSubmit";
435 extensions_v8::SearchBoxExtension::DispatchSubmit(
436 render_view()->GetWebView()->mainFrame());
437 }
438 if (!query.empty())
439 Reset();
440 }
441
OnThemeChanged(const ThemeBackgroundInfo & theme_info)442 void SearchBox::OnThemeChanged(const ThemeBackgroundInfo& theme_info) {
443 // Do not send duplicate notifications.
444 if (theme_info_ == theme_info)
445 return;
446
447 theme_info_ = theme_info;
448 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
449 extensions_v8::SearchBoxExtension::DispatchThemeChange(
450 render_view()->GetWebView()->mainFrame());
451 }
452 }
453
OnToggleVoiceSearch()454 void SearchBox::OnToggleVoiceSearch() {
455 if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) {
456 extensions_v8::SearchBoxExtension::DispatchToggleVoiceSearch(
457 render_view()->GetWebView()->mainFrame());
458 }
459 }
460
GetURLForMostVisitedItem(InstantRestrictedID item_id) const461 GURL SearchBox::GetURLForMostVisitedItem(InstantRestrictedID item_id) const {
462 InstantMostVisitedItem item;
463 return GetMostVisitedItemWithID(item_id, &item) ? item.url : GURL();
464 }
465
Reset()466 void SearchBox::Reset() {
467 query_.clear();
468 suggestion_ = InstantSuggestion();
469 start_margin_ = 0;
470 is_focused_ = false;
471 is_key_capture_enabled_ = false;
472 theme_info_ = ThemeBackgroundInfo();
473 }
474