Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(192)

Side by Side Diff: chrome/browser/ui/search/instant_controller.cc

Issue 18223002: InstantExtended: Remove overlay control code. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase. Created 7 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/ui/search/instant_controller.h" 5 #include "chrome/browser/ui/search/instant_controller.h"
6 6
7 #include <iterator>
8
9 #include "base/metrics/histogram.h" 7 #include "base/metrics/histogram.h"
10 #include "base/prefs/pref_service.h" 8 #include "base/prefs/pref_service.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/stringprintf.h" 9 #include "base/strings/stringprintf.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/autocomplete/autocomplete_provider.h"
15 #include "chrome/browser/autocomplete/autocomplete_result.h"
16 #include "chrome/browser/autocomplete/search_provider.h"
17 #include "chrome/browser/content_settings/content_settings_provider.h" 10 #include "chrome/browser/content_settings/content_settings_provider.h"
18 #include "chrome/browser/content_settings/host_content_settings_map.h" 11 #include "chrome/browser/content_settings/host_content_settings_map.h"
19 #include "chrome/browser/history/history_service.h"
20 #include "chrome/browser/history/history_service_factory.h"
21 #include "chrome/browser/history/history_tab_helper.h"
22 #include "chrome/browser/platform_util.h" 12 #include "chrome/browser/platform_util.h"
13 #include "chrome/browser/profiles/profile.h"
23 #include "chrome/browser/search/instant_service.h" 14 #include "chrome/browser/search/instant_service.h"
24 #include "chrome/browser/search/instant_service_factory.h" 15 #include "chrome/browser/search/instant_service_factory.h"
25 #include "chrome/browser/search/search.h" 16 #include "chrome/browser/search/search.h"
26 #include "chrome/browser/search_engines/search_terms_data.h" 17 #include "chrome/browser/search_engines/search_terms_data.h"
27 #include "chrome/browser/search_engines/template_url_service.h" 18 #include "chrome/browser/search_engines/template_url_service.h"
28 #include "chrome/browser/search_engines/template_url_service_factory.h" 19 #include "chrome/browser/search_engines/template_url_service_factory.h"
29 #include "chrome/browser/ui/browser_instant_controller.h" 20 #include "chrome/browser/ui/browser_instant_controller.h"
30 #include "chrome/browser/ui/search/instant_ntp.h" 21 #include "chrome/browser/ui/search/instant_ntp.h"
31 #include "chrome/browser/ui/search/instant_overlay.h"
32 #include "chrome/browser/ui/search/instant_tab.h" 22 #include "chrome/browser/ui/search/instant_tab.h"
33 #include "chrome/browser/ui/search/search_tab_helper.h" 23 #include "chrome/browser/ui/search/search_tab_helper.h"
34 #include "chrome/common/chrome_notification_types.h" 24 #include "chrome/common/chrome_notification_types.h"
35 #include "chrome/common/chrome_switches.h" 25 #include "chrome/common/chrome_switches.h"
36 #include "chrome/common/content_settings_types.h" 26 #include "chrome/common/content_settings_types.h"
37 #include "chrome/common/pref_names.h" 27 #include "chrome/common/pref_names.h"
38 #include "chrome/common/url_constants.h" 28 #include "chrome/common/url_constants.h"
39 #include "components/sessions/serialized_navigation_entry.h" 29 #include "components/sessions/serialized_navigation_entry.h"
40 #include "content/public/browser/navigation_entry.h" 30 #include "content/public/browser/navigation_entry.h"
41 #include "content/public/browser/notification_service.h" 31 #include "content/public/browser/notification_service.h"
42 #include "content/public/browser/render_process_host.h" 32 #include "content/public/browser/render_process_host.h"
43 #include "content/public/browser/render_widget_host_view.h" 33 #include "content/public/browser/render_widget_host_view.h"
44 #include "content/public/browser/user_metrics.h" 34 #include "content/public/browser/user_metrics.h"
45 #include "content/public/browser/web_contents.h" 35 #include "content/public/browser/web_contents.h"
46 #include "content/public/browser/web_contents_view.h" 36 #include "content/public/browser/web_contents_view.h"
47 #include "net/base/escape.h" 37 #include "net/base/escape.h"
48 #include "net/base/network_change_notifier.h" 38 #include "net/base/network_change_notifier.h"
49 #include "third_party/icu/public/common/unicode/normalizer2.h"
50 39
51 #if defined(TOOLKIT_VIEWS) 40 #if defined(TOOLKIT_VIEWS)
52 #include "ui/views/widget/widget.h" 41 #include "ui/views/widget/widget.h"
53 #endif 42 #endif
54 43
55 namespace { 44 namespace {
56 45
57 // An artificial delay (in milliseconds) we introduce before telling the Instant
58 // page about the new omnibox bounds, in cases where the bounds shrink. This is
59 // to avoid the page jumping up/down very fast in response to bounds changes.
60 const int kUpdateBoundsDelayMS = 1000;
61
62 // For reporting Instant navigations. 46 // For reporting Instant navigations.
63 enum InstantNavigation { 47 enum InstantNavigation {
64 INSTANT_NAVIGATION_LOCAL_CLICK = 0, 48 INSTANT_NAVIGATION_LOCAL_CLICK = 0,
65 INSTANT_NAVIGATION_LOCAL_SUBMIT = 1, 49 INSTANT_NAVIGATION_LOCAL_SUBMIT = 1,
66 INSTANT_NAVIGATION_ONLINE_CLICK = 2, 50 INSTANT_NAVIGATION_ONLINE_CLICK = 2,
67 INSTANT_NAVIGATION_ONLINE_SUBMIT = 3, 51 INSTANT_NAVIGATION_ONLINE_SUBMIT = 3,
68 INSTANT_NAVIGATION_NONEXTENDED = 4, 52 INSTANT_NAVIGATION_NONEXTENDED = 4,
69 INSTANT_NAVIGATION_MAX = 5 53 INSTANT_NAVIGATION_MAX = 5
70 }; 54 };
71 55
72 void RecordNavigationHistogram(bool is_local, bool is_click, bool is_extended) { 56 void RecordNavigationHistogram(bool is_local, bool is_click, bool is_extended) {
73 InstantNavigation navigation; 57 InstantNavigation navigation;
74 if (!is_extended) { 58 if (!is_extended) {
75 navigation = INSTANT_NAVIGATION_NONEXTENDED; 59 navigation = INSTANT_NAVIGATION_NONEXTENDED;
76 } else if (is_local) { 60 } else if (is_local) {
77 navigation = is_click ? INSTANT_NAVIGATION_LOCAL_CLICK : 61 navigation = is_click ? INSTANT_NAVIGATION_LOCAL_CLICK :
78 INSTANT_NAVIGATION_LOCAL_SUBMIT; 62 INSTANT_NAVIGATION_LOCAL_SUBMIT;
79 } else { 63 } else {
80 navigation = is_click ? INSTANT_NAVIGATION_ONLINE_CLICK : 64 navigation = is_click ? INSTANT_NAVIGATION_ONLINE_CLICK :
81 INSTANT_NAVIGATION_ONLINE_SUBMIT; 65 INSTANT_NAVIGATION_ONLINE_SUBMIT;
82 } 66 }
83 UMA_HISTOGRAM_ENUMERATION("InstantExtended.InstantNavigation", 67 UMA_HISTOGRAM_ENUMERATION("InstantExtended.InstantNavigation",
84 navigation, 68 navigation,
85 INSTANT_NAVIGATION_MAX); 69 INSTANT_NAVIGATION_MAX);
86 } 70 }
87 71
88 void RecordFallbackReasonHistogram(
89 const InstantController::InstantFallbackReason fallback_reason) {
90 UMA_HISTOGRAM_ENUMERATION("InstantExtended.FallbackToLocalOverlay",
91 fallback_reason,
92 InstantController::INSTANT_FALLBACK_MAX);
93 }
94
95 InstantController::InstantFallbackReason DetermineFallbackReason(
96 const InstantPage* page, std::string instant_url) {
97 InstantController::InstantFallbackReason fallback_reason;
98 if (!page) {
99 fallback_reason = InstantController::INSTANT_FALLBACK_NO_OVERLAY;
100 } else if (instant_url.empty()) {
101 fallback_reason = InstantController::INSTANT_FALLBACK_INSTANT_URL_EMPTY;
102 } else if (!chrome::MatchesOriginAndPath(GURL(page->instant_url()),
103 GURL(instant_url))) {
104 fallback_reason = InstantController::INSTANT_FALLBACK_ORIGIN_PATH_MISMATCH;
105 } else if (!page->supports_instant()) {
106 fallback_reason = InstantController::INSTANT_FALLBACK_INSTANT_NOT_SUPPORTED;
107 } else {
108 fallback_reason = InstantController::INSTANT_FALLBACK_UNKNOWN;
109 }
110 return fallback_reason;
111 }
112
113 void AddSessionStorageHistogram(bool extended_enabled,
114 const content::WebContents* tab1,
115 const content::WebContents* tab2) {
116 base::HistogramBase* histogram = base::BooleanHistogram::FactoryGet(
117 std::string("Instant.SessionStorageNamespace") +
118 (extended_enabled ? "_Extended" : "_Instant"),
119 base::HistogramBase::kUmaTargetedHistogramFlag);
120 const content::SessionStorageNamespaceMap& session_storage_map1 =
121 tab1->GetController().GetSessionStorageNamespaceMap();
122 const content::SessionStorageNamespaceMap& session_storage_map2 =
123 tab2->GetController().GetSessionStorageNamespaceMap();
124 bool is_session_storage_the_same =
125 session_storage_map1.size() == session_storage_map2.size();
126 if (is_session_storage_the_same) {
127 // The size is the same, so let's check that all entries match.
128 for (content::SessionStorageNamespaceMap::const_iterator
129 it1 = session_storage_map1.begin(),
130 it2 = session_storage_map2.begin();
131 it1 != session_storage_map1.end() && it2 != session_storage_map2.end();
132 ++it1, ++it2) {
133 if (it1->first != it2->first || it1->second.get() != it2->second.get()) {
134 is_session_storage_the_same = false;
135 break;
136 }
137 }
138 }
139 histogram->AddBoolean(is_session_storage_the_same);
140 }
141
142 string16 Normalize(const string16& str) {
143 UErrorCode status = U_ZERO_ERROR;
144 const icu::Normalizer2* normalizer =
145 icu::Normalizer2::getInstance(NULL, "nfkc_cf", UNORM2_COMPOSE, status);
146 if (normalizer == NULL || U_FAILURE(status))
147 return str;
148 icu::UnicodeString norm_str(normalizer->normalize(
149 icu::UnicodeString(FALSE, str.c_str(), str.size()), status));
150 if (U_FAILURE(status))
151 return str;
152 return string16(norm_str.getBuffer(), norm_str.length());
153 }
154
155 bool NormalizeAndStripPrefix(string16* text, const string16& prefix) {
156 string16 norm_prefix = Normalize(prefix);
157 string16 norm_text = Normalize(*text);
158 if (norm_prefix.size() <= norm_text.size() &&
159 norm_text.compare(0, norm_prefix.size(), norm_prefix) == 0) {
160 *text = norm_text.erase(0, norm_prefix.size());
161 return true;
162 }
163 return false;
164 }
165
166 // For TOOLKIT_VIEWS, the top level widget is always focused. If the focus
167 // change originated in views determine the child Widget from the view that is
168 // being focused.
169 gfx::NativeView GetViewGainingFocus(gfx::NativeView view_gaining_focus) {
170 #if defined(TOOLKIT_VIEWS)
171 views::Widget* widget = view_gaining_focus ?
172 views::Widget::GetWidgetForNativeView(view_gaining_focus) : NULL;
173 if (widget) {
174 views::FocusManager* focus_manager = widget->GetFocusManager();
175 if (focus_manager && focus_manager->is_changing_focus() &&
176 focus_manager->GetFocusedView() &&
177 focus_manager->GetFocusedView()->GetWidget())
178 return focus_manager->GetFocusedView()->GetWidget()->GetNativeView();
179 }
180 #endif
181 return view_gaining_focus;
182 }
183
184 // Returns true if |view| is the top-level contents view or a child view in the
185 // view hierarchy of |contents|.
186 bool IsViewInContents(gfx::NativeView view, content::WebContents* contents) {
187 content::RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView();
188 if (!view || !rwhv)
189 return false;
190
191 gfx::NativeView tab_view = contents->GetView()->GetNativeView();
192 if (view == rwhv->GetNativeView() || view == tab_view)
193 return true;
194
195 // Walk up the view hierarchy to determine if the view is a subview of the
196 // WebContents view (such as a windowed plugin or http auth dialog).
197 while (view) {
198 view = platform_util::GetParent(view);
199 if (view == tab_view)
200 return true;
201 }
202
203 return false;
204 }
205
206 bool IsFullHeight(const InstantOverlayModel& model) {
207 return model.height() == 100 && model.height_units() == INSTANT_SIZE_PERCENT;
208 }
209
210 bool IsContentsFrom(const InstantPage* page, 72 bool IsContentsFrom(const InstantPage* page,
211 const content::WebContents* contents) { 73 const content::WebContents* contents) {
212 return page && (page->contents() == contents); 74 return page && (page->contents() == contents);
213 } 75 }
214 76
215 // Adds a transient NavigationEntry to the supplied |contents|'s 77 // Adds a transient NavigationEntry to the supplied |contents|'s
216 // NavigationController if the page's URL has not already been updated with the 78 // NavigationController if the page's URL has not already been updated with the
217 // supplied |search_terms|. Sets the |search_terms| on the transient entry for 79 // supplied |search_terms|. Sets the |search_terms| on the transient entry for
218 // search terms extraction to work correctly. 80 // search terms extraction to work correctly.
219 void EnsureSearchTermsAreSet(content::WebContents* contents, 81 void EnsureSearchTermsAreSet(content::WebContents* contents,
(...skipping 29 matching lines...) Expand all
249 111
250 base::MessageLoop::current()->DeleteSoon(FROM_HERE, page.release()); 112 base::MessageLoop::current()->DeleteSoon(FROM_HERE, page.release());
251 } 113 }
252 114
253 } // namespace 115 } // namespace
254 116
255 InstantController::InstantController(BrowserInstantController* browser, 117 InstantController::InstantController(BrowserInstantController* browser,
256 bool extended_enabled) 118 bool extended_enabled)
257 : browser_(browser), 119 : browser_(browser),
258 extended_enabled_(extended_enabled), 120 extended_enabled_(extended_enabled),
259 instant_enabled_(false),
260 use_local_page_only_(true),
261 preload_ntp_(true),
262 model_(this),
263 use_tab_for_suggestions_(false),
264 last_omnibox_text_has_inline_autocompletion_(false),
265 last_verbatim_(false),
266 last_transition_type_(content::PAGE_TRANSITION_LINK),
267 last_match_was_search_(false),
268 omnibox_focus_state_(OMNIBOX_FOCUS_NONE), 121 omnibox_focus_state_(OMNIBOX_FOCUS_NONE),
269 omnibox_focus_change_reason_(OMNIBOX_FOCUS_CHANGE_EXPLICIT), 122 omnibox_focus_change_reason_(OMNIBOX_FOCUS_CHANGE_EXPLICIT),
270 omnibox_bounds_(-1, -1, 0, 0), 123 omnibox_bounds_(-1, -1, 0, 0) {
271 allow_overlay_to_show_search_suggestions_(false) {
272 124
273 // When the InstantController lives, the InstantService should live. 125 // When the InstantController lives, the InstantService should live.
274 // InstantService sets up profile-level facilities such as the ThemeSource for 126 // InstantService sets up profile-level facilities such as the ThemeSource for
275 // the NTP. 127 // the NTP.
276 // However, in some tests, browser_ may be null. 128 // However, in some tests, browser_ may be null.
277 if (browser_) { 129 if (browser_) {
278 InstantService* instant_service = GetInstantService(); 130 InstantService* instant_service = GetInstantService();
279 instant_service->AddObserver(this); 131 instant_service->AddObserver(this);
280 } 132 }
281 } 133 }
282 134
283 InstantController::~InstantController() { 135 InstantController::~InstantController() {
284 if (browser_) { 136 if (browser_) {
285 InstantService* instant_service = GetInstantService(); 137 InstantService* instant_service = GetInstantService();
286 instant_service->RemoveObserver(this); 138 instant_service->RemoveObserver(this);
287 } 139 }
288 } 140 }
289 141
290 void InstantController::OnAutocompleteStart() {
291 if (UseTabForSuggestions() && instant_tab_->supports_instant()) {
292 LOG_INSTANT_DEBUG_EVENT(
293 this, "OnAutocompleteStart: using InstantTab");
294 return;
295 }
296
297 // Not using |instant_tab_|. Check if overlay is OK to use.
298 InstantFallbackReason fallback_reason = ShouldSwitchToLocalOverlay();
299 if (fallback_reason != INSTANT_FALLBACK_NONE) {
300 ResetOverlay(GetLocalInstantURL());
301 RecordFallbackReasonHistogram(fallback_reason);
302 LOG_INSTANT_DEBUG_EVENT(
303 this, "OnAutocompleteStart: switching to local overlay");
304 } else {
305 LOG_INSTANT_DEBUG_EVENT(
306 this, "OnAutocompleteStart: using existing overlay");
307 }
308 use_tab_for_suggestions_ = false;
309 }
310
311 bool InstantController::Update(const AutocompleteMatch& match,
samarth 2013/07/02 21:14:15 Yay!
312 const string16& user_text,
313 const string16& full_text,
314 size_t selection_start,
315 size_t selection_end,
316 bool verbatim,
317 bool user_input_in_progress,
318 bool omnibox_popup_is_open,
319 bool escape_pressed,
320 bool is_keyword_search) {
321 if (!extended_enabled() && !instant_enabled_)
322 return false;
323
324 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
325 "Update: %s user_text='%s' full_text='%s' selection_start=%d "
326 "selection_end=%d verbatim=%d typing=%d popup=%d escape_pressed=%d "
327 "is_keyword_search=%d",
328 AutocompleteMatchType::ToString(match.type).c_str(),
329 UTF16ToUTF8(user_text).c_str(), UTF16ToUTF8(full_text).c_str(),
330 static_cast<int>(selection_start), static_cast<int>(selection_end),
331 verbatim, user_input_in_progress, omnibox_popup_is_open, escape_pressed,
332 is_keyword_search));
333
334 // Store the current |last_omnibox_text_| and update |last_omnibox_text_|
335 // upfront with the contents of |full_text|. Even if we do an early return,
336 // |last_omnibox_text_| will be updated.
337 string16 previous_omnibox_text = last_omnibox_text_;
338 last_omnibox_text_ = full_text;
339 last_match_was_search_ = AutocompleteMatch::IsSearchType(match.type) &&
340 !user_text.empty();
341
342 // TODO(dhollowa): Complete keyword match UI. For now just hide suggestions.
343 // http://crbug.com/153932. Note, this early escape is happens prior to the
344 // DCHECKs below because |user_text| and |full_text| have different semantics
345 // when keyword search is in effect.
346 if (is_keyword_search) {
347 if (UseTabForSuggestions())
348 instant_tab_->sender()->Update(string16(), 0, 0, true);
349 else
350 HideOverlay();
351 last_match_was_search_ = false;
352 last_suggestion_ = InstantSuggestion();
353 return false;
354 }
355
356 // Ignore spurious updates when the omnibox is blurred; otherwise click
357 // targets on the page may vanish before a click event arrives.
358 if (omnibox_focus_state_ == OMNIBOX_FOCUS_NONE)
359 return false;
360
361 // If the popup is open, the user has to be typing.
362 DCHECK(!omnibox_popup_is_open || user_input_in_progress);
363
364 // If the popup is closed, there should be no inline autocompletion.
365 DCHECK(omnibox_popup_is_open || user_text.empty() || user_text == full_text)
366 << user_text << "|" << full_text;
367
368 // If there's no text in the omnibox, the user can't have typed any.
369 DCHECK(!full_text.empty() || user_text.empty()) << user_text;
370
371 // If the user isn't typing, and the popup is closed, there can't be any
372 // user-typed text.
373 DCHECK(user_input_in_progress || omnibox_popup_is_open || user_text.empty())
374 << user_text;
375
376 // The overlay is being clicked and will commit soon. Don't change anything.
377 // TODO(sreeram): Add a browser test for this.
378 if (overlay_ && overlay_->is_pointer_down_from_activate())
379 return false;
380
381 // In non-extended mode, SearchModeChanged() is never called, so fake it. The
382 // mode is set to "disallow suggestions" here, so that if one of the early
383 // "return false" conditions is hit, suggestions will be disallowed. If the
384 // query is sent to the overlay, the mode is set to "allow" further below.
385 if (!extended_enabled())
386 search_mode_.mode = SearchMode::MODE_DEFAULT;
387
388 // In non extended mode, Instant is disabled for URLs and keyword mode.
389 if (!extended_enabled() &&
390 (!last_match_was_search_ ||
391 match.type == AutocompleteMatchType::SEARCH_OTHER_ENGINE)) {
392 HideOverlay();
393 return false;
394 }
395
396 if (!UseTabForSuggestions() && !overlay_) {
397 HideOverlay();
398 return false;
399 }
400
401 if (extended_enabled()) {
402 if (!omnibox_popup_is_open) {
403 if (!user_input_in_progress) {
404 // If the user isn't typing and the omnibox popup is closed, it means a
405 // regular navigation, tab-switch or the user hitting Escape.
406 if (UseTabForSuggestions()) {
407 // The user is on a search results page. It may be showing results for
408 // a partial query the user typed before they hit Escape. Send the
409 // omnibox text to the page to restore the original results.
410 //
411 // In a tab switch, |instant_tab_| won't have updated yet, so it may
412 // be pointing to the previous tab (which was a search results page).
413 // Ensure we don't send the omnibox text to a random webpage (the new
414 // tab), by comparing the old and new WebContents.
415 if (escape_pressed &&
416 instant_tab_->contents() == browser_->GetActiveWebContents()) {
417 // TODO(kmadhusu): If the |full_text| is not empty, send an
418 // onkeypress(esc) to the Instant page. Do not call
419 // onsubmit(full_text). Fix.
420 if (full_text.empty()) {
421 // Call onchange("") to clear the query for the page.
422 instant_tab_->sender()->Update(string16(), 0, 0, true);
423 instant_tab_->sender()->EscKeyPressed();
424 } else {
425 instant_tab_->sender()->Submit(full_text);
426 }
427 }
428 } else if (!full_text.empty()) {
429 // If |full_text| is empty, the user is on the NTP. The overlay may
430 // be showing custom NTP content; hide only if that's not the case.
431 HideOverlay();
432 }
433 } else if (full_text.empty()) {
434 // The user is typing, and backspaced away all omnibox text. Clear
435 // |last_omnibox_text_| so that we don't attempt to set suggestions.
436 last_omnibox_text_.clear();
437 last_user_text_.clear();
438 last_suggestion_ = InstantSuggestion();
439 if (UseTabForSuggestions()) {
440 // On a search results page, tell it to clear old results.
441 instant_tab_->sender()->Update(string16(), 0, 0, true);
442 } else if (overlay_ && search_mode_.is_origin_ntp()) {
443 // On the NTP, tell the overlay to clear old results. Don't hide the
444 // overlay so it can show a blank page or logo if it wants.
445 overlay_->Update(string16(), 0, 0, true);
446 } else {
447 HideOverlay();
448 }
449 } else {
450 // The user switched to a tab with partial text already in the omnibox.
451 HideOverlay();
452
453 // The new tab may or may not be a search results page; we don't know
454 // since SearchModeChanged() hasn't been called yet. If it later turns
455 // out to be, we should store |full_text| now, so that if the user hits
456 // Enter, we'll send the correct query to
457 // instant_tab_->sender()->Submit(). If the partial text is not a query
458 // (|last_match_was_search_| is false), we won't Submit(), so no need to
459 // worry about that.
460 last_user_text_ = user_text;
461 last_suggestion_ = InstantSuggestion();
462 }
463 return false;
464 } else if (full_text.empty()) {
465 // The user typed a solitary "?". Same as the backspace case above.
466 last_omnibox_text_.clear();
467 last_user_text_.clear();
468 last_suggestion_ = InstantSuggestion();
469 if (UseTabForSuggestions())
470 instant_tab_->sender()->Update(string16(), 0, 0, true);
471 else if (overlay_ && search_mode_.is_origin_ntp())
472 overlay_->Update(string16(), 0, 0, true);
473 else
474 HideOverlay();
475 return false;
476 }
477 } else if (!omnibox_popup_is_open || full_text.empty()) {
478 // In the non-extended case, hide the overlay as long as the user isn't
479 // actively typing a non-empty query.
480 HideOverlay();
481 return false;
482 }
483
484 last_omnibox_text_has_inline_autocompletion_ = user_text != full_text;
485
486 // If the user continues typing the same query as the suggested text is
487 // showing, reuse the suggestion (but only for INSTANT_COMPLETE_NEVER).
488 bool reused_suggestion = false;
489 if (last_suggestion_.behavior == INSTANT_COMPLETE_NEVER &&
490 !last_omnibox_text_has_inline_autocompletion_) {
491 if (StartsWith(previous_omnibox_text, full_text, false)) {
492 // The user is backspacing away characters.
493 last_suggestion_.text.insert(0, previous_omnibox_text, full_text.size(),
494 previous_omnibox_text.size() - full_text.size());
495 reused_suggestion = true;
496 } else if (StartsWith(full_text, previous_omnibox_text, false)) {
497 // The user is typing forward. Normalize any added characters.
498 reused_suggestion = NormalizeAndStripPrefix(&last_suggestion_.text,
499 string16(full_text, previous_omnibox_text.size()));
500 }
501 }
502 if (!reused_suggestion)
503 last_suggestion_ = InstantSuggestion();
504
505 // TODO(kmadhusu): Investigate whether it's possible to update
506 // |last_user_text_| at the beginning of this function.
507 last_user_text_ = user_text;
508
509 if (!extended_enabled()) {
510 // In non-extended mode, the query is verbatim if there's any selection
511 // (including inline autocompletion) or if the cursor is not at the end.
512 verbatim = verbatim || selection_start != selection_end ||
513 selection_start != full_text.size();
514 }
515 last_verbatim_ = verbatim;
516
517 last_transition_type_ = match.transition;
518 url_for_history_ = match.destination_url;
519
520 // Allow search suggestions. In extended mode, SearchModeChanged() will set
521 // this, but it's not called in non-extended mode, so fake it.
522 if (!extended_enabled())
523 search_mode_.mode = SearchMode::MODE_SEARCH_SUGGESTIONS;
524
525 if (UseTabForSuggestions()) {
526 instant_tab_->sender()->Update(user_text, selection_start,
527 selection_end, verbatim);
528 } else if (overlay_) {
529 allow_overlay_to_show_search_suggestions_ = true;
530
531 overlay_->Update(extended_enabled() ? user_text : full_text,
532 selection_start, selection_end, verbatim);
533 }
534
535 content::NotificationService::current()->Notify(
536 chrome::NOTIFICATION_INSTANT_CONTROLLER_UPDATED,
537 content::Source<InstantController>(this),
538 content::NotificationService::NoDetails());
539
540 // We don't have new suggestions yet, but we can either reuse the existing
541 // suggestion or reset the existing "gray text".
542 browser_->SetInstantSuggestion(last_suggestion_);
543
544 // Record the time of the first keypress for logging histograms.
545 if (!first_interaction_time_recorded_ && first_interaction_time_.is_null())
546 first_interaction_time_ = base::Time::Now();
547
548 return true;
549 }
550
551 scoped_ptr<content::WebContents> InstantController::ReleaseNTPContents() { 142 scoped_ptr<content::WebContents> InstantController::ReleaseNTPContents() {
552 if (!extended_enabled() || !browser_->profile() || 143 if (!extended_enabled() || !browser_->profile() ||
553 browser_->profile()->IsOffTheRecord() || 144 browser_->profile()->IsOffTheRecord() ||
554 !chrome::ShouldShowInstantNTP()) 145 !chrome::ShouldShowInstantNTP())
555 return scoped_ptr<content::WebContents>(); 146 return scoped_ptr<content::WebContents>();
556 147
557 LOG_INSTANT_DEBUG_EVENT(this, "ReleaseNTPContents"); 148 LOG_INSTANT_DEBUG_EVENT(this, "ReleaseNTPContents");
558 149
559 if (ShouldSwitchToLocalNTP()) 150 if (ShouldSwitchToLocalNTP())
560 ResetNTP(GetLocalInstantURL()); 151 ResetNTP(GetLocalInstantURL());
561 152
562 scoped_ptr<content::WebContents> ntp_contents = ntp_->ReleaseContents(); 153 scoped_ptr<content::WebContents> ntp_contents = ntp_->ReleaseContents();
563 154
564 // Preload a new Instant NTP. 155 // Preload a new Instant NTP.
565 if (preload_ntp_) 156 ResetNTP(GetInstantURL());
566 ResetNTP(GetInstantURL());
567 else
568 ntp_.reset();
569 157
570 return ntp_contents.Pass(); 158 return ntp_contents.Pass();
571 } 159 }
572 160
573 // TODO(tonyg): This method only fires when the omnibox bounds change. It also
574 // needs to fire when the overlay bounds change (e.g.: open/close info bar).
575 void InstantController::SetPopupBounds(const gfx::Rect& bounds) {
576 if (!extended_enabled() && !instant_enabled_)
577 return;
578
579 if (popup_bounds_ == bounds)
580 return;
581
582 popup_bounds_ = bounds;
583 if (popup_bounds_.height() > last_popup_bounds_.height()) {
584 update_bounds_timer_.Stop();
585 SendPopupBoundsToPage();
586 } else if (!update_bounds_timer_.IsRunning()) {
587 update_bounds_timer_.Start(FROM_HERE,
588 base::TimeDelta::FromMilliseconds(kUpdateBoundsDelayMS), this,
589 &InstantController::SendPopupBoundsToPage);
590 }
591 }
592
593 void InstantController::SetOmniboxBounds(const gfx::Rect& bounds) { 161 void InstantController::SetOmniboxBounds(const gfx::Rect& bounds) {
594 if (!extended_enabled() || omnibox_bounds_ == bounds) 162 if (!extended_enabled() || omnibox_bounds_ == bounds)
595 return; 163 return;
596 164
597 omnibox_bounds_ = bounds; 165 omnibox_bounds_ = bounds;
598 if (overlay_)
599 overlay_->sender()->SetOmniboxBounds(omnibox_bounds_);
600 if (ntp_) 166 if (ntp_)
601 ntp_->sender()->SetOmniboxBounds(omnibox_bounds_); 167 ntp_->sender()->SetOmniboxBounds(omnibox_bounds_);
602 if (instant_tab_) 168 if (instant_tab_)
603 instant_tab_->sender()->SetOmniboxBounds(omnibox_bounds_); 169 instant_tab_->sender()->SetOmniboxBounds(omnibox_bounds_);
604 } 170 }
605 171
606 void InstantController::HandleAutocompleteResults(
607 const std::vector<AutocompleteProvider*>& providers,
608 const AutocompleteResult& autocomplete_result) {
609 if (!extended_enabled())
610 return;
611
612 if (!UseTabForSuggestions() && !overlay_)
613 return;
614
615 // The omnibox sends suggestions when its possibly imaginary popup closes
616 // as it stops autocomplete. Ignore these.
617 if (omnibox_focus_state_ == OMNIBOX_FOCUS_NONE)
618 return;
619
620 DVLOG(1) << "AutocompleteResults:";
621 std::vector<InstantAutocompleteResult> results;
622 if (UsingLocalPage()) {
623 for (AutocompleteResult::const_iterator match(autocomplete_result.begin());
624 match != autocomplete_result.end(); ++match) {
625 InstantAutocompleteResult result;
626 PopulateInstantAutocompleteResultFromMatch(
627 *match, std::distance(autocomplete_result.begin(), match), &result);
628 results.push_back(result);
629 }
630 } else {
631 for (ACProviders::const_iterator provider = providers.begin();
632 provider != providers.end(); ++provider) {
633 for (ACMatches::const_iterator match = (*provider)->matches().begin();
634 match != (*provider)->matches().end(); ++match) {
635 // When the top match is an inline history URL, the page calls
636 // SetSuggestions(url) which calls FinalizeInstantQuery() in
637 // SearchProvider creating a NAVSUGGEST match for the URL. If we sent
638 // this NAVSUGGEST match back to the page, it would be deduped against
639 // the original history match and replace it. But since the page ignores
640 // SearchProvider suggestions, the match would then disappear. Yuck.
641 // TODO(jered): Remove this when FinalizeInstantQuery() is ripped out.
642 if ((*provider)->type() == AutocompleteProvider::TYPE_SEARCH &&
643 match->type == AutocompleteMatchType::NAVSUGGEST) {
644 continue;
645 }
646 InstantAutocompleteResult result;
647 PopulateInstantAutocompleteResultFromMatch(*match, kNoMatchIndex,
648 &result);
649 results.push_back(result);
650 }
651 }
652 }
653 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
654 "HandleAutocompleteResults: total_results=%d",
655 static_cast<int>(results.size())));
656
657 if (UseTabForSuggestions())
658 instant_tab_->sender()->SendAutocompleteResults(results);
659 else if (overlay_)
660 overlay_->sender()->SendAutocompleteResults(results);
661
662 content::NotificationService::current()->Notify(
663 chrome::NOTIFICATION_INSTANT_SENT_AUTOCOMPLETE_RESULTS,
664 content::Source<InstantController>(this),
665 content::NotificationService::NoDetails());
666 }
667
668 void InstantController::OnDefaultSearchProviderChanged() { 172 void InstantController::OnDefaultSearchProviderChanged() {
669 if (ntp_ && extended_enabled()) { 173 if (ntp_ && extended_enabled()) {
670 ntp_.reset(); 174 ntp_.reset();
671 if (preload_ntp_) 175 ResetNTP(GetInstantURL());
672 ResetNTP(GetInstantURL());
673 } 176 }
674
675 // Do not reload the overlay if it's actually the local overlay.
676 if (overlay_ && !overlay_->IsLocal()) {
677 overlay_.reset();
678 if (extended_enabled() || instant_enabled_) {
679 // Try to create another overlay immediately so that it is ready for the
680 // next user interaction.
681 ResetOverlay(GetInstantURL());
682 }
683 }
684 }
685
686 bool InstantController::OnUpOrDownKeyPressed(int count) {
687 if (!extended_enabled())
688 return false;
689
690 if (!UseTabForSuggestions() && !overlay_)
691 return false;
692
693 if (UseTabForSuggestions())
694 instant_tab_->sender()->UpOrDownKeyPressed(count);
695 else if (overlay_)
696 overlay_->sender()->UpOrDownKeyPressed(count);
697
698 return true;
699 }
700
701 void InstantController::OnCancel(const AutocompleteMatch& match,
702 const string16& user_text,
703 const string16& full_text) {
704 if (!extended_enabled())
705 return;
706
707 if (!UseTabForSuggestions() && !overlay_)
708 return;
709
710 // We manually reset the state here since the JS is not expected to do it.
711 // TODO(sreeram): Handle the case where user_text is now a URL
712 last_match_was_search_ = AutocompleteMatch::IsSearchType(match.type) &&
713 !full_text.empty();
714 last_omnibox_text_ = full_text;
715 last_user_text_ = user_text;
716 last_suggestion_ = InstantSuggestion();
717
718 // Say |full_text| is "amazon.com" and |user_text| is "ama". This means the
719 // inline autocompletion is "zon.com"; so the selection should span from
720 // user_text.size() to full_text.size(). The selection bounds are inverted
721 // because the caret is at the end of |user_text|, not |full_text|.
722 if (UseTabForSuggestions()) {
723 instant_tab_->sender()->CancelSelection(user_text, full_text.size(),
724 user_text.size(), last_verbatim_);
725 } else if (overlay_) {
726 overlay_->sender()->CancelSelection(user_text, full_text.size(),
727 user_text.size(), last_verbatim_);
728 }
729 }
730
731 void InstantController::OmniboxNavigateToURL() {
732 RecordNavigationHistogram(UsingLocalPage(), false, extended_enabled());
733 if (!extended_enabled())
734 return;
735 if (UseTabForSuggestions())
736 instant_tab_->sender()->Submit(string16());
737 } 177 }
738 178
739 void InstantController::ToggleVoiceSearch() { 179 void InstantController::ToggleVoiceSearch() {
740 if (instant_tab_) 180 if (instant_tab_)
741 instant_tab_->sender()->ToggleVoiceSearch(); 181 instant_tab_->sender()->ToggleVoiceSearch();
742 } 182 }
743 183
744 void InstantController::InstantPageLoadFailed(content::WebContents* contents) { 184 void InstantController::InstantPageLoadFailed(content::WebContents* contents) {
745 if (!chrome::ShouldPreferRemoteNTPOnStartup() || !extended_enabled()) { 185 if (!chrome::ShouldPreferRemoteNTPOnStartup() || !extended_enabled()) {
746 // We only need to fall back on errors if we're showing the online page 186 // We only need to fall back on errors if we're showing the online page
(...skipping 19 matching lines...) Expand all
766 contents->GetController().CanGoForward()) 206 contents->GetController().CanGoForward())
767 return; 207 return;
768 LOG_INSTANT_DEBUG_EVENT(this, "InstantPageLoadFailed: instant_tab"); 208 LOG_INSTANT_DEBUG_EVENT(this, "InstantPageLoadFailed: instant_tab");
769 RedirectToLocalNTP(contents); 209 RedirectToLocalNTP(contents);
770 } else if (IsContentsFrom(ntp(), contents)) { 210 } else if (IsContentsFrom(ntp(), contents)) {
771 LOG_INSTANT_DEBUG_EVENT(this, "InstantPageLoadFailed: ntp"); 211 LOG_INSTANT_DEBUG_EVENT(this, "InstantPageLoadFailed: ntp");
772 bool is_local = ntp_->IsLocal(); 212 bool is_local = ntp_->IsLocal();
773 DeletePageSoon(ntp_.Pass()); 213 DeletePageSoon(ntp_.Pass());
774 if (!is_local) 214 if (!is_local)
775 ResetNTP(GetLocalInstantURL()); 215 ResetNTP(GetLocalInstantURL());
776 } else if (IsContentsFrom(overlay(), contents)) { 216 } else {
777 LOG_INSTANT_DEBUG_EVENT(this, "InstantPageLoadFailed: overlay"); 217 NOTREACHED();
778 bool is_local = overlay_->IsLocal();
779 DeletePageSoon(overlay_.Pass());
780 if (!is_local)
781 ResetOverlay(GetLocalInstantURL());
782 } 218 }
783 } 219 }
784 220
785 content::WebContents* InstantController::GetOverlayContents() const {
786 return overlay_ ? overlay_->contents() : NULL;
787 }
788
789 content::WebContents* InstantController::GetNTPContents() const { 221 content::WebContents* InstantController::GetNTPContents() const {
790 return ntp_ ? ntp_->contents() : NULL; 222 return ntp_ ? ntp_->contents() : NULL;
791 } 223 }
792 224
793 bool InstantController::IsOverlayingSearchResults() const {
794 return model_.mode().is_search_suggestions() && IsFullHeight(model_) &&
795 (last_match_was_search_ ||
796 last_suggestion_.behavior == INSTANT_COMPLETE_NEVER);
797 }
798
799 bool InstantController::SubmitQuery(const string16& search_terms) { 225 bool InstantController::SubmitQuery(const string16& search_terms) {
800 if (extended_enabled() && instant_tab_ && instant_tab_->supports_instant() && 226 if (extended_enabled() && instant_tab_ && instant_tab_->supports_instant() &&
801 search_mode_.is_origin_search()) { 227 search_mode_.is_origin_search()) {
802 // Use |instant_tab_| to run the query if we're already on a search results 228 // Use |instant_tab_| to run the query if we're already on a search results
803 // page. (NOTE: in particular, we do not send the query to NTPs.) 229 // page. (NOTE: in particular, we do not send the query to NTPs.)
804 instant_tab_->sender()->Submit(search_terms); 230 instant_tab_->sender()->Submit(search_terms);
805 instant_tab_->contents()->GetView()->Focus(); 231 instant_tab_->contents()->GetView()->Focus();
806 EnsureSearchTermsAreSet(instant_tab_->contents(), search_terms); 232 EnsureSearchTermsAreSet(instant_tab_->contents(), search_terms);
807 return true; 233 return true;
808 } 234 }
809 return false; 235 return false;
810 } 236 }
811 237
812 bool InstantController::CommitIfPossible(InstantCommitType type) {
813 if (!extended_enabled() && !instant_enabled_)
814 return false;
815
816 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
817 "CommitIfPossible: type=%d last_omnibox_text_='%s' "
818 "last_match_was_search_=%d use_tab_for_suggestions=%d", type,
819 UTF16ToUTF8(last_omnibox_text_).c_str(), last_match_was_search_,
820 UseTabForSuggestions()));
821
822 // If we are on an already committed search results page, send a submit event
823 // to the page, but otherwise, nothing else to do.
824 if (UseTabForSuggestions()) {
825 if (type == INSTANT_COMMIT_PRESSED_ENTER &&
826 !instant_tab_->IsLocal() &&
827 (last_match_was_search_ ||
828 last_suggestion_.behavior == INSTANT_COMPLETE_NEVER)) {
829 last_suggestion_.text.clear();
830 instant_tab_->sender()->Submit(last_omnibox_text_);
831 instant_tab_->contents()->GetView()->Focus();
832 EnsureSearchTermsAreSet(instant_tab_->contents(), last_omnibox_text_);
833 return true;
834 }
835 return false;
836 }
837
838 if (!overlay_)
839 return false;
840
841 // If the overlay is not showing at all, don't commit it.
842 if (!model_.mode().is_search_suggestions())
843 return false;
844
845 // If the overlay is showing at full height (with results), commit it.
846 // If it's showing at parial height, commit if it's navigating.
847 if (!IsOverlayingSearchResults() && type != INSTANT_COMMIT_NAVIGATED)
848 return false;
849
850 // There may re-entrance here, from the call to browser_->CommitInstant below,
851 // which can cause a TabDeactivated notification which gets back here.
852 // In this case, overlay_->ReleaseContents() was called already.
853 if (!GetOverlayContents())
854 return false;
855
856 // Never commit the local overlay.
857 if (overlay_->IsLocal())
858 return false;
859
860 if (type == INSTANT_COMMIT_FOCUS_LOST) {
861 // Extended mode doesn't need or use the Cancel message.
862 if (!extended_enabled())
863 overlay_->sender()->Cancel(last_omnibox_text_);
864 } else if (type != INSTANT_COMMIT_NAVIGATED) {
865 overlay_->sender()->Submit(last_omnibox_text_);
866 }
867
868 // We expect the WebContents to be in a valid state (i.e., has a last
869 // committed entry, no transient entry, and no existing pending entry).
870 scoped_ptr<content::WebContents> overlay = overlay_->ReleaseContents();
871 CHECK(overlay->GetController().CanPruneAllButVisible());
872
873 // If the overlay page has navigated since the last Update(), we need to add
874 // the navigation to history ourselves. Else, the page will navigate after
875 // commit, and it will be added to history in the usual manner.
876 const history::HistoryAddPageArgs& last_navigation =
877 overlay_->last_navigation();
878 if (!last_navigation.url.is_empty()) {
879 content::NavigationEntry* entry = overlay->GetController().GetActiveEntry();
880
881 // The last navigation should be the same as the active entry if the overlay
882 // is in search mode. During navigation, the active entry could have
883 // changed since DidCommitProvisionalLoadForFrame is called after the entry
884 // is changed.
885 // TODO(shishir): Should we commit the last navigation for
886 // INSTANT_COMMIT_NAVIGATED.
887 DCHECK(type == INSTANT_COMMIT_NAVIGATED ||
888 last_navigation.url == entry->GetURL());
889
890 // Add the page to history.
891 HistoryTabHelper* history_tab_helper =
892 HistoryTabHelper::FromWebContents(overlay.get());
893 history_tab_helper->UpdateHistoryForNavigation(last_navigation);
894
895 // Update the page title.
896 history_tab_helper->UpdateHistoryPageTitle(*entry);
897 }
898
899 // Add a fake history entry with a non-Instant search URL, so that search
900 // terms extraction (for autocomplete history matches) works.
901 HistoryService* history = HistoryServiceFactory::GetForProfile(
902 Profile::FromBrowserContext(overlay->GetBrowserContext()),
903 Profile::EXPLICIT_ACCESS);
904 if (history) {
905 history->AddPage(url_for_history_, base::Time::Now(), NULL, 0, GURL(),
906 history::RedirectList(), last_transition_type_,
907 history::SOURCE_BROWSED, false);
908 }
909
910 if (type == INSTANT_COMMIT_PRESSED_ALT_ENTER) {
911 overlay->GetController().PruneAllButVisible();
912 } else {
913 content::WebContents* active_tab = browser_->GetActiveWebContents();
914 AddSessionStorageHistogram(extended_enabled(), active_tab, overlay.get());
915 overlay->GetController().CopyStateFromAndPrune(
916 &active_tab->GetController());
917 }
918
919 if (extended_enabled()) {
920 // Adjust the search terms shown in the omnibox for this query. Hitting
921 // ENTER searches for what the user typed, so use last_omnibox_text_.
922 // Clicking on the overlay commits what is currently showing, so add in the
923 // gray text in that case.
924 if (type == INSTANT_COMMIT_FOCUS_LOST &&
925 last_suggestion_.behavior == INSTANT_COMPLETE_NEVER) {
926 // Update |last_omnibox_text_| so that the controller commits the proper
927 // query if the user focuses the omnibox and presses Enter.
928 last_omnibox_text_ += last_suggestion_.text;
929 }
930
931 EnsureSearchTermsAreSet(overlay.get(), last_omnibox_text_);
932 }
933
934 // Save notification source before we release the overlay.
935 content::Source<content::WebContents> notification_source(overlay.get());
936
937 browser_->CommitInstant(overlay.Pass(),
938 type == INSTANT_COMMIT_PRESSED_ALT_ENTER);
939
940 content::NotificationService::current()->Notify(
941 chrome::NOTIFICATION_INSTANT_COMMITTED,
942 notification_source,
943 content::NotificationService::NoDetails());
944
945 // Hide explicitly. See comments in HideOverlay() for why.
946 model_.SetOverlayState(SearchMode(), 0, INSTANT_SIZE_PERCENT);
947
948 // Delay deletion as we could've gotten here from an InstantOverlay method.
949 DeletePageSoon(overlay_.Pass());
950
951 // Try to create another overlay immediately so that it is ready for the next
952 // user interaction.
953 ResetOverlay(GetInstantURL());
954
955 if (instant_tab_)
956 use_tab_for_suggestions_ = true;
957
958 LOG_INSTANT_DEBUG_EVENT(this, "Committed");
959 return true;
960 }
961
962 void InstantController::OmniboxFocusChanged( 238 void InstantController::OmniboxFocusChanged(
963 OmniboxFocusState state, 239 OmniboxFocusState state,
964 OmniboxFocusChangeReason reason, 240 OmniboxFocusChangeReason reason,
965 gfx::NativeView view_gaining_focus) { 241 gfx::NativeView view_gaining_focus) {
966 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf( 242 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
967 "OmniboxFocusChanged: %d to %d for reason %d", omnibox_focus_state_, 243 "OmniboxFocusChanged: %d to %d for reason %d", omnibox_focus_state_,
968 state, reason)); 244 state, reason));
969 245
970 OmniboxFocusState old_focus_state = omnibox_focus_state_;
971 omnibox_focus_state_ = state; 246 omnibox_focus_state_ = state;
972 if (!extended_enabled() && !instant_enabled_) 247 if (!extended_enabled() || !instant_tab_)
973 return; 248 return;
974 249
975 if (extended_enabled()) { 250 instant_tab_->sender()->FocusChanged(omnibox_focus_state_, reason);
976 if (overlay_) 251 // Don't send oninputstart/oninputend updates in response to focus changes
977 overlay_->sender()->FocusChanged(omnibox_focus_state_, reason); 252 // if there's a navigation in progress. This prevents Chrome from sending
978 253 // a spurious oninputend when the user accepts a match in the omnibox.
979 if (instant_tab_) { 254 if (instant_tab_->contents()->GetController().GetPendingEntry() == NULL)
980 instant_tab_->sender()->FocusChanged(omnibox_focus_state_, reason); 255 instant_tab_->sender()->SetInputInProgress(IsInputInProgress());
981 // Don't send oninputstart/oninputend updates in response to focus changes
982 // if there's a navigation in progress. This prevents Chrome from sending
983 // a spurious oninputend when the user accepts a match in the omnibox.
984 if (instant_tab_->contents()->GetController().GetPendingEntry() == NULL)
985 instant_tab_->sender()->SetInputInProgress(IsInputInProgress());
986 }
987 }
988
989 if (state == OMNIBOX_FOCUS_VISIBLE && old_focus_state == OMNIBOX_FOCUS_NONE) {
990 // If the user explicitly focused the omnibox, then create the overlay if
991 // it doesn't exist. If we're using a fallback overlay, try loading the
992 // remote overlay again.
993 if (!overlay_ || (overlay_->IsLocal() && !use_local_page_only_))
994 ResetOverlay(GetInstantURL());
995 } else if (state == OMNIBOX_FOCUS_NONE &&
996 old_focus_state != OMNIBOX_FOCUS_NONE) {
997 // If the focus went from the omnibox to outside the omnibox, commit or
998 // discard the overlay.
999 OmniboxLostFocus(view_gaining_focus);
1000 }
1001 } 256 }
1002 257
1003 void InstantController::SearchModeChanged(const SearchMode& old_mode, 258 void InstantController::SearchModeChanged(const SearchMode& old_mode,
1004 const SearchMode& new_mode) { 259 const SearchMode& new_mode) {
1005 if (!extended_enabled()) 260 if (!extended_enabled())
1006 return; 261 return;
1007 262
1008 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf( 263 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1009 "SearchModeChanged: [origin:mode] %d:%d to %d:%d", old_mode.origin, 264 "SearchModeChanged: [origin:mode] %d:%d to %d:%d", old_mode.origin,
1010 old_mode.mode, new_mode.origin, new_mode.mode)); 265 old_mode.mode, new_mode.origin, new_mode.mode));
1011 266
1012 search_mode_ = new_mode; 267 search_mode_ = new_mode;
1013 if (!new_mode.is_search_suggestions())
1014 HideOverlay();
1015
1016 ResetInstantTab(); 268 ResetInstantTab();
1017 269
1018 if (instant_tab_ && old_mode.is_ntp() != new_mode.is_ntp()) 270 if (instant_tab_ && old_mode.is_ntp() != new_mode.is_ntp())
1019 instant_tab_->sender()->SetInputInProgress(IsInputInProgress()); 271 instant_tab_->sender()->SetInputInProgress(IsInputInProgress());
1020 } 272 }
1021 273
1022 void InstantController::ActiveTabChanged() { 274 void InstantController::ActiveTabChanged() {
1023 if (!extended_enabled() && !instant_enabled_) 275 if (!extended_enabled())
1024 return; 276 return;
1025 277
1026 LOG_INSTANT_DEBUG_EVENT(this, "ActiveTabChanged"); 278 LOG_INSTANT_DEBUG_EVENT(this, "ActiveTabChanged");
1027 279 ResetInstantTab();
1028 // When switching tabs, always hide the overlay.
1029 HideOverlay();
1030
1031 if (extended_enabled())
1032 ResetInstantTab();
1033 } 280 }
1034 281
1035 void InstantController::TabDeactivated(content::WebContents* contents) { 282 void InstantController::TabDeactivated(content::WebContents* contents) {
samarth 2013/07/02 21:14:15 Can just remove this function.
Jered 2013/07/02 22:03:11 I kept it in anticipation of https://codereview.ch
1036 LOG_INSTANT_DEBUG_EVENT(this, "TabDeactivated");
1037 if (extended_enabled() && !contents->IsBeingDestroyed())
1038 CommitIfPossible(INSTANT_COMMIT_FOCUS_LOST);
1039
1040 if (GetOverlayContents())
1041 HideOverlay();
1042 }
1043
1044 void InstantController::SetInstantEnabled(bool instant_enabled,
1045 bool use_local_page_only) {
1046 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1047 "SetInstantEnabled: instant_enabled=%d, use_local_page_only=%d",
1048 instant_enabled, use_local_page_only));
1049
1050 // Non extended mode does not care about |use_local_page_only|.
1051 if (instant_enabled == instant_enabled_ &&
1052 (!extended_enabled() ||
1053 use_local_page_only == use_local_page_only_)) {
1054 return;
1055 }
1056
1057 instant_enabled_ = instant_enabled;
1058 use_local_page_only_ = use_local_page_only;
1059 preload_ntp_ = !use_local_page_only_;
1060
1061 // Preload the overlay.
1062 HideInternal();
1063 overlay_.reset();
1064 if (extended_enabled() || instant_enabled_)
1065 ResetOverlay(GetInstantURL());
1066
1067 // Preload the Instant NTP.
1068 ntp_.reset();
1069 if (extended_enabled() && preload_ntp_)
1070 ResetNTP(GetInstantURL());
1071
1072 if (instant_tab_)
1073 instant_tab_->sender()->SetDisplayInstantResults(instant_enabled_);
1074 } 283 }
1075 284
1076 void InstantController::ThemeInfoChanged( 285 void InstantController::ThemeInfoChanged(
1077 const ThemeBackgroundInfo& theme_info) { 286 const ThemeBackgroundInfo& theme_info) {
1078 if (!extended_enabled()) 287 if (!extended_enabled())
1079 return; 288 return;
1080 289
1081 if (overlay_)
1082 overlay_->sender()->SendThemeBackgroundInfo(theme_info);
1083 if (ntp_) 290 if (ntp_)
1084 ntp_->sender()->SendThemeBackgroundInfo(theme_info); 291 ntp_->sender()->SendThemeBackgroundInfo(theme_info);
1085 if (instant_tab_) 292 if (instant_tab_)
1086 instant_tab_->sender()->SendThemeBackgroundInfo(theme_info); 293 instant_tab_->sender()->SendThemeBackgroundInfo(theme_info);
1087 } 294 }
1088 295
1089 void InstantController::SwappedOverlayContents() {
1090 model_.SetOverlayContents(GetOverlayContents());
1091 }
1092
1093 void InstantController::FocusedOverlayContents() {
1094 #if defined(USE_AURA)
1095 // On aura the omnibox only receives a focus lost if we initiate the focus
1096 // change. This does that.
1097 if (!model_.mode().is_default())
1098 browser_->InstantOverlayFocused();
1099 #endif
1100 }
1101
1102 void InstantController::ReloadOverlayIfStale() {
1103 // The local overlay is never stale.
1104 if (overlay_ && (overlay_->IsLocal() || !overlay_->is_stale()))
1105 return;
1106
1107 // If the overlay is showing or the omnibox has focus, don't refresh the
1108 // overlay. It will get refreshed the next time the overlay is hidden or the
1109 // omnibox loses focus.
1110 if (omnibox_focus_state_ == OMNIBOX_FOCUS_NONE && model_.mode().is_default())
1111 ResetOverlay(GetInstantURL());
1112 }
1113
1114 void InstantController::OverlayLoadCompletedMainFrame() {
1115 if (!overlay_ || overlay_->supports_instant())
1116 return;
1117 InstantService* instant_service = GetInstantService();
1118 content::WebContents* contents = overlay_->contents();
1119 DCHECK(contents);
1120 if (instant_service->IsInstantProcess(
1121 contents->GetRenderProcessHost()->GetID())) {
1122 return;
1123 }
1124 InstantSupportDetermined(contents, false);
1125 }
1126
1127 void InstantController::LogDebugEvent(const std::string& info) const { 296 void InstantController::LogDebugEvent(const std::string& info) const {
1128 DVLOG(1) << info; 297 DVLOG(1) << info;
1129 298
1130 debug_events_.push_front(std::make_pair( 299 debug_events_.push_front(std::make_pair(
1131 base::Time::Now().ToInternalValue(), info)); 300 base::Time::Now().ToInternalValue(), info));
1132 static const size_t kMaxDebugEventSize = 2000; 301 static const size_t kMaxDebugEventSize = 2000;
1133 if (debug_events_.size() > kMaxDebugEventSize) 302 if (debug_events_.size() > kMaxDebugEventSize)
1134 debug_events_.pop_back(); 303 debug_events_.pop_back();
1135 } 304 }
1136 305
1137 void InstantController::ClearDebugEvents() { 306 void InstantController::ClearDebugEvents() {
1138 debug_events_.clear(); 307 debug_events_.clear();
1139 } 308 }
1140 309
1141 void InstantController::MostVisitedItemsChanged( 310 void InstantController::MostVisitedItemsChanged(
1142 const std::vector<InstantMostVisitedItem>& items) { 311 const std::vector<InstantMostVisitedItem>& items) {
1143 if (overlay_)
1144 overlay_->sender()->SendMostVisitedItems(items);
1145
1146 if (ntp_) 312 if (ntp_)
1147 ntp_->sender()->SendMostVisitedItems(items); 313 ntp_->sender()->SendMostVisitedItems(items);
1148
1149 if (instant_tab_) 314 if (instant_tab_)
1150 instant_tab_->sender()->SendMostVisitedItems(items); 315 instant_tab_->sender()->SendMostVisitedItems(items);
1151 316
1152 content::NotificationService::current()->Notify( 317 content::NotificationService::current()->Notify(
1153 chrome::NOTIFICATION_INSTANT_SENT_MOST_VISITED_ITEMS, 318 chrome::NOTIFICATION_INSTANT_SENT_MOST_VISITED_ITEMS,
1154 content::Source<InstantController>(this), 319 content::Source<InstantController>(this),
1155 content::NotificationService::NoDetails()); 320 content::NotificationService::NoDetails());
1156 } 321 }
1157 322
1158 void InstantController::DeleteMostVisitedItem(const GURL& url) { 323 void InstantController::DeleteMostVisitedItem(const GURL& url) {
(...skipping 19 matching lines...) Expand all
1178 if (!instant_service) 343 if (!instant_service)
1179 return; 344 return;
1180 345
1181 instant_service->UndoAllMostVisitedDeletions(); 346 instant_service->UndoAllMostVisitedDeletions();
1182 } 347 }
1183 348
1184 Profile* InstantController::profile() const { 349 Profile* InstantController::profile() const {
1185 return browser_->profile(); 350 return browser_->profile();
1186 } 351 }
1187 352
1188 InstantOverlay* InstantController::overlay() const {
1189 return overlay_.get();
1190 }
1191
1192 InstantTab* InstantController::instant_tab() const { 353 InstantTab* InstantController::instant_tab() const {
1193 return instant_tab_.get(); 354 return instant_tab_.get();
1194 } 355 }
1195 356
1196 InstantNTP* InstantController::ntp() const { 357 InstantNTP* InstantController::ntp() const {
1197 return ntp_.get(); 358 return ntp_.get();
1198 } 359 }
1199 360
1200 // TODO(shishir): We assume that the WebContent's current RenderViewHost is the 361 // TODO(shishir): We assume that the WebContent's current RenderViewHost is the
1201 // RenderViewHost being created which is not always true. Fix this. 362 // RenderViewHost being created which is not always true. Fix this.
1202 void InstantController::InstantPageRenderViewCreated( 363 void InstantController::InstantPageRenderViewCreated(
1203 const content::WebContents* contents) { 364 const content::WebContents* contents) {
1204 if (!extended_enabled()) 365 if (!extended_enabled())
1205 return; 366 return;
1206 367
1207 // Update theme info so that the page picks it up. 368 // Update theme info so that the page picks it up.
1208 InstantService* instant_service = GetInstantService(); 369 InstantService* instant_service = GetInstantService();
1209 if (instant_service) { 370 if (instant_service) {
1210 instant_service->UpdateThemeInfo(); 371 instant_service->UpdateThemeInfo();
1211 instant_service->UpdateMostVisitedItemsInfo(); 372 instant_service->UpdateMostVisitedItemsInfo();
1212 } 373 }
1213 374
1214 // Ensure the searchbox API has the correct initial state. 375 // Ensure the searchbox API has the correct initial state.
1215 if (IsContentsFrom(overlay(), contents)) { 376 if (IsContentsFrom(ntp(), contents)) {
1216 overlay_->sender()->SetDisplayInstantResults(instant_enabled_);
1217 overlay_->sender()->FocusChanged(omnibox_focus_state_,
1218 omnibox_focus_change_reason_);
1219 overlay_->sender()->SetOmniboxBounds(omnibox_bounds_);
1220 overlay_->InitializeFonts();
1221 } else if (IsContentsFrom(ntp(), contents)) {
1222 ntp_->sender()->SetDisplayInstantResults(instant_enabled_);
1223 ntp_->sender()->SetOmniboxBounds(omnibox_bounds_); 377 ntp_->sender()->SetOmniboxBounds(omnibox_bounds_);
1224 ntp_->InitializeFonts(); 378 ntp_->InitializeFonts();
1225 ntp_->InitializePromos(); 379 ntp_->InitializePromos();
1226 } else { 380 } else {
1227 NOTREACHED(); 381 NOTREACHED();
1228 } 382 }
1229 } 383 }
1230 384
1231 void InstantController::InstantSupportChanged( 385 void InstantController::InstantSupportChanged(
1232 InstantSupportState instant_support) { 386 InstantSupportState instant_support) {
(...skipping 30 matching lines...) Expand all
1263 // Preload a local NTP in place of the broken online one. 417 // Preload a local NTP in place of the broken online one.
1264 if (!is_local) 418 if (!is_local)
1265 ResetNTP(GetLocalInstantURL()); 419 ResetNTP(GetLocalInstantURL());
1266 } 420 }
1267 421
1268 content::NotificationService::current()->Notify( 422 content::NotificationService::current()->Notify(
1269 chrome::NOTIFICATION_INSTANT_NTP_SUPPORT_DETERMINED, 423 chrome::NOTIFICATION_INSTANT_NTP_SUPPORT_DETERMINED,
1270 content::Source<InstantController>(this), 424 content::Source<InstantController>(this),
1271 content::NotificationService::NoDetails()); 425 content::NotificationService::NoDetails());
1272 426
1273 } else if (IsContentsFrom(overlay(), contents)) { 427 } else {
1274 if (!supports_instant) { 428 NOTREACHED();
1275 HideInternal();
1276 bool is_local = overlay_->IsLocal();
1277 DeletePageSoon(overlay_.Pass());
1278 // Preload a local overlay in place of the broken online one.
1279 if (!is_local && extended_enabled())
1280 ResetOverlay(GetLocalInstantURL());
1281 }
1282
1283 content::NotificationService::current()->Notify(
1284 chrome::NOTIFICATION_INSTANT_OVERLAY_SUPPORT_DETERMINED,
1285 content::Source<InstantController>(this),
1286 content::NotificationService::NoDetails());
1287 } 429 }
1288 } 430 }
1289 431
1290 void InstantController::InstantPageRenderViewGone( 432 void InstantController::InstantPageRenderViewGone(
1291 const content::WebContents* contents) { 433 const content::WebContents* contents) {
1292 if (IsContentsFrom(overlay(), contents)) { 434 if (IsContentsFrom(ntp(), contents)) {
1293 HideInternal();
1294 DeletePageSoon(overlay_.Pass());
1295 } else if (IsContentsFrom(ntp(), contents)) {
1296 DeletePageSoon(ntp_.Pass()); 435 DeletePageSoon(ntp_.Pass());
1297 } else { 436 } else {
1298 NOTREACHED(); 437 NOTREACHED();
1299 } 438 }
1300 } 439 }
1301 440
1302 void InstantController::InstantPageAboutToNavigateMainFrame( 441 void InstantController::InstantPageAboutToNavigateMainFrame(
1303 const content::WebContents* contents, 442 const content::WebContents* contents,
1304 const GURL& url) { 443 const GURL& url) {
1305 if (IsContentsFrom(overlay(), contents)) { 444 if (IsContentsFrom(instant_tab(), contents)) {
1306 // If the page does not yet support Instant, we allow redirects and other
1307 // navigations to go through since the Instant URL can redirect - e.g. to
1308 // country specific pages.
1309 if (!overlay_->supports_instant())
1310 return;
1311
1312 GURL instant_url(overlay_->instant_url());
1313
1314 // If we are navigating to the Instant URL, do nothing.
1315 if (url == instant_url)
1316 return;
1317
1318 // Commit the navigation if either:
1319 // - The page is in NTP mode (so it could only navigate on a user click) or
1320 // - The page is not in NTP mode and we are navigating to a URL with a
1321 // different host or path than the Instant URL. This enables the instant
1322 // page when it is showing search results to change the query parameters
1323 // and fragments of the URL without it navigating.
1324 if (model_.mode().is_ntp() ||
1325 (url.host() != instant_url.host() ||
1326 url.path() != instant_url.path())) {
1327 CommitIfPossible(INSTANT_COMMIT_NAVIGATED);
1328 }
1329 } else if (IsContentsFrom(instant_tab(), contents)) {
1330 // The Instant tab navigated. Send it the data it needs to display 445 // The Instant tab navigated. Send it the data it needs to display
1331 // properly. 446 // properly.
1332 UpdateInfoForInstantTab(); 447 UpdateInfoForInstantTab();
1333 } else { 448 } else {
1334 NOTREACHED(); 449 NOTREACHED();
1335 } 450 }
1336 } 451 }
1337 452
1338 void InstantController::SetSuggestions(
1339 const content::WebContents* contents,
1340 const std::vector<InstantSuggestion>& suggestions) {
1341 LOG_INSTANT_DEBUG_EVENT(this, "SetSuggestions");
1342
1343 // Ignore if the message is from an unexpected source.
1344 if (IsContentsFrom(ntp(), contents))
1345 return;
1346 if (UseTabForSuggestions() && !IsContentsFrom(instant_tab(), contents))
1347 return;
1348 if (IsContentsFrom(overlay(), contents) &&
1349 !allow_overlay_to_show_search_suggestions_)
1350 return;
1351
1352 InstantSuggestion suggestion;
1353 if (!suggestions.empty())
1354 suggestion = suggestions[0];
1355
1356 // TODO(samarth): allow InstantTabs to call SetSuggestions() from the NTP once
1357 // that is better supported.
1358 bool can_use_instant_tab = UseTabForSuggestions() &&
1359 search_mode_.is_search();
1360 bool can_use_overlay = search_mode_.is_search_suggestions() &&
1361 !last_omnibox_text_.empty();
1362 if (!can_use_instant_tab && !can_use_overlay)
1363 return;
1364
1365 if (suggestion.behavior == INSTANT_COMPLETE_REPLACE) {
1366 if (omnibox_focus_state_ == OMNIBOX_FOCUS_NONE) {
1367 // TODO(samarth,skanuj): setValue() needs to be handled differently when
1368 // the omnibox doesn't have focus. Instead of setting temporary text, we
1369 // should be setting search terms on the appropriate NavigationEntry.
1370 // (Among other things, this ensures that URL-shaped values will get the
1371 // additional security token.)
1372 //
1373 // Note that this also breaks clicking on a suggestion corresponding to
1374 // gray-text completion: we can't distinguish between the user
1375 // clicking on white space (where we don't accept the gray text) and the
1376 // user clicking on the suggestion (when we do accept the gray text).
1377 // This needs to be fixed before we can turn on Instant again.
1378 return;
1379 }
1380
1381 // We don't get an Update() when changing the omnibox due to a REPLACE
1382 // suggestion (so that we don't inadvertently cause the overlay to change
1383 // what it's showing, as the user arrows up/down through the page-provided
1384 // suggestions). So, update these state variables here.
1385 last_omnibox_text_ = suggestion.text;
1386 last_user_text_.clear();
1387 last_suggestion_ = InstantSuggestion();
1388 last_match_was_search_ = suggestion.type == INSTANT_SUGGESTION_SEARCH;
1389 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1390 "ReplaceSuggestion text='%s' type=%d",
1391 UTF16ToUTF8(suggestion.text).c_str(), suggestion.type));
1392 browser_->SetInstantSuggestion(suggestion);
1393 } else {
1394 if (FixSuggestion(&suggestion)) {
1395 last_suggestion_ = suggestion;
1396 if (suggestion.type == INSTANT_SUGGESTION_SEARCH &&
1397 suggestion.behavior == INSTANT_COMPLETE_NEVER)
1398 last_omnibox_text_ = last_user_text_;
1399 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1400 "SetInstantSuggestion: text='%s' behavior=%d",
1401 UTF16ToUTF8(suggestion.text).c_str(),
1402 suggestion.behavior));
1403 browser_->SetInstantSuggestion(suggestion);
1404 content::NotificationService::current()->Notify(
1405 chrome::NOTIFICATION_INSTANT_SET_SUGGESTION,
1406 content::Source<InstantController>(this),
1407 content::NotificationService::NoDetails());
1408 } else {
1409 last_suggestion_ = InstantSuggestion();
1410 }
1411 }
1412
1413 // Extended mode pages will call ShowOverlay() when they are ready.
1414 if (!extended_enabled())
1415 ShowOverlay(100, INSTANT_SIZE_PERCENT);
1416 }
1417
1418 void InstantController::ShowInstantOverlay(const content::WebContents* contents,
1419 int height,
1420 InstantSizeUnits units) {
1421 if (extended_enabled() && IsContentsFrom(overlay(), contents))
1422 ShowOverlay(height, units);
1423 }
1424
1425 void InstantController::LogDropdownShown() {
1426 // If suggestions are being shown for the first time since the user started
1427 // typing, record a histogram value.
1428 if (!first_interaction_time_.is_null() && !first_interaction_time_recorded_) {
1429 base::TimeDelta delta = base::Time::Now() - first_interaction_time_;
1430 first_interaction_time_recorded_ = true;
1431 if (search_mode_.is_origin_ntp()) {
1432 UMA_HISTOGRAM_TIMES("Instant.TimeToFirstShowFromNTP", delta);
1433 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1434 "LogShowInstantOverlay: TimeToFirstShowFromNTP=%d",
1435 static_cast<int>(delta.InMilliseconds())));
1436 } else if (search_mode_.is_origin_search()) {
1437 UMA_HISTOGRAM_TIMES("Instant.TimeToFirstShowFromSERP", delta);
1438 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1439 "LogShowInstantOverlay: TimeToFirstShowFromSERP=%d",
1440 static_cast<int>(delta.InMilliseconds())));
1441 } else {
1442 UMA_HISTOGRAM_TIMES("Instant.TimeToFirstShowFromWeb", delta);
1443 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1444 "LogShowInstantOverlay: TimeToFirstShowFromWeb=%d",
1445 static_cast<int>(delta.InMilliseconds())));
1446 }
1447 }
1448 }
1449
1450 void InstantController::FocusOmnibox(const content::WebContents* contents, 453 void InstantController::FocusOmnibox(const content::WebContents* contents,
1451 OmniboxFocusState state) { 454 OmniboxFocusState state) {
1452 if (!extended_enabled()) 455 if (!extended_enabled())
1453 return; 456 return;
1454 457
1455 DCHECK(IsContentsFrom(instant_tab(), contents)); 458 DCHECK(IsContentsFrom(instant_tab(), contents));
1456 459
1457 // Do not add a default case in the switch block for the following reasons: 460 // Do not add a default case in the switch block for the following reasons:
1458 // (1) Explicitly handle the new states. If new states are added in the 461 // (1) Explicitly handle the new states. If new states are added in the
1459 // OmniboxFocusState, the compiler will warn the developer to handle the new 462 // OmniboxFocusState, the compiler will warn the developer to handle the new
(...skipping 22 matching lines...) Expand all
1482 content::PageTransition transition, 485 content::PageTransition transition,
1483 WindowOpenDisposition disposition, 486 WindowOpenDisposition disposition,
1484 bool is_search_type) { 487 bool is_search_type) {
1485 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf( 488 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1486 "NavigateToURL: url='%s'", url.spec().c_str())); 489 "NavigateToURL: url='%s'", url.spec().c_str()));
1487 490
1488 // TODO(samarth): handle case where contents are no longer "active" (e.g. user 491 // TODO(samarth): handle case where contents are no longer "active" (e.g. user
1489 // has switched tabs). 492 // has switched tabs).
1490 if (!extended_enabled()) 493 if (!extended_enabled())
1491 return; 494 return;
1492 if (overlay_) {
1493 HideOverlay();
1494 }
1495 495
1496 if (transition == content::PAGE_TRANSITION_AUTO_BOOKMARK) { 496 if (transition == content::PAGE_TRANSITION_AUTO_BOOKMARK) {
1497 content::RecordAction( 497 content::RecordAction(
1498 content::UserMetricsAction("InstantExtended.MostVisitedClicked")); 498 content::UserMetricsAction("InstantExtended.MostVisitedClicked"));
1499 } else { 499 } else {
1500 // Exclude navigation by Most Visited click and searches. 500 // Exclude navigation by Most Visited click and searches.
1501 if (!is_search_type) 501 if (!is_search_type)
1502 RecordNavigationHistogram(UsingLocalPage(), true, true); 502 RecordNavigationHistogram(UsingLocalPage(), true, true);
1503 } 503 }
1504 browser_->OpenURL(url, transition, disposition); 504 browser_->OpenURL(url, transition, disposition);
1505 } 505 }
1506 506
1507 void InstantController::OmniboxLostFocus(gfx::NativeView view_gaining_focus) {
1508 // If the overlay is showing custom NTP content, don't hide it, commit it
1509 // (no matter where the user clicked) or try to recreate it.
1510 if (model_.mode().is_ntp())
1511 return;
1512
1513 if (model_.mode().is_default()) {
1514 // If the overlay is not showing at all, recreate it if it's stale.
1515 ReloadOverlayIfStale();
1516 return;
1517 }
1518
1519 // The overlay is showing search suggestions. If GetOverlayContents() is NULL,
1520 // we are in the commit path. Don't do anything.
1521 if (!GetOverlayContents())
1522 return;
1523
1524 #if defined(OS_MACOSX)
1525 // TODO(sreeram): See if Mac really needs this special treatment.
1526 if (!overlay_->is_pointer_down_from_activate())
1527 HideOverlay();
1528 #else
1529 if (IsFullHeight(model_))
1530 CommitIfPossible(INSTANT_COMMIT_FOCUS_LOST);
1531 else if (!IsViewInContents(GetViewGainingFocus(view_gaining_focus),
1532 overlay_->contents()))
1533 HideOverlay();
1534 #endif
1535 }
1536
1537 std::string InstantController::GetLocalInstantURL() const { 507 std::string InstantController::GetLocalInstantURL() const {
1538 return chrome::GetLocalInstantURL(profile()).spec(); 508 return chrome::GetLocalInstantURL(profile()).spec();
1539 } 509 }
1540 510
1541 std::string InstantController::GetInstantURL() const { 511 std::string InstantController::GetInstantURL() const {
1542 if (extended_enabled() && 512 if (extended_enabled() && net::NetworkChangeNotifier::IsOffline())
1543 (use_local_page_only_ || net::NetworkChangeNotifier::IsOffline()))
1544 return GetLocalInstantURL(); 513 return GetLocalInstantURL();
1545 514
1546 const GURL instant_url = chrome::GetInstantURL(profile(), 515 const GURL instant_url = chrome::GetInstantURL(profile(),
1547 omnibox_bounds_.x()); 516 omnibox_bounds_.x());
1548 if (instant_url.is_valid()) 517 if (instant_url.is_valid())
1549 return instant_url.spec(); 518 return instant_url.spec();
1550 519
1551 // Only extended mode has a local fallback. 520 // Only extended mode has a local fallback.
1552 return extended_enabled() ? GetLocalInstantURL() : std::string(); 521 return extended_enabled() ? GetLocalInstantURL() : std::string();
1553 } 522 }
(...skipping 24 matching lines...) Expand all
1578 ntp_.reset(new InstantNTP(this, instant_url, 547 ntp_.reset(new InstantNTP(this, instant_url,
1579 browser_->profile()->IsOffTheRecord())); 548 browser_->profile()->IsOffTheRecord()));
1580 ntp_->InitContents(profile(), browser_->GetActiveWebContents(), 549 ntp_->InitContents(profile(), browser_->GetActiveWebContents(),
1581 base::Bind(&InstantController::ReloadStaleNTP, 550 base::Bind(&InstantController::ReloadStaleNTP,
1582 base::Unretained(this))); 551 base::Unretained(this)));
1583 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf( 552 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1584 "ResetNTP: instant_url='%s'", instant_url.c_str())); 553 "ResetNTP: instant_url='%s'", instant_url.c_str()));
1585 } 554 }
1586 555
1587 void InstantController::ReloadStaleNTP() { 556 void InstantController::ReloadStaleNTP() {
1588 ResetNTP(GetInstantURL()); 557 if (extended_enabled())
samarth 2013/07/02 21:14:15 Why add this? If anything, we should be killing th
Jered 2013/07/02 22:03:11 This is called from BrowserInstantController now w
558 ResetNTP(GetInstantURL());
1589 } 559 }
1590 560
1591 bool InstantController::ShouldSwitchToLocalNTP() const { 561 bool InstantController::ShouldSwitchToLocalNTP() const {
1592 if (!ntp()) 562 if (!ntp())
1593 return true; 563 return true;
1594 564
1595 // Assume users with Javascript disabled do not want the online experience. 565 // Assume users with Javascript disabled do not want the online experience.
1596 if (!IsJavascriptEnabled()) 566 if (!IsJavascriptEnabled())
1597 return true; 567 return true;
1598 568
1599 // Already a local page. Not calling IsLocal() because we want to distinguish 569 // Already a local page. Not calling IsLocal() because we want to distinguish
1600 // between the Google-specific and generic local NTP. 570 // between the Google-specific and generic local NTP.
1601 if (extended_enabled() && ntp()->instant_url() == GetLocalInstantURL()) 571 if (extended_enabled() && ntp()->instant_url() == GetLocalInstantURL())
1602 return false; 572 return false;
1603 573
1604 if (PageIsCurrent(ntp())) 574 if (PageIsCurrent(ntp()))
1605 return false; 575 return false;
1606 576
1607 // The preloaded NTP does not support instant yet. If we're not in startup, 577 // The preloaded NTP does not support instant yet. If we're not in startup,
1608 // always fall back to the local NTP. If we are in startup, use the local NTP 578 // always fall back to the local NTP. If we are in startup, use the local NTP
1609 // (unless the finch flag to use the remote NTP is set). 579 // (unless the finch flag to use the remote NTP is set).
1610 return !(InStartup() && chrome::ShouldPreferRemoteNTPOnStartup()); 580 return !(InStartup() && chrome::ShouldPreferRemoteNTPOnStartup());
1611 } 581 }
1612 582
1613 void InstantController::ResetOverlay(const std::string& instant_url) {
1614 HideInternal();
1615 overlay_.reset();
1616 }
1617
1618 InstantController::InstantFallbackReason
1619 InstantController::ShouldSwitchToLocalOverlay() const {
1620 if (!extended_enabled())
1621 return INSTANT_FALLBACK_NONE;
1622
1623 if (!overlay())
1624 return DetermineFallbackReason(NULL, std::string());
1625
1626 // Assume users with Javascript disabled do not want the online experience.
1627 if (!IsJavascriptEnabled())
1628 return INSTANT_FALLBACK_JAVASCRIPT_DISABLED;
1629
1630 if (overlay()->IsLocal())
1631 return INSTANT_FALLBACK_NONE;
1632
1633 bool page_is_current = PageIsCurrent(overlay());
1634 if (!page_is_current)
1635 return DetermineFallbackReason(overlay(), GetInstantURL());
1636
1637 return INSTANT_FALLBACK_NONE;
1638 }
1639
1640 void InstantController::ResetInstantTab() { 583 void InstantController::ResetInstantTab() {
1641 if (!search_mode_.is_origin_default()) { 584 if (!search_mode_.is_origin_default()) {
1642 content::WebContents* active_tab = browser_->GetActiveWebContents(); 585 content::WebContents* active_tab = browser_->GetActiveWebContents();
1643 if (!instant_tab_ || active_tab != instant_tab_->contents()) { 586 if (!instant_tab_ || active_tab != instant_tab_->contents()) {
1644 instant_tab_.reset( 587 instant_tab_.reset(
1645 new InstantTab(this, browser_->profile()->IsOffTheRecord())); 588 new InstantTab(this, browser_->profile()->IsOffTheRecord()));
1646 instant_tab_->Init(active_tab); 589 instant_tab_->Init(active_tab);
1647 UpdateInfoForInstantTab(); 590 UpdateInfoForInstantTab();
1648 use_tab_for_suggestions_ = true;
1649 } 591 }
1650
1651 // Hide the |overlay_| since we are now using |instant_tab_| instead.
1652 HideOverlay();
1653 } else { 592 } else {
1654 instant_tab_.reset(); 593 instant_tab_.reset();
1655 } 594 }
1656 } 595 }
1657 596
1658 void InstantController::UpdateInfoForInstantTab() { 597 void InstantController::UpdateInfoForInstantTab() {
1659 if (instant_tab_) { 598 if (instant_tab_) {
1660 instant_tab_->sender()->SetDisplayInstantResults(instant_enabled_);
1661 instant_tab_->sender()->SetOmniboxBounds(omnibox_bounds_); 599 instant_tab_->sender()->SetOmniboxBounds(omnibox_bounds_);
1662 600
1663 // Update theme details. 601 // Update theme details.
1664 InstantService* instant_service = GetInstantService(); 602 InstantService* instant_service = GetInstantService();
1665 if (instant_service) { 603 if (instant_service) {
1666 instant_service->UpdateThemeInfo(); 604 instant_service->UpdateThemeInfo();
1667 instant_service->UpdateMostVisitedItemsInfo(); 605 instant_service->UpdateMostVisitedItemsInfo();
1668 } 606 }
1669 607
1670 instant_tab_->InitializeFonts(); 608 instant_tab_->InitializeFonts();
1671 instant_tab_->InitializePromos(); 609 instant_tab_->InitializePromos();
1672 instant_tab_->sender()->FocusChanged(omnibox_focus_state_, 610 instant_tab_->sender()->FocusChanged(omnibox_focus_state_,
1673 omnibox_focus_change_reason_); 611 omnibox_focus_change_reason_);
1674 instant_tab_->sender()->SetInputInProgress(IsInputInProgress()); 612 instant_tab_->sender()->SetInputInProgress(IsInputInProgress());
1675 } 613 }
1676 } 614 }
1677 615
1678 bool InstantController::IsInputInProgress() const { 616 bool InstantController::IsInputInProgress() const {
1679 return !search_mode_.is_ntp() && 617 return !search_mode_.is_ntp() &&
1680 omnibox_focus_state_ == OMNIBOX_FOCUS_VISIBLE; 618 omnibox_focus_state_ == OMNIBOX_FOCUS_VISIBLE;
1681 } 619 }
1682 620
1683 void InstantController::HideOverlay() {
1684 HideInternal();
1685 ReloadOverlayIfStale();
1686 }
1687
1688 void InstantController::HideInternal() {
1689 LOG_INSTANT_DEBUG_EVENT(this, "Hide");
1690
1691 // If GetOverlayContents() returns NULL, either we're already in the desired
1692 // MODE_DEFAULT state, or we're in the commit path. For the latter, don't
1693 // change the state just yet; else we may hide the overlay unnecessarily.
1694 // Instead, the state will be set correctly after the commit is done.
1695 if (GetOverlayContents()) {
1696 model_.SetOverlayState(SearchMode(), 0, INSTANT_SIZE_PERCENT);
1697 allow_overlay_to_show_search_suggestions_ = false;
1698
1699 // Send a message asking the overlay to clear out old results.
1700 overlay_->Update(string16(), 0, 0, true);
1701 }
1702
1703 // Clear the first interaction timestamp for later use.
1704 first_interaction_time_ = base::Time();
1705 first_interaction_time_recorded_ = false;
1706
1707 if (instant_tab_)
1708 use_tab_for_suggestions_ = true;
1709 }
1710
1711 void InstantController::ShowOverlay(int height, InstantSizeUnits units) {
1712 // Nothing to see here.
1713 if (!overlay_)
1714 return;
1715
1716 // If we are on a committed search results page, the |overlay_| is not in use.
1717 if (UseTabForSuggestions())
1718 return;
1719
1720 LOG_INSTANT_DEBUG_EVENT(this, base::StringPrintf(
1721 "Show: height=%d units=%d", height, units));
1722
1723 // Must have updated omnibox after the last HideOverlay() to show suggestions.
1724 if (!allow_overlay_to_show_search_suggestions_)
1725 return;
1726
1727 // The page is trying to hide itself. Hide explicitly (i.e., don't use
1728 // HideOverlay()) so that it can change its mind.
1729 if (height == 0) {
1730 model_.SetOverlayState(SearchMode(), 0, INSTANT_SIZE_PERCENT);
1731 if (instant_tab_)
1732 use_tab_for_suggestions_ = true;
1733 return;
1734 }
1735
1736 // Show at 100% height except in the following cases:
1737 // - The local overlay (omnibox popup) is being loaded.
1738 // - Instant is disabled. The page needs to be able to show only a dropdown.
1739 // - The page is over a website other than search or an NTP, and is not
1740 // already showing at 100% height.
1741 if (overlay_->IsLocal() || !instant_enabled_ ||
1742 (search_mode_.is_origin_default() && !IsFullHeight(model_)))
1743 model_.SetOverlayState(search_mode_, height, units);
1744 else
1745 model_.SetOverlayState(search_mode_, 100, INSTANT_SIZE_PERCENT);
1746
1747 // If the overlay is being shown at full height and the omnibox is not
1748 // focused, commit right away.
1749 if (IsFullHeight(model_) && omnibox_focus_state_ == OMNIBOX_FOCUS_NONE)
1750 CommitIfPossible(INSTANT_COMMIT_FOCUS_LOST);
1751 }
1752
1753 void InstantController::SendPopupBoundsToPage() {
1754 if (last_popup_bounds_ == popup_bounds_ || !overlay_ ||
1755 overlay_->is_pointer_down_from_activate())
1756 return;
1757
1758 last_popup_bounds_ = popup_bounds_;
1759 gfx::Rect overlay_bounds = browser_->GetInstantBounds();
1760 gfx::Rect intersection = gfx::IntersectRects(popup_bounds_, overlay_bounds);
1761
1762 // Translate into window coordinates.
1763 if (!intersection.IsEmpty()) {
1764 intersection.Offset(-overlay_bounds.origin().x(),
1765 -overlay_bounds.origin().y());
1766 }
1767
1768 // In the current Chrome UI, these must always be true so they sanity check
1769 // the above operations. In a future UI, these may be removed or adjusted.
1770 // There is no point in sanity-checking |intersection.y()| because the omnibox
1771 // can be placed anywhere vertically relative to the overlay (for example, in
1772 // Mac fullscreen mode, the omnibox is fully enclosed by the overlay bounds).
1773 DCHECK_LE(0, intersection.x());
1774 DCHECK_LE(0, intersection.width());
1775 DCHECK_LE(0, intersection.height());
1776
1777 overlay_->sender()->SetPopupBounds(intersection);
1778 }
1779
1780
1781
1782 bool InstantController::FixSuggestion(InstantSuggestion* suggestion) const {
1783 // We only accept suggestions if the user has typed text. If the user is
1784 // arrowing up/down (|last_user_text_| is empty), we reject suggestions.
1785 if (last_user_text_.empty())
1786 return false;
1787
1788 // If the page is trying to set inline autocompletion in verbatim mode,
1789 // instead try suggesting the exact omnibox text. This makes the omnibox
1790 // interpret user text as an URL if possible while preventing unwanted
1791 // autocompletion during backspacing.
1792 if (suggestion->behavior == INSTANT_COMPLETE_NOW && last_verbatim_)
1793 suggestion->text = last_omnibox_text_;
1794
1795 // Suggestion text should be a full URL for URL suggestions, or the
1796 // completion of a query for query suggestions.
1797 if (suggestion->type == INSTANT_SUGGESTION_URL) {
1798 // If the suggestion is not a valid URL, perhaps it's something like
1799 // "foo.com". Try prefixing "http://". If it still isn't valid, drop it.
1800 if (!GURL(suggestion->text).is_valid()) {
1801 suggestion->text.insert(0, ASCIIToUTF16("http://"));
1802 if (!GURL(suggestion->text).is_valid())
1803 return false;
1804 }
1805
1806 // URL suggestions are only accepted if the query for which the suggestion
1807 // was generated is the same as |last_user_text_|.
1808 //
1809 // Any other URL suggestions--in particular suggestions for old user_text
1810 // lagging behind a slow IPC--are ignored. See crbug.com/181589.
1811 //
1812 // TODO(samarth): Accept stale suggestions if they would be accepted by
1813 // SearchProvider as an inlinable suggestion. http://crbug.com/191656.
1814 return suggestion->query == last_user_text_;
1815 }
1816
1817 // We use |last_user_text_| because |last_omnibox_text| may contain text from
1818 // a previous URL suggestion at this point.
1819 if (suggestion->type == INSTANT_SUGGESTION_SEARCH) {
1820 if (StartsWith(suggestion->text, last_user_text_, true)) {
1821 // The user typed an exact prefix of the suggestion.
1822 suggestion->text.erase(0, last_user_text_.size());
1823 return true;
1824 } else if (NormalizeAndStripPrefix(&suggestion->text, last_user_text_)) {
1825 // Unicode normalize and case-fold the user text and suggestion. If the
1826 // user text is a prefix, suggest the normalized, case-folded completion
1827 // for instance, if the user types 'i' and the suggestion is 'INSTANT',
1828 // suggest 'nstant'. Otherwise, the user text really isn't a prefix, so
1829 // suggest nothing.
1830 // TODO(samarth|jered): revisit this logic. http://crbug.com/196572.
1831 return true;
1832 }
1833 }
1834
1835 return false;
1836 }
1837
1838 bool InstantController::UsingLocalPage() const { 621 bool InstantController::UsingLocalPage() const {
1839 return (UseTabForSuggestions() && instant_tab_->IsLocal()) || 622 return instant_tab_ && instant_tab_->IsLocal();
1840 (!UseTabForSuggestions() && overlay_ && overlay_->IsLocal());
1841 }
1842
1843 bool InstantController::UseTabForSuggestions() const {
1844 return instant_tab_ && use_tab_for_suggestions_;
1845 } 623 }
1846 624
1847 void InstantController::RedirectToLocalNTP(content::WebContents* contents) { 625 void InstantController::RedirectToLocalNTP(content::WebContents* contents) {
1848 contents->GetController().LoadURL( 626 contents->GetController().LoadURL(
1849 chrome::GetLocalInstantURL(browser_->profile()), 627 chrome::GetLocalInstantURL(browser_->profile()),
1850 content::Referrer(), 628 content::Referrer(),
1851 content::PAGE_TRANSITION_SERVER_REDIRECT, 629 content::PAGE_TRANSITION_SERVER_REDIRECT,
1852 std::string()); // No extra headers. 630 std::string()); // No extra headers.
1853 // TODO(dcblack): Remove extraneous history entry caused by 404s. 631 // TODO(dcblack): Remove extraneous history entry caused by 404s.
1854 // Note that the base case of a 204 being returned doesn't push a history 632 // Note that the base case of a 204 being returned doesn't push a history
1855 // entry. 633 // entry.
1856 } 634 }
1857 635
1858 void InstantController::PopulateInstantAutocompleteResultFromMatch(
1859 const AutocompleteMatch& match, size_t autocomplete_match_index,
1860 InstantAutocompleteResult* result) {
1861 DCHECK(result);
1862 result->provider = UTF8ToUTF16(match.provider->GetName());
1863 result->type = match.type;
1864 result->description = match.description;
1865 result->destination_url = UTF8ToUTF16(match.destination_url.spec());
1866
1867 // Setting the search_query field tells the Instant page to treat the
1868 // suggestion as a query.
1869 if (AutocompleteMatch::IsSearchType(match.type))
1870 result->search_query = match.contents;
1871
1872 result->transition = match.transition;
1873 result->relevance = match.relevance;
1874 result->autocomplete_match_index = autocomplete_match_index;
1875
1876 DVLOG(1) << " " << result->relevance << " "
1877 << UTF8ToUTF16(AutocompleteMatchType::ToString(result->type)) << " "
1878 << result->provider << " " << result->destination_url << " '"
1879 << result->description << "' '" << result->search_query << "' "
1880 << result->transition << " " << result->autocomplete_match_index;
1881 }
1882
1883 bool InstantController::IsJavascriptEnabled() const { 636 bool InstantController::IsJavascriptEnabled() const {
1884 GURL instant_url(GetInstantURL()); 637 GURL instant_url(GetInstantURL());
1885 GURL origin(instant_url.GetOrigin()); 638 GURL origin(instant_url.GetOrigin());
1886 ContentSetting js_setting = profile()->GetHostContentSettingsMap()-> 639 ContentSetting js_setting = profile()->GetHostContentSettingsMap()->
1887 GetContentSetting(origin, origin, CONTENT_SETTINGS_TYPE_JAVASCRIPT, 640 GetContentSetting(origin, origin, CONTENT_SETTINGS_TYPE_JAVASCRIPT,
1888 NO_RESOURCE_IDENTIFIER); 641 NO_RESOURCE_IDENTIFIER);
1889 // Javascript can be disabled either in content settings or via a WebKit 642 // Javascript can be disabled either in content settings or via a WebKit
1890 // preference, so check both. Disabling it through the Settings page affects 643 // preference, so check both. Disabling it through the Settings page affects
1891 // content settings. I'm not sure how to disable the WebKit preference, but 644 // content settings. I'm not sure how to disable the WebKit preference, but
1892 // it's theoretically possible some users have it off. 645 // it's theoretically possible some users have it off.
1893 bool js_content_enabled = 646 bool js_content_enabled =
1894 js_setting == CONTENT_SETTING_DEFAULT || 647 js_setting == CONTENT_SETTING_DEFAULT ||
1895 js_setting == CONTENT_SETTING_ALLOW; 648 js_setting == CONTENT_SETTING_ALLOW;
1896 bool js_webkit_enabled = profile()->GetPrefs()->GetBoolean( 649 bool js_webkit_enabled = profile()->GetPrefs()->GetBoolean(
1897 prefs::kWebKitJavascriptEnabled); 650 prefs::kWebKitJavascriptEnabled);
1898 return js_content_enabled && js_webkit_enabled; 651 return js_content_enabled && js_webkit_enabled;
1899 } 652 }
1900 653
1901 bool InstantController::InStartup() const { 654 bool InstantController::InStartup() const {
1902 // TODO(shishir): This is not completely reliable. Find a better way to detect 655 // TODO(shishir): This is not completely reliable. Find a better way to detect
1903 // startup time. 656 // startup time.
1904 return !browser_->GetActiveWebContents(); 657 return !browser_->GetActiveWebContents();
1905 } 658 }
1906 659
1907 InstantService* InstantController::GetInstantService() const { 660 InstantService* InstantController::GetInstantService() const {
1908 return InstantServiceFactory::GetForProfile(profile()); 661 return InstantServiceFactory::GetForProfile(profile());
1909 } 662 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698