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

Side by Side Diff: chrome/browser/instant/instant_loader.cc

Issue 10732002: Upstream rewrite of Instant. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Replace id with instant_url. Created 8 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 (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 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/instant/instant_loader.h" 5 #include "chrome/browser/instant/instant_loader.h"
6 6
7 #include <algorithm> 7 #include "base/string_util.h"
8 #include <string>
9 #include <utility>
10 #include <vector>
11
12 #include "base/command_line.h"
13 #include "base/i18n/case_conversion.h"
14 #include "base/metrics/histogram.h"
15 #include "base/string_number_conversions.h"
16 #include "base/timer.h"
17 #include "base/utf_string_conversions.h" 8 #include "base/utf_string_conversions.h"
18 #include "base/values.h" 9 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
19 #include "chrome/browser/favicon/favicon_service.h"
20 #include "chrome/browser/history/history_marshaling.h"
21 #include "chrome/browser/history/history_tab_helper.h"
22 #include "chrome/browser/instant/instant_loader_delegate.h" 10 #include "chrome/browser/instant/instant_loader_delegate.h"
23 #include "chrome/browser/profiles/profile.h" 11 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/search_engines/template_url.h"
25 #include "chrome/browser/tab_contents/thumbnail_generator.h" 12 #include "chrome/browser/tab_contents/thumbnail_generator.h"
26 #include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h" 13 #include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h"
27 #include "chrome/browser/ui/constrained_window_tab_helper.h" 14 #include "chrome/browser/ui/constrained_window_tab_helper.h"
28 #include "chrome/browser/ui/constrained_window_tab_helper_delegate.h" 15 #include "chrome/browser/ui/constrained_window_tab_helper_delegate.h"
29 #include "chrome/browser/ui/tab_contents/core_tab_helper.h" 16 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
30 #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h" 17 #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h"
31 #include "chrome/browser/ui/tab_contents/tab_contents.h" 18 #include "chrome/browser/ui/tab_contents/tab_contents.h"
32 #include "chrome/common/chrome_notification_types.h" 19 #include "chrome/common/chrome_notification_types.h"
33 #include "chrome/common/chrome_switches.h"
34 #include "chrome/common/render_messages.h" 20 #include "chrome/common/render_messages.h"
35 #include "content/public/browser/favicon_status.h"
36 #include "content/public/browser/navigation_controller.h" 21 #include "content/public/browser/navigation_controller.h"
37 #include "content/public/browser/navigation_details.h"
38 #include "content/public/browser/navigation_entry.h" 22 #include "content/public/browser/navigation_entry.h"
39 #include "content/public/browser/notification_details.h" 23 #include "content/public/browser/notification_details.h"
40 #include "content/public/browser/notification_observer.h"
41 #include "content/public/browser/notification_registrar.h"
42 #include "content/public/browser/notification_service.h" 24 #include "content/public/browser/notification_service.h"
43 #include "content/public/browser/notification_source.h" 25 #include "content/public/browser/notification_source.h"
44 #include "content/public/browser/notification_types.h" 26 #include "content/public/browser/notification_types.h"
45 #include "content/public/browser/render_view_host.h" 27 #include "content/public/browser/render_view_host.h"
46 #include "content/public/browser/render_widget_host.h"
47 #include "content/public/browser/render_widget_host_view.h" 28 #include "content/public/browser/render_widget_host_view.h"
48 #include "content/public/browser/session_storage_namespace.h"
49 #include "content/public/browser/web_contents.h" 29 #include "content/public/browser/web_contents.h"
50 #include "content/public/browser/web_contents_delegate.h" 30 #include "content/public/browser/web_contents_delegate.h"
51 #include "content/public/browser/web_contents_view.h" 31 #include "content/public/browser/web_contents_observer.h"
52 #include "net/http/http_util.h"
53 #include "ui/base/l10n/l10n_util.h"
54 #include "ui/gfx/codec/png_codec.h"
55
56 using content::NavigationController;
57 using content::NavigationEntry;
58 using content::RenderViewHost;
59 using content::RenderWidgetHost;
60 using content::SessionStorageNamespace;
61 using content::WebContents;
62
63 namespace {
64
65 // Number of ms to delay before updating the omnibox bounds. This is only used
66 // when the bounds of the omnibox shrinks. If the bounds grows, we update
67 // immediately.
68 const int kUpdateBoundsDelayMS = 1000;
69
70 // If this status code is seen instant is disabled for the specified host.
71 const int kHostBlacklistStatusCode = 403;
72
73 enum PreviewUsageType {
74 PREVIEW_CREATED,
75 PREVIEW_DELETED,
76 PREVIEW_LOADED,
77 PREVIEW_SHOWN,
78 PREVIEW_COMMITTED,
79 PREVIEW_NUM_TYPES,
80 };
81
82 void AddPreviewUsageForHistogram(TemplateURLID template_url_id,
83 PreviewUsageType usage,
84 const std::string& group) {
85 DCHECK(0 <= usage && usage < PREVIEW_NUM_TYPES);
86 // Only track the histogram for the instant loaders, for now.
87 if (template_url_id) {
88 base::Histogram* histogram = base::LinearHistogram::FactoryGet(
89 "Instant.Previews" + group, 1, PREVIEW_NUM_TYPES, PREVIEW_NUM_TYPES + 1,
90 base::Histogram::kUmaTargetedHistogramFlag);
91 histogram->Add(usage);
92 }
93 }
94
95 SessionStorageNamespace* GetSessionStorageNamespace(TabContents* tab) {
96 return tab->web_contents()->GetController().GetSessionStorageNamespace();
97 }
98
99 } // namespace
100
101 // static
102 const char* const InstantLoader::kInstantHeader = "X-Purpose";
103 // static
104 const char* const InstantLoader::kInstantHeaderValue = "instant";
105
106 // FrameLoadObserver is responsible for determining if the page supports
107 // instant after it has loaded.
108 class InstantLoader::FrameLoadObserver : public content::NotificationObserver {
109 public:
110 FrameLoadObserver(InstantLoader* loader,
111 WebContents* web_contents,
112 const string16& text,
113 bool verbatim)
114 : loader_(loader),
115 web_contents_(web_contents),
116 text_(text),
117 verbatim_(verbatim),
118 unique_id_(
119 web_contents_->GetController().GetPendingEntry()->GetUniqueID()) {
120 registrar_.Add(this, content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
121 content::Source<WebContents>(web_contents_));
122 }
123
124 // Sets the text to send to the page.
125 void set_text(const string16& text) { text_ = text; }
126
127 // Sets whether verbatim results are obtained rather than predictive.
128 void set_verbatim(bool verbatim) { verbatim_ = verbatim; }
129
130 // content::NotificationObserver:
131 virtual void Observe(int type,
132 const content::NotificationSource& source,
133 const content::NotificationDetails& details) OVERRIDE;
134
135 private:
136 InstantLoader* loader_;
137
138 // The WebContents we're listening for changes on.
139 WebContents* web_contents_;
140
141 // Text to send down to the page.
142 string16 text_;
143
144 // Whether verbatim results are obtained.
145 bool verbatim_;
146
147 // unique_id of the NavigationEntry we're waiting on.
148 const int unique_id_;
149
150 // Registers and unregisters us for notifications.
151 content::NotificationRegistrar registrar_;
152
153 DISALLOW_COPY_AND_ASSIGN(FrameLoadObserver);
154 };
155
156 void InstantLoader::FrameLoadObserver::Observe(
157 int type,
158 const content::NotificationSource& source,
159 const content::NotificationDetails& details) {
160 switch (type) {
161 case content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME: {
162 int page_id = *(content::Details<int>(details).ptr());
163 NavigationEntry* active_entry =
164 web_contents_->GetController().GetActiveEntry();
165 if (!active_entry || active_entry->GetPageID() != page_id ||
166 active_entry->GetUniqueID() != unique_id_) {
167 return;
168 }
169 loader_->SendBoundsToPage(true);
170 // TODO: support real cursor position.
171 int text_length = static_cast<int>(text_.size());
172 RenderViewHost* host = web_contents_->GetRenderViewHost();
173 host->Send(new ChromeViewMsg_DetermineIfPageSupportsInstant(
174 host->GetRoutingID(), text_, verbatim_, text_length, text_length));
175 break;
176 }
177 default:
178 NOTREACHED();
179 break;
180 }
181 }
182 32
183 // WebContentsDelegateImpl ----------------------------------------------------- 33 // WebContentsDelegateImpl -----------------------------------------------------
184 34
185 class InstantLoader::WebContentsDelegateImpl 35 class InstantLoader::WebContentsDelegateImpl
186 : public content::WebContentsDelegate, 36 : public ConstrainedWindowTabHelperDelegate,
187 public CoreTabHelperDelegate, 37 public CoreTabHelperDelegate,
188 public ConstrainedWindowTabHelperDelegate, 38 public content::WebContentsDelegate,
189 public content::NotificationObserver,
190 public content::WebContentsObserver { 39 public content::WebContentsObserver {
191 public: 40 public:
192 explicit WebContentsDelegateImpl(InstantLoader* loader); 41 explicit WebContentsDelegateImpl(InstantLoader* loader);
193 42
194 // Invoked prior to loading a new URL.
195 void PrepareForNewLoad();
196
197 // Invoked when the preview paints. Invokes PreviewPainted on the loader.
198 void PreviewPainted();
199
200 bool is_mouse_down_from_activate() const { 43 bool is_mouse_down_from_activate() const {
201 return is_mouse_down_from_activate_; 44 return is_mouse_down_from_activate_;
202 } 45 }
203 46
204 void set_user_typed_before_load() { user_typed_before_load_ = true; } 47 // ConstrainedWindowTabHelperDelegate:
48 virtual bool ShouldFocusConstrainedWindow() OVERRIDE;
205 49
206 // Sets the last URL that will be added to history when CommitHistory is 50 // CoreTabHelperDelegate:
207 // invoked and removes all but the first navigation. 51 virtual void SwapTabContents(TabContents* old_tc,
208 void SetLastHistoryURLAndPrune(const GURL& url); 52 TabContents* new_tc) OVERRIDE;
209
210 // Commits the currently buffered history.
211 void CommitHistory(bool supports_instant);
212
213 void RegisterForPaintNotifications(RenderWidgetHost* render_widget_host);
214
215 void UnregisterForPaintNotifications();
216
217 // NotificationObserver:
218 virtual void Observe(int type,
219 const content::NotificationSource& source,
220 const content::NotificationDetails& details) OVERRIDE;
221 53
222 // content::WebContentsDelegate: 54 // content::WebContentsDelegate:
223 virtual void NavigationStateChanged(const WebContents* source,
224 unsigned changed_flags) OVERRIDE;
225 virtual void AddNavigationHeaders(const GURL& url,
226 std::string* headers) OVERRIDE;
227 virtual bool ShouldSuppressDialogs() OVERRIDE; 55 virtual bool ShouldSuppressDialogs() OVERRIDE;
228 virtual void BeforeUnloadFired(content::WebContents* tab,
229 bool proceed,
230 bool* proceed_to_fire_unload) OVERRIDE;
231 virtual void SetFocusToLocationBar(bool select_all) OVERRIDE;
232 virtual bool ShouldFocusPageAfterCrash() OVERRIDE; 56 virtual bool ShouldFocusPageAfterCrash() OVERRIDE;
233 virtual void WebContentsFocused(WebContents* contents) OVERRIDE;
234 virtual void LostCapture() OVERRIDE; 57 virtual void LostCapture() OVERRIDE;
235 // If the user drags, we won't get a mouse up (at least on Linux). Commit the 58 virtual void WebContentsFocused(content::WebContents* contents) OVERRIDE;
236 // instant result when the drag ends, so that during the drag the page won't
237 // move around.
238 virtual void DragEnded() OVERRIDE;
239 virtual bool CanDownload(content::RenderViewHost* render_view_host, 59 virtual bool CanDownload(content::RenderViewHost* render_view_host,
240 int request_id, 60 int request_id,
241 const std::string& request_method) OVERRIDE; 61 const std::string& request_method) OVERRIDE;
242 virtual void HandleMouseUp() OVERRIDE; 62 virtual void HandleMouseUp() OVERRIDE;
243 virtual void HandleMouseActivate() OVERRIDE; 63 virtual void HandleMouseActivate() OVERRIDE;
64 virtual void DragEnded() OVERRIDE;
244 virtual bool OnGoToEntryOffset(int offset) OVERRIDE; 65 virtual bool OnGoToEntryOffset(int offset) OVERRIDE;
245 virtual bool ShouldAddNavigationToHistory( 66 virtual bool ShouldAddNavigationToHistory(
246 const history::HistoryAddPageArgs& add_page_args, 67 const history::HistoryAddPageArgs& add_page_args,
247 content::NavigationType navigation_type) OVERRIDE; 68 content::NavigationType navigation_type) OVERRIDE;
248 69
249 // CoreTabHelperDelegate:
250 virtual void SwapTabContents(TabContents* old_tc,
251 TabContents* new_tc) OVERRIDE;
252
253 // ConstrainedWindowTabHelperDelegate:
254 virtual void WillShowConstrainedWindow(TabContents* source) OVERRIDE;
255 virtual bool ShouldFocusConstrainedWindow() OVERRIDE;
256
257 // content::WebContentsObserver: 70 // content::WebContentsObserver:
71 virtual void DidFinishLoad(int64 frame_id,
72 const GURL& validated_url,
73 bool is_main_frame) OVERRIDE;
258 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; 74 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;
259 virtual void DidFailProvisionalLoad(
260 int64 frame_id,
261 bool is_main_frame,
262 const GURL& validated_url,
263 int error_code,
264 const string16& error_description,
265 content::RenderViewHost* render_view_host) OVERRIDE;
266 75
267 private: 76 private:
268 typedef std::vector<scoped_refptr<history::HistoryAddPageArgs> >
269 AddPageVector;
270
271 // Message from renderer indicating the page has suggestions. 77 // Message from renderer indicating the page has suggestions.
272 void OnSetSuggestions( 78 void OnSetSuggestions(
273 int32 page_id, 79 int page_id,
274 const std::vector<std::string>& suggestions, 80 const std::vector<std::string>& suggestions,
275 InstantCompleteBehavior behavior); 81 InstantCompleteBehavior behavior);
276 82
277 // Messages from the renderer when we've determined whether the page supports 83 // Message from the renderer determining whether it supports the Instant API.
278 // instant. 84 void OnInstantSupportDetermined(int page_id, bool result);
279 void OnInstantSupportDetermined(int32 page_id, bool result);
280 85
281 void CommitFromMouseReleaseIfNecessary(); 86 void CommitFromMouseReleaseIfNecessary();
87 void MaybeSetAndNotifyInstantSupportDetermined(bool supports_instant);
282 88
283 InstantLoader* loader_; 89 InstantLoader* loader_;
284 90
285 content::NotificationRegistrar registrar_;
286
287 // If we are registered for paint notifications on a RenderWidgetHost this
288 // will contain a pointer to it.
289 RenderWidgetHost* registered_render_widget_host_;
290
291 // Used to cache data that needs to be added to history. Normally entries are
292 // added to history as the user types, but for instant we only want to add the
293 // items to history if the user commits instant. So, we cache them here and if
294 // committed then add the items to history.
295 AddPageVector add_page_vector_;
296
297 // Are we we waiting for a NavigationType of NEW_PAGE? If we're waiting for
298 // NEW_PAGE navigation we don't add history items to add_page_vector_.
299 bool waiting_for_new_page_;
300
301 // True if the mouse is down from an activate. 91 // True if the mouse is down from an activate.
302 bool is_mouse_down_from_activate_; 92 bool is_mouse_down_from_activate_;
303 93
304 // True if the user typed in the search box before the page loaded.
305 bool user_typed_before_load_;
306
307 DISALLOW_COPY_AND_ASSIGN(WebContentsDelegateImpl); 94 DISALLOW_COPY_AND_ASSIGN(WebContentsDelegateImpl);
308 }; 95 };
309 96
310 InstantLoader::WebContentsDelegateImpl::WebContentsDelegateImpl( 97 InstantLoader::WebContentsDelegateImpl::WebContentsDelegateImpl(
311 InstantLoader* loader) 98 InstantLoader* loader)
312 : content::WebContentsObserver(loader->preview_contents()->web_contents()), 99 : content::WebContentsObserver(loader->preview_contents_->web_contents()),
313 loader_(loader), 100 loader_(loader),
314 registered_render_widget_host_(NULL), 101 is_mouse_down_from_activate_(false) {
315 waiting_for_new_page_(true),
316 is_mouse_down_from_activate_(false),
317 user_typed_before_load_(false) {
318 DCHECK(loader->preview_contents());
319 registrar_.Add(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
320 content::Source<WebContents>(loader->preview_contents()->web_contents()));
321 } 102 }
322 103
323 void InstantLoader::WebContentsDelegateImpl::PrepareForNewLoad() { 104 bool InstantLoader::WebContentsDelegateImpl::ShouldFocusConstrainedWindow() {
324 user_typed_before_load_ = false; 105 // Return false so that constrained windows are not initially focused. If we
325 waiting_for_new_page_ = true; 106 // did otherwise the preview would prematurely get committed when focus goes
326 add_page_vector_.clear(); 107 // to the constrained window.
327 UnregisterForPaintNotifications(); 108 return false;
328 } 109 }
329 110
330 void InstantLoader::WebContentsDelegateImpl::PreviewPainted() { 111 void InstantLoader::WebContentsDelegateImpl::SwapTabContents(
331 loader_->PreviewPainted(); 112 TabContents* old_tc,
332 } 113 TabContents* new_tc) {
333 114 // If this is being called, something is swapping in to our
334 void InstantLoader::WebContentsDelegateImpl::SetLastHistoryURLAndPrune( 115 // |preview_contents_| before we've added it to the tab strip.
335 const GURL& url) { 116 loader_->ReplacePreviewContents(old_tc, new_tc);
336 if (add_page_vector_.empty())
337 return;
338
339 history::HistoryAddPageArgs* args = add_page_vector_.front().get();
340 args->url = url;
341 args->redirects.clear();
342 args->redirects.push_back(url);
343
344 // Prune all but the first entry.
345 add_page_vector_.erase(add_page_vector_.begin() + 1,
346 add_page_vector_.end());
347 }
348
349 void InstantLoader::WebContentsDelegateImpl::CommitHistory(
350 bool supports_instant) {
351 TabContents* tab = loader_->preview_contents();
352 if (tab->profile()->IsOffTheRecord())
353 return;
354
355 for (size_t i = 0; i < add_page_vector_.size(); ++i) {
356 tab->history_tab_helper()->UpdateHistoryForNavigation(
357 add_page_vector_[i].get());
358 }
359
360 NavigationEntry* active_entry =
361 tab->web_contents()->GetController().GetActiveEntry();
362 if (!active_entry) {
363 // It appears to be possible to get here with no active entry. This seems
364 // to be possible with an auth dialog, but I can't narrow down the
365 // circumstances. If you hit this, file a bug with the steps you did and
366 // assign it to me (sky).
367 NOTREACHED();
368 return;
369 }
370 tab->history_tab_helper()->UpdateHistoryPageTitle(*active_entry);
371
372 FaviconService* favicon_service =
373 tab->profile()->GetFaviconService(Profile::EXPLICIT_ACCESS);
374
375 if (favicon_service && active_entry->GetFavicon().valid &&
376 !active_entry->GetFavicon().bitmap.empty()) {
377 std::vector<unsigned char> image_data;
378 gfx::PNGCodec::EncodeBGRASkBitmap(active_entry->GetFavicon().bitmap, false,
379 &image_data);
380 favicon_service->SetFavicon(active_entry->GetURL(),
381 active_entry->GetFavicon().url,
382 image_data,
383 history::FAVICON);
384 if (supports_instant && !add_page_vector_.empty()) {
385 // If we're using the instant API, then we've tweaked the url that is
386 // going to be added to history. We need to also set the favicon for the
387 // url we're adding to history (see comment in ReleasePreviewContents
388 // for details).
389 favicon_service->SetFavicon(add_page_vector_.back()->url,
390 active_entry->GetFavicon().url,
391 image_data,
392 history::FAVICON);
393 }
394 }
395 }
396
397 void InstantLoader::WebContentsDelegateImpl::RegisterForPaintNotifications(
398 RenderWidgetHost* render_widget_host) {
399 DCHECK(registered_render_widget_host_ == NULL);
400 registered_render_widget_host_ = render_widget_host;
401 content::Source<RenderWidgetHost> source =
402 content::Source<RenderWidgetHost>(registered_render_widget_host_);
403 registrar_.Add(
404 this,
405 content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
406 source);
407 registrar_.Add(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
408 source);
409 }
410
411 void InstantLoader::WebContentsDelegateImpl::UnregisterForPaintNotifications() {
412 if (registered_render_widget_host_) {
413 content::Source<RenderWidgetHost> source =
414 content::Source<RenderWidgetHost>(registered_render_widget_host_);
415 registrar_.Remove(
416 this,
417 content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE,
418 source);
419 registrar_.Remove(this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
420 source);
421 registered_render_widget_host_ = NULL;
422 }
423 }
424
425 void InstantLoader::WebContentsDelegateImpl::Observe(
426 int type,
427 const content::NotificationSource& source,
428 const content::NotificationDetails& details) {
429 switch (type) {
430 case content::NOTIFICATION_RENDER_WIDGET_HOST_DID_UPDATE_BACKING_STORE:
431 UnregisterForPaintNotifications();
432 PreviewPainted();
433 break;
434 case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED:
435 UnregisterForPaintNotifications();
436 break;
437 case content::NOTIFICATION_INTERSTITIAL_ATTACHED:
438 PreviewPainted();
439 break;
440 default:
441 NOTREACHED() << "Got a notification we didn't register for.";
442 }
443 }
444
445 void InstantLoader::WebContentsDelegateImpl::NavigationStateChanged(
446 const WebContents* source,
447 unsigned changed_flags) {
448 if (!loader_->ready() && !registered_render_widget_host_ &&
449 source->GetController().GetEntryCount()) {
450 // The load has been committed. Install an observer that waits for the
451 // first paint then makes the preview active. We wait for the load to be
452 // committed before waiting on paint as there is always an initial paint
453 // when a new renderer is created from the resize so that if we showed the
454 // preview after the first paint we would end up with a white rect.
455 content::RenderWidgetHostView *rwhv = source->GetRenderWidgetHostView();
456 if (rwhv)
457 RegisterForPaintNotifications(rwhv->GetRenderWidgetHost());
458 } else if (source->IsCrashed()) {
459 PreviewPainted();
460 }
461 }
462
463 void InstantLoader::WebContentsDelegateImpl::AddNavigationHeaders(
464 const GURL& url,
465 std::string* headers) {
466 net::HttpUtil::AppendHeaderIfMissing(kInstantHeader, kInstantHeaderValue,
467 headers);
468 } 117 }
469 118
470 bool InstantLoader::WebContentsDelegateImpl::ShouldSuppressDialogs() { 119 bool InstantLoader::WebContentsDelegateImpl::ShouldSuppressDialogs() {
471 // Any message shown during instant cancels instant, so we suppress them. 120 // Any message shown during Instant cancels Instant, so we suppress them.
472 return true; 121 return true;
473 } 122 }
474 123
475 void InstantLoader::WebContentsDelegateImpl::BeforeUnloadFired(
476 WebContents* tab,
477 bool proceed,
478 bool* proceed_to_fire_unload) {
479 }
480
481 void InstantLoader::WebContentsDelegateImpl::SetFocusToLocationBar(
482 bool select_all) {
483 }
484
485 bool InstantLoader::WebContentsDelegateImpl::ShouldFocusPageAfterCrash() { 124 bool InstantLoader::WebContentsDelegateImpl::ShouldFocusPageAfterCrash() {
486 return false; 125 return false;
487 } 126 }
488 127
489 void InstantLoader::WebContentsDelegateImpl::WebContentsFocused(
490 WebContents* contents) {
491 loader_->delegate_->InstantLoaderContentsFocused();
492 }
493
494 void InstantLoader::WebContentsDelegateImpl::LostCapture() { 128 void InstantLoader::WebContentsDelegateImpl::LostCapture() {
495 CommitFromMouseReleaseIfNecessary(); 129 CommitFromMouseReleaseIfNecessary();
496 } 130 }
497 131
498 void InstantLoader::WebContentsDelegateImpl::DragEnded() { 132 void InstantLoader::WebContentsDelegateImpl::WebContentsFocused(
499 CommitFromMouseReleaseIfNecessary(); 133 content::WebContents* contents) {
134 loader_->loader_delegate_->InstantLoaderContentsFocused(loader_);
500 } 135 }
501 136
502 bool InstantLoader::WebContentsDelegateImpl::CanDownload( 137 bool InstantLoader::WebContentsDelegateImpl::CanDownload(
503 RenderViewHost* render_view_host, 138 content::RenderViewHost* render_view_host,
504 int request_id, 139 int request_id,
505 const std::string& request_method) { 140 const std::string& request_method) {
506 // Downloads are disabled. 141 // Downloads are disabled.
507 return false; 142 return false;
508 } 143 }
509 144
510 void InstantLoader::WebContentsDelegateImpl::HandleMouseUp() { 145 void InstantLoader::WebContentsDelegateImpl::HandleMouseUp() {
511 CommitFromMouseReleaseIfNecessary(); 146 CommitFromMouseReleaseIfNecessary();
512 } 147 }
513 148
514 void InstantLoader::WebContentsDelegateImpl::HandleMouseActivate() { 149 void InstantLoader::WebContentsDelegateImpl::HandleMouseActivate() {
515 is_mouse_down_from_activate_ = true; 150 is_mouse_down_from_activate_ = true;
516 } 151 }
517 152
153 void InstantLoader::WebContentsDelegateImpl::DragEnded() {
154 // If the user drags, we won't get a mouse up (at least on Linux). Commit the
155 // Instant result when the drag ends, so that during the drag the page won't
156 // move around.
157 CommitFromMouseReleaseIfNecessary();
158 }
159
518 bool InstantLoader::WebContentsDelegateImpl::OnGoToEntryOffset(int offset) { 160 bool InstantLoader::WebContentsDelegateImpl::OnGoToEntryOffset(int offset) {
519 return false; 161 return false;
520 } 162 }
521 163
522 bool InstantLoader::WebContentsDelegateImpl::ShouldAddNavigationToHistory( 164 bool InstantLoader::WebContentsDelegateImpl::ShouldAddNavigationToHistory(
523 const history::HistoryAddPageArgs& add_page_args, 165 const history::HistoryAddPageArgs& add_page_args,
524 content::NavigationType navigation_type) { 166 content::NavigationType navigation_type) {
525 if (waiting_for_new_page_ &&
526 navigation_type == content::NAVIGATION_TYPE_NEW_PAGE) {
527 waiting_for_new_page_ = false;
528 }
529
530 if (!waiting_for_new_page_) {
531 add_page_vector_.push_back(
532 scoped_refptr<history::HistoryAddPageArgs>(add_page_args.Clone()));
533 }
534 return false; 167 return false;
535 } 168 }
536 169
537 // If this is being called, something is swapping in to our preview_contents_ 170 void InstantLoader::WebContentsDelegateImpl::DidFinishLoad(
538 // before we've added it to the tab strip. 171 int64 frame_id,
539 void InstantLoader::WebContentsDelegateImpl::SwapTabContents( 172 const GURL& validated_url,
540 TabContents* old_tc, 173 bool is_main_frame) {
541 TabContents* new_tc) { 174 if (is_main_frame && !loader_->supports_instant_) {
542 loader_->ReplacePreviewContents(old_tc, new_tc); 175 Send(new ChromeViewMsg_DetermineIfPageSupportsInstant(routing_id()));
543 } 176 loader_->loader_delegate_->InstantLoaderPreviewLoaded(loader_);
544
545 bool InstantLoader::WebContentsDelegateImpl::ShouldFocusConstrainedWindow() {
546 // Return false so that constrained windows are not initially focused. If
547 // we did otherwise the preview would prematurely get committed when focus
548 // goes to the constrained window.
549 return false;
550 }
551
552 void InstantLoader::WebContentsDelegateImpl::WillShowConstrainedWindow(
553 TabContents* source) {
554 if (!loader_->ready()) {
555 // A constrained window shown for an auth may not paint. Show the preview
556 // contents.
557 UnregisterForPaintNotifications();
558 loader_->ShowPreview();
559 } 177 }
560 } 178 }
561 179
562 bool InstantLoader::WebContentsDelegateImpl::OnMessageReceived( 180 bool InstantLoader::WebContentsDelegateImpl::OnMessageReceived(
563 const IPC::Message& message) { 181 const IPC::Message& message) {
564 bool handled = true; 182 bool handled = true;
565 IPC_BEGIN_MESSAGE_MAP(WebContentsDelegateImpl, message) 183 IPC_BEGIN_MESSAGE_MAP(WebContentsDelegateImpl, message)
566 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetSuggestions, OnSetSuggestions) 184 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetSuggestions, OnSetSuggestions)
567 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_InstantSupportDetermined, 185 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_InstantSupportDetermined,
568 OnInstantSupportDetermined) 186 OnInstantSupportDetermined)
569 IPC_MESSAGE_UNHANDLED(handled = false) 187 IPC_MESSAGE_UNHANDLED(handled = false)
570 IPC_END_MESSAGE_MAP() 188 IPC_END_MESSAGE_MAP()
571 return handled; 189 return handled;
572 } 190 }
573 191
574 void InstantLoader::WebContentsDelegateImpl::DidFailProvisionalLoad(
575 int64 frame_id,
576 bool is_main_frame,
577 const GURL& validated_url,
578 int error_code,
579 const string16& error_description,
580 content::RenderViewHost* render_view_host) {
581 if (validated_url == loader_->url_) {
582 // This typically happens with downloads (which are disabled with
583 // instant active). To ensure the download happens when the user presses
584 // enter we set needs_reload_ to true, which triggers a reload.
585 loader_->needs_reload_ = true;
586 }
587 }
588
589 void InstantLoader::WebContentsDelegateImpl::OnSetSuggestions( 192 void InstantLoader::WebContentsDelegateImpl::OnSetSuggestions(
590 int32 page_id, 193 int32 page_id,
591 const std::vector<std::string>& suggestions, 194 const std::vector<std::string>& suggestions,
592 InstantCompleteBehavior behavior) { 195 InstantCompleteBehavior behavior) {
593 TabContents* source = loader_->preview_contents(); 196 content::NavigationEntry* entry = loader_->preview_contents_->web_contents()->
594 NavigationEntry* entry = 197 GetController().GetActiveEntry();
595 source->web_contents()->GetController().GetActiveEntry(); 198 if (entry && page_id == entry->GetPageID()) {
596 if (!entry || page_id != entry->GetPageID()) 199 MaybeSetAndNotifyInstantSupportDetermined(true);
597 return; 200 loader_->loader_delegate_->SetSuggestions(loader_, suggestions, behavior);
598 201 }
599 if (suggestions.empty())
600 loader_->SetCompleteSuggestedText(string16(), behavior);
601 else
602 loader_->SetCompleteSuggestedText(UTF8ToUTF16(suggestions[0]), behavior);
603 } 202 }
604 203
605 void InstantLoader::WebContentsDelegateImpl::OnInstantSupportDetermined( 204 void InstantLoader::WebContentsDelegateImpl::OnInstantSupportDetermined(
606 int32 page_id, 205 int page_id,
607 bool result) { 206 bool result) {
608 WebContents* source = loader_->preview_contents()->web_contents(); 207 content::NavigationEntry* entry = loader_->preview_contents_->web_contents()->
609 if (!source->GetController().GetActiveEntry() || 208 GetController().GetActiveEntry();
610 page_id != source->GetController().GetActiveEntry()->GetPageID()) 209 if (entry && page_id == entry->GetPageID())
210 MaybeSetAndNotifyInstantSupportDetermined(result);
211 }
212
213
214 void InstantLoader::WebContentsDelegateImpl
215 ::CommitFromMouseReleaseIfNecessary() {
216 if (is_mouse_down_from_activate_) {
217 is_mouse_down_from_activate_ = false;
218 loader_->loader_delegate_->CommitInstantLoader(loader_);
219 }
220 }
221
222 void InstantLoader::WebContentsDelegateImpl
223 ::MaybeSetAndNotifyInstantSupportDetermined(bool supports_instant) {
224 // If we already determined that the loader supports Instant, nothing to do.
225 if (loader_->supports_instant_)
611 return; 226 return;
612 227
613 content::Details<const bool> details(&result); 228 loader_->supports_instant_ = supports_instant;
229 loader_->loader_delegate_->InstantSupportDetermined(loader_,
230 supports_instant);
231 content::Details<const bool> details(&supports_instant);
614 content::NotificationService::current()->Notify( 232 content::NotificationService::current()->Notify(
615 chrome::NOTIFICATION_INSTANT_SUPPORT_DETERMINED, 233 chrome::NOTIFICATION_INSTANT_SUPPORT_DETERMINED,
616 content::NotificationService::AllSources(), 234 content::NotificationService::AllSources(),
617 details); 235 details);
618 236
619 if (result) 237 // If the page doesn't support the Instant API, InstantController schedules
620 loader_->PageFinishedLoading(); 238 // the loader for destruction. Stop sending the controller any more messages,
621 else 239 // by severing the connection from the WebContents to us (its delegate).
622 loader_->PageDoesntSupportInstant(user_typed_before_load_); 240 if (!supports_instant)
623 } 241 loader_->preview_contents_->web_contents()->SetDelegate(NULL);
624
625 void InstantLoader::WebContentsDelegateImpl
626 ::CommitFromMouseReleaseIfNecessary() {
627 bool was_down = is_mouse_down_from_activate_;
628 is_mouse_down_from_activate_ = false;
629 if (was_down && loader_->ShouldCommitInstantOnMouseUp())
630 loader_->CommitInstantLoader();
631 } 242 }
632 243
633 // InstantLoader --------------------------------------------------------------- 244 // InstantLoader ---------------------------------------------------------------
634 245
635 InstantLoader::InstantLoader(InstantLoaderDelegate* delegate, 246 InstantLoader::InstantLoader(InstantLoaderDelegate* delegate,
636 TemplateURLID id, 247 const GURL& instant_url,
637 const std::string& group) 248 const TabContents* tab_contents)
638 : delegate_(delegate), 249 : loader_delegate_(delegate),
639 template_url_id_(id), 250 preview_contents_(new TabContents(content::WebContents::Create(
640 ready_(false), 251 tab_contents->profile(), NULL, MSG_ROUTING_NONE,
641 http_status_ok_(true), 252 tab_contents->web_contents(),
642 last_transition_type_(content::PAGE_TRANSITION_LINK), 253 tab_contents->web_contents()->GetController().
643 verbatim_(false), 254 GetSessionStorageNamespace()))),
644 needs_reload_(false), 255 preview_delegate_(new WebContentsDelegateImpl(
645 group_(group) { 256 ALLOW_THIS_IN_INITIALIZER_LIST(this))),
257 supports_instant_(false),
258 instant_url_(instant_url) {
646 } 259 }
647 260
648 InstantLoader::~InstantLoader() { 261 InstantLoader::~InstantLoader() {
649 registrar_.RemoveAll();
650
651 // Delete the TabContents before the delegate as the TabContents
652 // holds a reference to the delegate.
653 if (preview_contents()) 262 if (preview_contents())
654 AddPreviewUsageForHistogram(template_url_id_, PREVIEW_DELETED, group_); 263 preview_contents_->web_contents()->SetDelegate(NULL);
655 preview_contents_.reset();
656 } 264 }
657 265
658 bool InstantLoader::Update(TabContents* tab_contents, 266 void InstantLoader::Init() {
659 const TemplateURL* template_url, 267 SetupPreviewContents();
660 const GURL& url, 268 // This HTTP header and value are set on loads that originate from instant.
661 content::PageTransition transition_type, 269 const char* const kInstantHeader = "X-Purpose";
662 const string16& user_text, 270 const char* const kInstantHeaderValue = "Instant";
663 bool verbatim, 271 preview_contents_->web_contents()->GetController().LoadURL(instant_url_,
664 string16* suggested_text) { 272 content::Referrer(), content::PAGE_TRANSITION_GENERATED,
665 DCHECK(!url.is_empty() && url.is_valid()); 273 base::StringPrintf("%s: %s", kInstantHeader, kInstantHeaderValue));
274 preview_contents_->web_contents()->WasHidden();
275 }
666 276
667 // Strip leading ?. 277 void InstantLoader::Update(const std::string& user_text, bool verbatim) {
668 string16 new_user_text = 278 // TODO: Support real cursor position.
669 !user_text.empty() && (UTF16ToWide(user_text)[0] == L'?') ? 279 content::RenderViewHost* rvh =
670 user_text.substr(1) : user_text; 280 preview_contents_->web_contents()->GetRenderViewHost();
671 281 rvh->Send(new ChromeViewMsg_SearchBoxChange(rvh->GetRoutingID(), user_text,
672 // We should preserve the transition type regardless of whether we're already 282 verbatim, user_text.size(), user_text.size()));
673 // showing the url.
674 last_transition_type_ = transition_type;
675
676 // If state hasn't changed, reuse the last suggestion. There are two cases:
677 // 1. If no template url (not using instant API), then we only care if the url
678 // changes.
679 // 2. Template url (using instant API) then the important part is if the
680 // user_text changes.
681 // We have to be careful in checking user_text as in some situations
682 // InstantController passes in an empty string (when it knows the user_text
683 // won't matter).
684 if ((!template_url_id_ && url_ == url) ||
685 (template_url_id_ &&
686 (new_user_text.empty() || user_text_ == new_user_text))) {
687 suggested_text->assign(last_suggestion_);
688 // Track the url even if we're not going to update. This is important as
689 // when we get the suggest text we set user_text_ to the new suggest text,
690 // but yet the url is much different.
691 url_ = url;
692 return false;
693 }
694
695 url_ = url;
696 user_text_ = new_user_text;
697 verbatim_ = verbatim;
698 last_suggestion_.clear();
699 needs_reload_ = false;
700
701 bool created_preview_contents = preview_contents_.get() == NULL;
702 if (created_preview_contents)
703 CreatePreviewContents(tab_contents);
704
705 // Carry over the user agent override setting to the new entry.
706 content::NavigationEntry* entry =
707 tab_contents->web_contents()->GetController().GetActiveEntry();
708 bool override_user_agent = entry && entry->GetIsOverridingUserAgent();
709
710 if (template_url) {
711 DCHECK(template_url_id_ == template_url->id());
712 if (!created_preview_contents) {
713 if (is_determining_if_page_supports_instant()) {
714 // The page hasn't loaded yet. Note it, but send down the text anyway.
715 frame_load_observer_->set_text(user_text_);
716 frame_load_observer_->set_verbatim(verbatim);
717 preview_tab_contents_delegate_->set_user_typed_before_load();
718 }
719 // TODO: support real cursor position.
720 int text_length = static_cast<int>(user_text_.size());
721 RenderViewHost* host =
722 preview_contents_->web_contents()->GetRenderViewHost();
723 host->Send(new ChromeViewMsg_SearchBoxChange(
724 host->GetRoutingID(),
725 user_text_,
726 verbatim,
727 text_length,
728 text_length));
729
730 string16 complete_suggested_text_lower = base::i18n::ToLower(
731 complete_suggested_text_);
732 string16 user_text_lower = base::i18n::ToLower(user_text_);
733 if (!verbatim &&
734 complete_suggested_text_lower.size() > user_text_lower.size() &&
735 !complete_suggested_text_lower.compare(0, user_text_lower.size(),
736 user_text_lower)) {
737 *suggested_text = last_suggestion_ =
738 complete_suggested_text_.substr(user_text_.size());
739 }
740 } else {
741 LoadInstantURL(template_url, transition_type, user_text_, verbatim,
742 override_user_agent);
743 }
744 } else {
745 DCHECK(template_url_id_ == 0);
746 preview_tab_contents_delegate_->PrepareForNewLoad();
747 frame_load_observer_.reset(NULL);
748
749 preview_contents_->web_contents()->GetController().
750 LoadURLWithUserAgentOverride(url_, content::Referrer(), transition_type,
751 false, std::string(), override_user_agent);
752 }
753 return true;
754 } 283 }
755 284
756 void InstantLoader::SetOmniboxBounds(const gfx::Rect& bounds) { 285 void InstantLoader::SetOmniboxBounds(const gfx::Rect& bounds) {
757 if (omnibox_bounds_ == bounds) 286 content::RenderViewHost* rvh =
758 return; 287 preview_contents_->web_contents()->GetRenderViewHost();
759 288 rvh->Send(new ChromeViewMsg_SearchBoxResize(rvh->GetRoutingID(), bounds));
760 // Don't update the page while the mouse is down. http://crbug.com/71952
761 if (IsMouseDownFromActivate())
762 return;
763
764 omnibox_bounds_ = bounds;
765 if (preview_contents_.get() && is_showing_instant() &&
766 !is_determining_if_page_supports_instant()) {
767 // Updating the bounds is rather expensive, and because of the async nature
768 // of the omnibox the bounds can dance around a bit. Delay the update in
769 // hopes of things settling down. To avoid hiding results we grow
770 // immediately, but delay shrinking.
771 update_bounds_timer_.Stop();
772 if (omnibox_bounds_.height() > last_omnibox_bounds_.height()) {
773 SendBoundsToPage(false);
774 } else {
775 update_bounds_timer_.Start(FROM_HERE,
776 base::TimeDelta::FromMilliseconds(kUpdateBoundsDelayMS),
777 this, &InstantLoader::ProcessBoundsChange);
778 }
779 }
780 } 289 }
781 290
782 bool InstantLoader::IsMouseDownFromActivate() { 291 TabContents* InstantLoader::ReleasePreviewContents(InstantCommitType type,
783 return preview_tab_contents_delegate_.get() && 292 const string16& text) {
784 preview_tab_contents_delegate_->is_mouse_down_from_activate(); 293 content::RenderViewHost* rvh =
785 } 294 preview_contents_->web_contents()->GetRenderViewHost();
786 295 const std::string searchbox_text = UTF16ToUTF8(text);
787 TabContents* InstantLoader::ReleasePreviewContents( 296 if (type == INSTANT_COMMIT_PRESSED_ENTER) {
788 InstantCommitType type, 297 rvh->Send(new ChromeViewMsg_SearchBoxSubmit(rvh->GetRoutingID(),
789 TabContents* tab_contents) { 298 searchbox_text));
790 if (!preview_contents_.get()) 299 } else {
791 return NULL; 300 rvh->Send(new ChromeViewMsg_SearchBoxCancel(rvh->GetRoutingID(),
792 301 searchbox_text));
793 // FrameLoadObserver is only used for instant results, and instant results are
794 // only committed if active (when the FrameLoadObserver isn't installed).
795 DCHECK(type == INSTANT_COMMIT_DESTROY || !frame_load_observer_.get());
796
797 if (type != INSTANT_COMMIT_DESTROY && is_showing_instant()) {
798 RenderViewHost* host =
799 preview_contents_->web_contents()->GetRenderViewHost();
800 if (type == INSTANT_COMMIT_FOCUS_LOST) {
801 host->Send(new ChromeViewMsg_SearchBoxCancel(host->GetRoutingID()));
802 } else {
803 host->Send(new ChromeViewMsg_SearchBoxSubmit(
804 host->GetRoutingID(), user_text_,
805 type == INSTANT_COMMIT_PRESSED_ENTER));
806 }
807 } 302 }
808 omnibox_bounds_ = gfx::Rect(); 303 CleanupPreviewContents();
809 last_omnibox_bounds_ = gfx::Rect();
810 GURL url;
811 url.Swap(&url_);
812 user_text_.clear();
813 complete_suggested_text_.clear();
814 if (preview_contents_.get()) {
815 if (type != INSTANT_COMMIT_DESTROY) {
816 if (template_url_id_) {
817 // The URL used during instant is mostly gibberish, and not something
818 // we'll parse and match as a past search. Set it to something we can
819 // parse.
820 preview_tab_contents_delegate_->SetLastHistoryURLAndPrune(url);
821 }
822 preview_tab_contents_delegate_->CommitHistory(template_url_id_ != 0);
823 }
824 if (preview_contents_->web_contents()->GetRenderWidgetHostView()) {
825 #if defined(OS_MACOSX)
826 preview_contents_->web_contents()->GetRenderWidgetHostView()->
827 SetTakesFocusOnlyOnMouseDown(false);
828 registrar_.Remove(
829 this,
830 content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
831 content::Source<NavigationController>(
832 &preview_contents_->web_contents()->GetController()));
833 #endif
834 }
835 preview_contents_->web_contents()->SetDelegate(NULL);
836 ready_ = false;
837 }
838 update_bounds_timer_.Stop();
839 AddPreviewUsageForHistogram(template_url_id_,
840 type == INSTANT_COMMIT_DESTROY ? PREVIEW_DELETED : PREVIEW_COMMITTED,
841 group_);
842 if (type != INSTANT_COMMIT_DESTROY) {
843 base::Histogram* histogram = base::LinearHistogram::FactoryGet(
844 "Instant.SessionStorageNamespace" + group_, 1, 2, 3,
845 base::Histogram::kUmaTargetedHistogramFlag);
846 histogram->Add(tab_contents == NULL || session_storage_namespace_ ==
847 GetSessionStorageNamespace(tab_contents));
848 // Now that the ownership is being passed to the caller, the thumbnailer
849 // needs to resume taking thumbnails.
850 if (preview_contents_->thumbnail_generator())
851 preview_contents_->thumbnail_generator()->set_enabled(true);
852 }
853 session_storage_namespace_ = NULL;
854 return preview_contents_.release(); 304 return preview_contents_.release();
855 } 305 }
856 306
857 bool InstantLoader::ShouldCommitInstantOnMouseUp() { 307 bool InstantLoader::IsMouseDownFromActivate() const {
858 return delegate_->ShouldCommitInstantOnMouseUp(); 308 return preview_delegate_->is_mouse_down_from_activate();
859 }
860
861 void InstantLoader::CommitInstantLoader() {
862 delegate_->CommitInstantLoader(this);
863 }
864
865 void InstantLoader::MaybeLoadInstantURL(TabContents* tab_contents,
866 const TemplateURL* template_url) {
867 DCHECK(template_url_id_ == template_url->id());
868
869 // If we already have a |preview_contents_|, future search queries will be
870 // issued into it (see the "if (!created_preview_contents)" block in |Update|
871 // above), so there is no need to load the |template_url|'s instant URL.
872 if (preview_contents_.get())
873 return;
874
875 // Carry over the user agent override setting to the new entry.
876 content::NavigationEntry* entry =
877 tab_contents->web_contents()->GetController().GetActiveEntry();
878 bool override_user_agent = entry && entry->GetIsOverridingUserAgent();
879
880 CreatePreviewContents(tab_contents);
881 LoadInstantURL(template_url, content::PAGE_TRANSITION_GENERATED, string16(),
882 true, override_user_agent);
883 }
884
885 bool InstantLoader::IsNavigationPending() const {
886 return preview_contents_.get() &&
887 preview_contents_->web_contents()->GetController().GetPendingEntry();
888 } 309 }
889 310
890 void InstantLoader::Observe(int type, 311 void InstantLoader::Observe(int type,
891 const content::NotificationSource& source, 312 const content::NotificationSource& source,
892 const content::NotificationDetails& details) { 313 const content::NotificationDetails& details) {
893 #if defined(OS_MACOSX) 314 #if defined(OS_MACOSX)
894 if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) { 315 if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) {
895 if (preview_contents_->web_contents()->GetRenderWidgetHostView()) { 316 if (content::RenderWidgetHostView* rwhv =
896 preview_contents_->web_contents()->GetRenderWidgetHostView()-> 317 preview_contents_->web_contents()->GetRenderWidgetHostView()) {
897 SetTakesFocusOnlyOnMouseDown(true); 318 rwhv->SetTakesFocusOnlyOnMouseDown(true);
898 } 319 }
899 return; 320 return;
900 } 321 }
322 NOTREACHED();
901 #endif 323 #endif
902 if (type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) {
903 content::LoadCommittedDetails* load_details =
904 content::Details<content::LoadCommittedDetails>(details).ptr();
905 if (load_details->is_main_frame) {
906 if (load_details->http_status_code == kHostBlacklistStatusCode) {
907 delegate_->AddToBlacklist(this, load_details->entry->GetURL());
908 } else {
909 SetHTTPStatusOK(load_details->http_status_code == 200);
910 }
911 }
912 return;
913 }
914
915 NOTREACHED() << "Got a notification we didn't register for.";
916 } 324 }
917 325
918 void InstantLoader::SetCompleteSuggestedText( 326 void InstantLoader::SetupPreviewContents() {
919 const string16& complete_suggested_text, 327 content::WebContents* new_contents = preview_contents_->web_contents();
920 InstantCompleteBehavior behavior) { 328 WebContentsDelegateImpl* new_delegate = preview_delegate_.get();
921 if (!is_showing_instant()) { 329 new_contents->SetDelegate(new_delegate);
922 // We're not trying to use the instant API with this page. Ignore it. 330
923 return; 331 // Disable popups and such (mainly to avoid losing focus and committing the
332 // preview prematurely).
333 preview_contents_->blocked_content_tab_helper()->SetAllContentsBlocked(true);
334 preview_contents_->constrained_window_tab_helper()->set_delegate(
335 new_delegate);
336 preview_contents_->content_settings()->SetPopupsBlocked(true);
337 preview_contents_->core_tab_helper()->set_delegate(new_delegate);
338 if (ThumbnailGenerator* tg = preview_contents_->thumbnail_generator())
339 tg->set_enabled(false);
340
341 #if defined(OS_MACOSX)
342 // If |preview_contents_| does not currently have a RWHV, we will call
343 // SetTakesFocusOnlyOnMouseDown() as a result of the RENDER_VIEW_HOST_CHANGED
344 // notification.
345 if (content::RenderWidgetHostView* rwhv =
346 new_contents->GetRenderWidgetHostView()) {
347 rwhv->SetTakesFocusOnlyOnMouseDown(true);
924 } 348 }
925 349 registrar_.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
926 ShowPreview(); 350 content::Source<content::NavigationController>(
927 351 &new_contents->GetController()));
928 if (complete_suggested_text == complete_suggested_text_) 352 #endif
929 return;
930
931 if (verbatim_) {
932 // Don't show suggest results for verbatim queries.
933 return;
934 }
935
936 string16 user_text_lower = base::i18n::ToLower(user_text_);
937 string16 complete_suggested_text_lower = base::i18n::ToLower(
938 complete_suggested_text);
939 last_suggestion_.clear();
940 if (user_text_lower.compare(0, user_text_lower.size(),
941 complete_suggested_text_lower,
942 0, user_text_lower.size())) {
943 // The user text no longer contains the suggested text, ignore it.
944 complete_suggested_text_.clear();
945 delegate_->SetSuggestedTextFor(this, string16(), behavior);
946 return;
947 }
948
949 complete_suggested_text_ = complete_suggested_text;
950 if (behavior == INSTANT_COMPLETE_NOW) {
951 // We are effectively showing complete_suggested_text_ now. Update
952 // user_text_ so we don't notify the page again if Update happens to be
953 // invoked (which is more than likely if this callback completes before the
954 // omnibox is done).
955 string16 suggestion = complete_suggested_text_.substr(user_text_.size());
956 user_text_ = complete_suggested_text_;
957 delegate_->SetSuggestedTextFor(this, suggestion, behavior);
958 } else {
959 DCHECK((behavior == INSTANT_COMPLETE_DELAYED) ||
960 (behavior == INSTANT_COMPLETE_NEVER));
961 last_suggestion_ = complete_suggested_text_.substr(user_text_.size());
962 delegate_->SetSuggestedTextFor(this, last_suggestion_, behavior);
963 }
964 } 353 }
965 354
966 void InstantLoader::PreviewPainted() { 355 void InstantLoader::CleanupPreviewContents() {
967 // If instant is supported then we wait for the first suggest result before 356 content::WebContents* old_contents = preview_contents_->web_contents();
968 // showing the page. 357 old_contents->SetDelegate(NULL);
969 if (!template_url_id_)
970 ShowPreview();
971 }
972 358
973 void InstantLoader::SetHTTPStatusOK(bool is_ok) { 359 preview_contents_->blocked_content_tab_helper()->SetAllContentsBlocked(false);
974 if (is_ok == http_status_ok_) 360 preview_contents_->constrained_window_tab_helper()->set_delegate(NULL);
975 return; 361 preview_contents_->content_settings()->SetPopupsBlocked(false);
362 preview_contents_->core_tab_helper()->set_delegate(NULL);
363 if (ThumbnailGenerator* tg = preview_contents_->thumbnail_generator())
364 tg->set_enabled(true);
976 365
977 http_status_ok_ = is_ok; 366 #if defined(OS_MACOSX)
978 if (ready_) 367 if (content::RenderWidgetHostView* rwhv =
979 delegate_->InstantStatusChanged(this); 368 old_contents->GetRenderWidgetHostView()) {
980 } 369 rwhv->SetTakesFocusOnlyOnMouseDown(false);
981
982 void InstantLoader::ShowPreview() {
983 if (!ready_) {
984 ready_ = true;
985 delegate_->InstantStatusChanged(this);
986 AddPreviewUsageForHistogram(template_url_id_, PREVIEW_SHOWN, group_);
987 } 370 }
988 } 371 registrar_.Remove(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
989 372 content::Source<content::NavigationController>(
990 void InstantLoader::PageFinishedLoading() { 373 &old_contents->GetController()));
991 frame_load_observer_.reset(); 374 #endif
992
993 // Send the bounds of the omnibox down now.
994 SendBoundsToPage(false);
995
996 // Wait for the user input before showing, this way the page should be up to
997 // date by the time we show it.
998 AddPreviewUsageForHistogram(template_url_id_, PREVIEW_LOADED, group_);
999 }
1000
1001 // TODO(tonyg): This method only fires when the omnibox bounds change. It also
1002 // needs to fire when the preview bounds change (e.g. open/close info bar).
1003 gfx::Rect InstantLoader::GetOmniboxBoundsInTermsOfPreview() {
1004 gfx::Rect preview_bounds(delegate_->GetInstantBounds());
1005 gfx::Rect intersection(omnibox_bounds_.Intersect(preview_bounds));
1006
1007 // Translate into window's coordinates.
1008 if (!intersection.IsEmpty()) {
1009 intersection.Offset(-preview_bounds.origin().x(),
1010 -preview_bounds.origin().y());
1011 }
1012
1013 // In the current Chrome UI, these must always be true so they sanity check
1014 // the above operations. In a future UI, these may be removed or adjusted.
1015 // There is no point in sanity-checking |intersection.y()| because the omnibox
1016 // can be placed anywhere vertically relative to the preview (for example, in
1017 // Mac fullscreen mode, the omnibox is entirely enclosed by the preview
1018 // bounds).
1019 DCHECK_LE(0, intersection.x());
1020 DCHECK_LE(0, intersection.width());
1021 DCHECK_LE(0, intersection.height());
1022
1023 return intersection;
1024 }
1025
1026 void InstantLoader::PageDoesntSupportInstant(bool needs_reload) {
1027 frame_load_observer_.reset(NULL);
1028
1029 delegate_->InstantLoaderDoesntSupportInstant(this);
1030
1031 AddPreviewUsageForHistogram(template_url_id_, PREVIEW_LOADED, group_);
1032 }
1033
1034 void InstantLoader::ProcessBoundsChange() {
1035 SendBoundsToPage(false);
1036 }
1037
1038 void InstantLoader::SendBoundsToPage(bool force_if_waiting) {
1039 if (last_omnibox_bounds_ == omnibox_bounds_)
1040 return;
1041
1042 if (preview_contents_.get() && is_showing_instant() &&
1043 (force_if_waiting || !is_determining_if_page_supports_instant())) {
1044 last_omnibox_bounds_ = omnibox_bounds_;
1045 RenderViewHost* host =
1046 preview_contents_->web_contents()->GetRenderViewHost();
1047 host->Send(new ChromeViewMsg_SearchBoxResize(
1048 host->GetRoutingID(), GetOmniboxBoundsInTermsOfPreview()));
1049 }
1050 } 375 }
1051 376
1052 void InstantLoader::ReplacePreviewContents(TabContents* old_tc, 377 void InstantLoader::ReplacePreviewContents(TabContents* old_tc,
1053 TabContents* new_tc) { 378 TabContents* new_tc) {
1054 DCHECK(old_tc == preview_contents_); 379 DCHECK(old_tc == preview_contents_);
1055 // We release here without deleting so that the caller still has reponsibility 380 CleanupPreviewContents();
1056 // for deleting the TabContents. 381 // We release here without deleting so that the caller still has the
382 // responsibility for deleting the TabContents.
1057 ignore_result(preview_contents_.release()); 383 ignore_result(preview_contents_.release());
1058 preview_contents_.reset(new_tc); 384 preview_contents_.reset(new_tc);
1059 session_storage_namespace_ = GetSessionStorageNamespace(new_tc); 385 SetupPreviewContents();
1060 386 loader_delegate_->SwappedTabContents(this);
1061 // Make sure the new preview contents acts like the old one.
1062 SetupPreviewContents(old_tc);
1063
1064 // Cleanup the old preview contents.
1065 old_tc->constrained_window_tab_helper()->set_delegate(NULL);
1066 old_tc->core_tab_helper()->set_delegate(NULL);
1067 old_tc->web_contents()->SetDelegate(NULL);
1068
1069 #if defined(OS_MACOSX)
1070 registrar_.Remove(
1071 this,
1072 content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
1073 content::Source<NavigationController>(
1074 &old_tc->web_contents()->GetController()));
1075 #endif
1076 registrar_.Remove(
1077 this,
1078 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1079 content::Source<NavigationController>(
1080 &old_tc->web_contents()->GetController()));
1081
1082 // We prerendered so we should be ready to show. If we're ready, swap in
1083 // immediately, otherwise show the preview as normal.
1084 if (ready_)
1085 delegate_->SwappedTabContents(this);
1086 else
1087 ShowPreview();
1088 } 387 }
1089
1090 void InstantLoader::SetupPreviewContents(TabContents* tab_contents) {
1091 preview_contents_->web_contents()->SetDelegate(
1092 preview_tab_contents_delegate_.get());
1093 preview_contents_->blocked_content_tab_helper()->SetAllContentsBlocked(true);
1094 preview_contents_->constrained_window_tab_helper()->set_delegate(
1095 preview_tab_contents_delegate_.get());
1096 preview_contents_->core_tab_helper()->set_delegate(
1097 preview_tab_contents_delegate_.get());
1098 // Disables thumbnailing while the web contents is shown as preview to avoid
1099 // generating unnecessary thumbnails.
1100 if (preview_contents_->thumbnail_generator())
1101 preview_contents_->thumbnail_generator()->set_enabled(false);
1102
1103 #if defined(OS_MACOSX)
1104 // If |preview_contents_| does not currently have a RWHV, we will call
1105 // SetTakesFocusOnlyOnMouseDown() as a result of the
1106 // RENDER_VIEW_HOST_CHANGED notification.
1107 if (preview_contents_->web_contents()->GetRenderWidgetHostView()) {
1108 preview_contents_->web_contents()->GetRenderWidgetHostView()->
1109 SetTakesFocusOnlyOnMouseDown(true);
1110 }
1111 registrar_.Add(
1112 this,
1113 content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
1114 content::Source<NavigationController>(
1115 &preview_contents_->web_contents()->GetController()));
1116 #endif
1117
1118 registrar_.Add(
1119 this,
1120 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
1121 content::Source<NavigationController>(
1122 &preview_contents_->web_contents()->GetController()));
1123
1124 gfx::Rect tab_bounds;
1125 tab_contents->web_contents()->GetView()->GetContainerBounds(&tab_bounds);
1126 preview_contents_->web_contents()->GetView()->SizeContents(tab_bounds.size());
1127
1128 // Carry over the user agent override string.
1129 const std::string& override =
1130 tab_contents->web_contents()->GetUserAgentOverride();
1131 preview_contents_->web_contents()->SetUserAgentOverride(override);
1132 }
1133
1134 void InstantLoader::CreatePreviewContents(TabContents* tab_contents) {
1135 WebContents* new_contents = WebContents::Create(
1136 tab_contents->profile(), NULL, MSG_ROUTING_NONE, NULL, NULL);
1137 preview_contents_.reset(new TabContents(new_contents));
1138 AddPreviewUsageForHistogram(template_url_id_, PREVIEW_CREATED, group_);
1139 session_storage_namespace_ = GetSessionStorageNamespace(tab_contents);
1140 preview_tab_contents_delegate_.reset(new WebContentsDelegateImpl(this));
1141 SetupPreviewContents(tab_contents);
1142
1143 // TODO(beng): investigate if we can avoid this and instead rely on the
1144 // visibility of the WebContentsView
1145 preview_contents_->web_contents()->WasRestored();
1146 }
1147
1148 void InstantLoader::LoadInstantURL(const TemplateURL* template_url,
1149 content::PageTransition transition_type,
1150 const string16& user_text,
1151 bool verbatim,
1152 bool override_user_agent) {
1153 preview_tab_contents_delegate_->PrepareForNewLoad();
1154
1155 // Load the instant URL. We don't reflect the url we load in url() as
1156 // callers expect that we're loading the URL they tell us to.
1157 //
1158 // This uses an empty string for the replacement text as the url doesn't
1159 // really have the search params, but we need to use the replace
1160 // functionality so that embeded tags (like {google:baseURL}) are escaped
1161 // correctly.
1162 // TODO(sky): having to use a replaceable url is a bit of a hack here.
1163 GURL instant_url(template_url->instant_url_ref().ReplaceSearchTerms(
1164 TemplateURLRef::SearchTermsArgs(string16())));
1165 CommandLine* cl = CommandLine::ForCurrentProcess();
1166 if (cl->HasSwitch(switches::kInstantURL))
1167 instant_url = GURL(cl->GetSwitchValueASCII(switches::kInstantURL));
1168
1169 preview_contents_->web_contents()->GetController().
1170 LoadURLWithUserAgentOverride(instant_url, content::Referrer(),
1171 transition_type, false, std::string(), override_user_agent);
1172
1173 RenderViewHost* host = preview_contents_->web_contents()->GetRenderViewHost();
1174 preview_contents_->web_contents()->WasHidden();
1175
1176 // If user_text is empty, this must be a preload of the search homepage. In
1177 // that case, send down a SearchBoxResize message, which will switch the page
1178 // to "search results" UI. This avoids flicker when the page is shown with
1179 // results. In addition, we don't want the page accidentally causing the
1180 // preloaded page to be displayed yet (by calling setSuggestions), so don't
1181 // send a SearchBoxChange message.
1182 if (user_text.empty()) {
1183 host->Send(new ChromeViewMsg_SearchBoxResize(
1184 host->GetRoutingID(), GetOmniboxBoundsInTermsOfPreview()));
1185 } else {
1186 host->Send(new ChromeViewMsg_SearchBoxChange(
1187 host->GetRoutingID(), user_text, verbatim, 0, 0));
1188 }
1189
1190 frame_load_observer_.reset(new FrameLoadObserver(
1191 this, preview_contents()->web_contents(), user_text, verbatim));
1192 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698