instant_controller.cc revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
1// Copyright (c) 2011 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/browser/instant/instant_controller.h"
6
7#include "build/build_config.h"
8#include "base/command_line.h"
9#include "base/message_loop.h"
10#include "base/metrics/histogram.h"
11#include "chrome/browser/autocomplete/autocomplete_match.h"
12#include "chrome/browser/instant/instant_delegate.h"
13#include "chrome/browser/instant/instant_loader.h"
14#include "chrome/browser/instant/instant_loader_manager.h"
15#include "chrome/browser/instant/promo_counter.h"
16#include "chrome/browser/platform_util.h"
17#include "chrome/browser/prefs/pref_service.h"
18#include "chrome/browser/profiles/profile.h"
19#include "chrome/browser/renderer_host/render_widget_host_view.h"
20#include "chrome/browser/search_engines/template_url.h"
21#include "chrome/browser/search_engines/template_url_model.h"
22#include "chrome/browser/tab_contents/tab_contents.h"
23#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
24#include "chrome/common/chrome_switches.h"
25#include "chrome/common/notification_service.h"
26#include "chrome/common/pref_names.h"
27#include "chrome/common/url_constants.h"
28
29// Number of ms to delay between loading urls.
30static const int kUpdateDelayMS = 200;
31
32// static
33InstantController::HostBlacklist* InstantController::host_blacklist_ = NULL;
34
35InstantController::InstantController(Profile* profile,
36                                     InstantDelegate* delegate)
37    : delegate_(delegate),
38      tab_contents_(NULL),
39      is_active_(false),
40      is_displayable_(false),
41      commit_on_mouse_up_(false),
42      last_transition_type_(PageTransition::LINK),
43      ALLOW_THIS_IN_INITIALIZER_LIST(destroy_factory_(this)) {
44  PrefService* service = profile->GetPrefs();
45  if (service) {
46    // kInstantWasEnabledOnce was added after instant, set it now to make sure
47    // it is correctly set.
48    service->SetBoolean(prefs::kInstantEnabledOnce, true);
49  }
50}
51
52InstantController::~InstantController() {
53}
54
55// static
56void InstantController::RegisterUserPrefs(PrefService* prefs) {
57  prefs->RegisterBooleanPref(prefs::kInstantConfirmDialogShown, false);
58  prefs->RegisterBooleanPref(prefs::kInstantEnabled, false);
59  prefs->RegisterBooleanPref(prefs::kInstantEnabledOnce, false);
60  prefs->RegisterInt64Pref(prefs::kInstantEnabledTime, false);
61  PromoCounter::RegisterUserPrefs(prefs, prefs::kInstantPromo);
62}
63
64// static
65void InstantController::RecordMetrics(Profile* profile) {
66  if (!IsEnabled(profile))
67    return;
68
69  PrefService* service = profile->GetPrefs();
70  if (service) {
71    int64 enable_time = service->GetInt64(prefs::kInstantEnabledTime);
72    if (!enable_time) {
73      service->SetInt64(prefs::kInstantEnabledTime,
74                        base::Time::Now().ToInternalValue());
75    } else {
76      base::TimeDelta delta =
77          base::Time::Now() - base::Time::FromInternalValue(enable_time);
78      // Histogram from 1 hour to 30 days.
79      UMA_HISTOGRAM_CUSTOM_COUNTS("Instant.EnabledTime.Predictive",
80                                  delta.InHours(), 1, 30 * 24, 50);
81    }
82  }
83}
84
85// static
86bool InstantController::IsEnabled(Profile* profile) {
87  PrefService* prefs = profile->GetPrefs();
88  return prefs->GetBoolean(prefs::kInstantEnabled);
89}
90
91// static
92void InstantController::Enable(Profile* profile) {
93  PromoCounter* promo_counter = profile->GetInstantPromoCounter();
94  if (promo_counter)
95    promo_counter->Hide();
96
97  PrefService* service = profile->GetPrefs();
98  if (!service)
99    return;
100
101  service->SetBoolean(prefs::kInstantEnabled, true);
102  service->SetBoolean(prefs::kInstantConfirmDialogShown, true);
103  service->SetInt64(prefs::kInstantEnabledTime,
104                    base::Time::Now().ToInternalValue());
105  service->SetBoolean(prefs::kInstantEnabledOnce, true);
106}
107
108// static
109void InstantController::Disable(Profile* profile) {
110  PrefService* service = profile->GetPrefs();
111  if (!service || !IsEnabled(profile))
112    return;
113
114  int64 enable_time = service->GetInt64(prefs::kInstantEnabledTime);
115  if (enable_time) {
116    base::TimeDelta delta =
117        base::Time::Now() - base::Time::FromInternalValue(enable_time);
118    // Histogram from 1 minute to 10 days.
119    UMA_HISTOGRAM_CUSTOM_COUNTS("Instant.TimeToDisable.Predictive",
120                                delta.InMinutes(), 1, 60 * 24 * 10, 50);
121  }
122
123  service->SetBoolean(prefs::kInstantEnabled, false);
124}
125
126// static
127bool InstantController::CommitIfCurrent(InstantController* controller) {
128  if (controller && controller->IsCurrent()) {
129    controller->CommitCurrentPreview(INSTANT_COMMIT_PRESSED_ENTER);
130    return true;
131  }
132  return false;
133}
134
135void InstantController::Update(TabContentsWrapper* tab_contents,
136                               const AutocompleteMatch& match,
137                               const string16& user_text,
138                               bool verbatim,
139                               string16* suggested_text) {
140  suggested_text->clear();
141
142  if (tab_contents != tab_contents_)
143    DestroyPreviewContents();
144
145  const GURL& url = match.destination_url;
146  tab_contents_ = tab_contents;
147  commit_on_mouse_up_ = false;
148  last_transition_type_ = match.transition;
149  const TemplateURL* template_url = NULL;
150
151  if (url.is_empty() || !url.is_valid()) {
152    // Assume we were invoked with GURL() and should destroy all.
153    DestroyPreviewContents();
154    return;
155  }
156
157  if (!ShouldShowPreviewFor(match, &template_url)) {
158    DestroyAndLeaveActive();
159    return;
160  }
161
162  if (!loader_manager_.get())
163    loader_manager_.reset(new InstantLoaderManager(this));
164
165  if (!is_active_) {
166    is_active_ = true;
167    delegate_->PrepareForInstant();
168  }
169
170  TemplateURLID template_url_id = template_url ? template_url->id() : 0;
171  // Verbatim only makes sense if the search engines supports instant.
172  bool real_verbatim = template_url_id ? verbatim : false;
173
174  if (ShouldUpdateNow(template_url_id, match.destination_url)) {
175    UpdateLoader(template_url, match.destination_url, match.transition,
176                 user_text, real_verbatim, suggested_text);
177  } else {
178    ScheduleUpdate(match.destination_url);
179  }
180
181  NotificationService::current()->Notify(
182      NotificationType::INSTANT_CONTROLLER_UPDATED,
183      Source<InstantController>(this),
184      NotificationService::NoDetails());
185}
186
187void InstantController::SetOmniboxBounds(const gfx::Rect& bounds) {
188  if (omnibox_bounds_ == bounds)
189    return;
190
191  // Always track the omnibox bounds. That way if Update is later invoked the
192  // bounds are in sync.
193  omnibox_bounds_ = bounds;
194  if (loader_manager_.get()) {
195    if (loader_manager_->current_loader())
196      loader_manager_->current_loader()->SetOmniboxBounds(bounds);
197    if (loader_manager_->pending_loader())
198      loader_manager_->pending_loader()->SetOmniboxBounds(bounds);
199  }
200}
201
202void InstantController::DestroyPreviewContents() {
203  if (!loader_manager_.get()) {
204    // We're not showing anything, nothing to do.
205    return;
206  }
207
208  // ReleasePreviewContents sets is_active_ to false, but we need to set it
209  // before notifying the delegate, otherwise if the delegate asks for the state
210  // we'll still be active.
211  is_active_ = false;
212  delegate_->HideInstant();
213  delete ReleasePreviewContents(INSTANT_COMMIT_DESTROY);
214}
215
216bool InstantController::IsCurrent() {
217  return loader_manager_.get() && loader_manager_->active_loader() &&
218      loader_manager_->active_loader()->ready() && !update_timer_.IsRunning();
219}
220
221void InstantController::CommitCurrentPreview(InstantCommitType type) {
222  DCHECK(loader_manager_.get());
223  DCHECK(loader_manager_->current_loader());
224  TabContentsWrapper* tab = ReleasePreviewContents(type);
225  delegate_->CommitInstant(tab);
226  CompleteRelease(tab->tab_contents());
227}
228
229void InstantController::SetCommitOnMouseUp() {
230  commit_on_mouse_up_ = true;
231}
232
233bool InstantController::IsMouseDownFromActivate() {
234  DCHECK(loader_manager_.get());
235  DCHECK(loader_manager_->current_loader());
236  return loader_manager_->current_loader()->IsMouseDownFromActivate();
237}
238
239void InstantController::OnAutocompleteLostFocus(
240    gfx::NativeView view_gaining_focus) {
241  if (!is_active() || !GetPreviewContents()) {
242    DestroyPreviewContents();
243    return;
244  }
245
246  RenderWidgetHostView* rwhv =
247      GetPreviewContents()->tab_contents()->GetRenderWidgetHostView();
248  if (!view_gaining_focus || !rwhv) {
249    DestroyPreviewContents();
250    return;
251  }
252
253  gfx::NativeView tab_view =
254      GetPreviewContents()->tab_contents()->GetNativeView();
255  // Focus is going to the renderer.
256  if (rwhv->GetNativeView() == view_gaining_focus ||
257      tab_view == view_gaining_focus) {
258    if (!IsMouseDownFromActivate()) {
259      // If the mouse is not down, focus is not going to the renderer. Someone
260      // else moved focus and we shouldn't commit.
261      DestroyPreviewContents();
262      return;
263    }
264
265    if (IsShowingInstant()) {
266      // We're showing instant results. As instant results may shift when
267      // committing we commit on the mouse up. This way a slow click still
268      // works fine.
269      SetCommitOnMouseUp();
270      return;
271    }
272
273    CommitCurrentPreview(INSTANT_COMMIT_FOCUS_LOST);
274    return;
275  }
276
277  // Walk up the view hierarchy. If the view gaining focus is a subview of the
278  // TabContents view (such as a windowed plugin or http auth dialog), we want
279  // to keep the preview contents. Otherwise, focus has gone somewhere else,
280  // such as the JS inspector, and we want to cancel the preview.
281  gfx::NativeView view_gaining_focus_ancestor = view_gaining_focus;
282  while (view_gaining_focus_ancestor &&
283         view_gaining_focus_ancestor != tab_view) {
284    view_gaining_focus_ancestor =
285        platform_util::GetParent(view_gaining_focus_ancestor);
286  }
287
288  if (view_gaining_focus_ancestor) {
289    CommitCurrentPreview(INSTANT_COMMIT_FOCUS_LOST);
290    return;
291  }
292
293  DestroyPreviewContents();
294}
295
296TabContentsWrapper* InstantController::ReleasePreviewContents(
297    InstantCommitType type) {
298  if (!loader_manager_.get())
299    return NULL;
300
301  // Loader may be null if the url blacklisted instant.
302  scoped_ptr<InstantLoader> loader;
303  if (loader_manager_->current_loader())
304    loader.reset(loader_manager_->ReleaseCurrentLoader());
305  TabContentsWrapper* tab = loader.get() ?
306      loader->ReleasePreviewContents(type) : NULL;
307
308  ClearBlacklist();
309  is_active_ = false;
310  is_displayable_ = false;
311  commit_on_mouse_up_ = false;
312  omnibox_bounds_ = gfx::Rect();
313  loader_manager_.reset();
314  update_timer_.Stop();
315  return tab;
316}
317
318void InstantController::CompleteRelease(TabContents* tab) {
319  tab->SetAllContentsBlocked(false);
320}
321
322TabContentsWrapper* InstantController::GetPreviewContents() {
323  return loader_manager_.get() && loader_manager_->current_loader() ?
324      loader_manager_->current_loader()->preview_contents() : NULL;
325}
326
327bool InstantController::IsShowingInstant() {
328  return loader_manager_.get() && loader_manager_->current_loader() &&
329      loader_manager_->current_loader()->is_showing_instant();
330}
331
332bool InstantController::MightSupportInstant() {
333  return loader_manager_.get() && loader_manager_->active_loader() &&
334      loader_manager_->active_loader()->is_showing_instant();
335}
336
337GURL InstantController::GetCurrentURL() {
338  return loader_manager_.get() && loader_manager_->active_loader() ?
339      loader_manager_->active_loader()->url() : GURL();
340}
341
342void InstantController::ShowInstantLoader(InstantLoader* loader) {
343  DCHECK(loader_manager_.get());
344  if (loader_manager_->current_loader() == loader) {
345    is_displayable_ = true;
346    delegate_->ShowInstant(loader->preview_contents());
347  } else if (loader_manager_->pending_loader() == loader) {
348    scoped_ptr<InstantLoader> old_loader;
349    loader_manager_->MakePendingCurrent(&old_loader);
350    delegate_->ShowInstant(loader->preview_contents());
351  } else {
352    // The loader supports instant but isn't active yet. Nothing to do.
353  }
354
355  NotificationService::current()->Notify(
356      NotificationType::INSTANT_CONTROLLER_SHOWN,
357      Source<InstantController>(this),
358      NotificationService::NoDetails());
359}
360
361void InstantController::SetSuggestedTextFor(InstantLoader* loader,
362                                            const string16& text) {
363  if (loader_manager_->current_loader() == loader)
364    delegate_->SetSuggestedText(text);
365}
366
367gfx::Rect InstantController::GetInstantBounds() {
368  return delegate_->GetInstantBounds();
369}
370
371bool InstantController::ShouldCommitInstantOnMouseUp() {
372  return commit_on_mouse_up_;
373}
374
375void InstantController::CommitInstantLoader(InstantLoader* loader) {
376  if (loader_manager_.get() && loader_manager_->current_loader() == loader) {
377    CommitCurrentPreview(INSTANT_COMMIT_FOCUS_LOST);
378  } else {
379    // This can happen if the mouse was down, we swapped out the preview and
380    // the mouse was released. Generally this shouldn't happen, but if it does
381    // revert.
382    DestroyPreviewContents();
383  }
384}
385
386void InstantController::InstantLoaderDoesntSupportInstant(
387    InstantLoader* loader) {
388  DCHECK(!loader->ready());  // We better not be showing this loader.
389  DCHECK(loader->template_url_id());
390
391  VLOG(1) << "provider does not support instant";
392
393  // Don't attempt to use instant for this search engine again.
394  BlacklistFromInstant(loader->template_url_id());
395
396  if (loader_manager_->active_loader() == loader) {
397    // The loader is active, hide all.
398    DestroyAndLeaveActive();
399  } else {
400    if (loader_manager_->current_loader() == loader && is_displayable_) {
401      // There is a pending loader and we're active. Hide the preview. When then
402      // pending loader finishes loading we'll notify the delegate to show.
403      DCHECK(loader_manager_->pending_loader());
404      is_displayable_ = false;
405      delegate_->HideInstant();
406    }
407    loader_manager_->DestroyLoader(loader);
408  }
409}
410
411void InstantController::AddToBlacklist(InstantLoader* loader, const GURL& url) {
412  std::string host = url.host();
413  if (host.empty())
414    return;
415
416  if (!host_blacklist_)
417    host_blacklist_ = new HostBlacklist;
418  host_blacklist_->insert(host);
419
420  if (!loader_manager_.get())
421    return;
422
423  // Because of the state of the stack we can't destroy the loader now.
424  ScheduleDestroy(loader);
425
426  loader_manager_->ReleaseLoader(loader);
427  if (is_displayable_ &&
428      (!loader_manager_->active_loader() ||
429       !loader_manager_->current_loader()->ready())) {
430    // Hide instant. When the pending loader finishes loading we'll go active
431    // again.
432    is_displayable_ = false;
433    delegate_->HideInstant();
434  }
435}
436
437void InstantController::DestroyAndLeaveActive() {
438  is_displayable_ = false;
439  commit_on_mouse_up_ = false;
440  delegate_->HideInstant();
441
442  loader_manager_.reset(new InstantLoaderManager(this));
443  update_timer_.Stop();
444}
445
446TabContentsWrapper* InstantController::GetPendingPreviewContents() {
447  return loader_manager_.get() && loader_manager_->pending_loader() ?
448      loader_manager_->pending_loader()->preview_contents() : NULL;
449}
450
451bool InstantController::ShouldUpdateNow(TemplateURLID instant_id,
452                                        const GURL& url) {
453  DCHECK(loader_manager_.get());
454
455  if (instant_id) {
456    // Update sites that support instant immediately, they can do their own
457    // throttling.
458    return true;
459  }
460
461  if (url.SchemeIsFile())
462    return true;  // File urls should load quickly, so don't delay loading them.
463
464  if (loader_manager_->WillUpateChangeActiveLoader(instant_id)) {
465    // If Update would change loaders, update now. This indicates transitioning
466    // from an instant to non-instant loader.
467    return true;
468  }
469
470  InstantLoader* active_loader = loader_manager_->active_loader();
471  // WillUpateChangeActiveLoader should return true if no active loader, so
472  // we know there will be an active loader if we get here.
473  DCHECK(active_loader);
474  // Immediately update if the url is the same (which should result in nothing
475  // happening) or the hosts differ, otherwise we'll delay the update.
476  return (active_loader->url() == url) ||
477      (active_loader->url().host() != url.host());
478}
479
480void InstantController::ScheduleUpdate(const GURL& url) {
481  scheduled_url_ = url;
482
483  if (update_timer_.IsRunning())
484    update_timer_.Stop();
485  update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateDelayMS),
486                      this, &InstantController::ProcessScheduledUpdate);
487}
488
489void InstantController::ProcessScheduledUpdate() {
490  DCHECK(loader_manager_.get());
491
492  // We only delay loading of sites that don't support instant, so we can ignore
493  // suggested_text here.
494  string16 suggested_text;
495  UpdateLoader(NULL, scheduled_url_, last_transition_type_, string16(), false,
496               &suggested_text);
497}
498
499void InstantController::UpdateLoader(const TemplateURL* template_url,
500                                     const GURL& url,
501                                     PageTransition::Type transition_type,
502                                     const string16& user_text,
503                                     bool verbatim,
504                                     string16* suggested_text) {
505  update_timer_.Stop();
506
507  InstantLoader* old_loader = loader_manager_->current_loader();
508  scoped_ptr<InstantLoader> owned_loader;
509  TemplateURLID template_url_id = template_url ? template_url->id() : 0;
510  InstantLoader* new_loader =
511      loader_manager_->UpdateLoader(template_url_id, &owned_loader);
512
513  new_loader->SetOmniboxBounds(omnibox_bounds_);
514  new_loader->Update(tab_contents_, template_url, url, transition_type,
515                     user_text, verbatim, suggested_text);
516  if (old_loader != new_loader && new_loader->ready())
517    delegate_->ShowInstant(new_loader->preview_contents());
518}
519
520bool InstantController::ShouldShowPreviewFor(const AutocompleteMatch& match,
521                                             const TemplateURL** template_url) {
522  const TemplateURL* t_url = GetTemplateURL(match);
523  if (t_url) {
524    if (!t_url->id() ||
525        !t_url->instant_url() ||
526        IsBlacklistedFromInstant(t_url->id()) ||
527        !t_url->instant_url()->SupportsReplacement()) {
528      // To avoid extra load on other search engines we only enable previews if
529      // they support the instant API.
530      return false;
531    }
532  }
533  *template_url = t_url;
534
535  if (match.destination_url.SchemeIs(chrome::kJavaScriptScheme))
536    return false;
537
538  // Extension keywords don't have a real destionation URL.
539  if (match.template_url && match.template_url->IsExtensionKeyword())
540    return false;
541
542  // Was the host blacklisted?
543  if (host_blacklist_ && host_blacklist_->count(match.destination_url.host()))
544    return false;
545
546  return true;
547}
548
549void InstantController::BlacklistFromInstant(TemplateURLID id) {
550  blacklisted_ids_.insert(id);
551}
552
553bool InstantController::IsBlacklistedFromInstant(TemplateURLID id) {
554  return blacklisted_ids_.count(id) > 0;
555}
556
557void InstantController::ClearBlacklist() {
558  blacklisted_ids_.clear();
559}
560
561void InstantController::ScheduleDestroy(InstantLoader* loader) {
562  loaders_to_destroy_.push_back(loader);
563  if (destroy_factory_.empty()) {
564    MessageLoop::current()->PostTask(
565        FROM_HERE, destroy_factory_.NewRunnableMethod(
566            &InstantController::DestroyLoaders));
567  }
568}
569
570void InstantController::DestroyLoaders() {
571  loaders_to_destroy_.reset();
572}
573
574const TemplateURL* InstantController::GetTemplateURL(
575    const AutocompleteMatch& match) {
576  const TemplateURL* template_url = match.template_url;
577  if (match.type == AutocompleteMatch::SEARCH_WHAT_YOU_TYPED ||
578      match.type == AutocompleteMatch::SEARCH_HISTORY ||
579      match.type == AutocompleteMatch::SEARCH_SUGGEST) {
580    TemplateURLModel* model = tab_contents_->profile()->GetTemplateURLModel();
581    template_url = model ? model->GetDefaultSearchProvider() : NULL;
582  }
583  return template_url;
584}
585