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

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: Merge test 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 "chrome/browser/content_settings/tab_specific_content_settings.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"
18 #include "base/values.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" 8 #include "chrome/browser/instant/instant_loader_delegate.h"
23 #include "chrome/browser/profiles/profile.h" 9 #include "chrome/browser/profiles/profile.h"
24 #include "chrome/browser/search_engines/template_url.h"
25 #include "chrome/browser/tab_contents/thumbnail_generator.h" 10 #include "chrome/browser/tab_contents/thumbnail_generator.h"
26 #include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h" 11 #include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h"
27 #include "chrome/browser/ui/constrained_window_tab_helper.h" 12 #include "chrome/browser/ui/constrained_window_tab_helper.h"
28 #include "chrome/browser/ui/constrained_window_tab_helper_delegate.h" 13 #include "chrome/browser/ui/constrained_window_tab_helper_delegate.h"
29 #include "chrome/browser/ui/tab_contents/core_tab_helper.h" 14 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
30 #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h" 15 #include "chrome/browser/ui/tab_contents/core_tab_helper_delegate.h"
31 #include "chrome/browser/ui/tab_contents/tab_contents.h" 16 #include "chrome/browser/ui/tab_contents/tab_contents.h"
32 #include "chrome/common/chrome_notification_types.h" 17 #include "chrome/common/chrome_notification_types.h"
33 #include "chrome/common/chrome_switches.h"
34 #include "chrome/common/render_messages.h" 18 #include "chrome/common/render_messages.h"
35 #include "content/public/browser/favicon_status.h"
36 #include "content/public/browser/navigation_controller.h" 19 #include "content/public/browser/navigation_controller.h"
37 #include "content/public/browser/navigation_details.h"
38 #include "content/public/browser/navigation_entry.h" 20 #include "content/public/browser/navigation_entry.h"
39 #include "content/public/browser/notification_details.h" 21 #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" 22 #include "content/public/browser/notification_service.h"
43 #include "content/public/browser/notification_source.h" 23 #include "content/public/browser/notification_source.h"
44 #include "content/public/browser/notification_types.h" 24 #include "content/public/browser/notification_types.h"
45 #include "content/public/browser/render_view_host.h" 25 #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" 26 #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" 27 #include "content/public/browser/web_contents.h"
50 #include "content/public/browser/web_contents_delegate.h" 28 #include "content/public/browser/web_contents_delegate.h"
51 #include "content/public/browser/web_contents_view.h" 29 #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;
sky 2012/07/17 18:21:42 I guess we're removing this because it doesn't mak
sreeram 2012/07/18 01:29:45 It's not being removed. It's just being moved to i
sreeram 2012/07/18 01:29:45 It's not being removed. It's just being moved to i
Jered 2012/07/18 17:38:58 This still exists, but is now in the controller.
69
70 // If this status code is seen instant is disabled for the specified host.
71 const int kHostBlacklistStatusCode = 403;
sky 2012/07/17 18:21:42 Why are you removing this? We've documented allowi
sreeram 2012/07/18 01:29:45 I don't see it being documented at http://dev.chro
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";
sky 2012/07/17 18:21:42 Similar comments for the header and header-value.
dominich 2012/07/17 18:42:19 They are - see 262. They were removed as constant
Jered 2012/07/18 17:38:58 I have re-added these below. I chose not to expose
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 30
183 // WebContentsDelegateImpl ----------------------------------------------------- 31 // WebContentsDelegateImpl -----------------------------------------------------
184 32
185 class InstantLoader::WebContentsDelegateImpl 33 class InstantLoader::WebContentsDelegateImpl
186 : public content::WebContentsDelegate, 34 : public ConstrainedWindowTabHelperDelegate,
187 public CoreTabHelperDelegate, 35 public CoreTabHelperDelegate,
188 public ConstrainedWindowTabHelperDelegate, 36 public content::WebContentsDelegate,
189 public content::NotificationObserver,
190 public content::WebContentsObserver { 37 public content::WebContentsObserver {
191 public: 38 public:
192 explicit WebContentsDelegateImpl(InstantLoader* loader); 39 explicit WebContentsDelegateImpl(InstantLoader* loader);
193 40
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 { 41 bool is_mouse_down_from_activate() const {
201 return is_mouse_down_from_activate_; 42 return is_mouse_down_from_activate_;
202 } 43 }
203 44
204 void set_user_typed_before_load() { user_typed_before_load_ = true; } 45 // ConstrainedWindowTabHelperDelegate:
46 virtual bool ShouldFocusConstrainedWindow() OVERRIDE;
205 47
206 // Sets the last URL that will be added to history when CommitHistory is 48 // CoreTabHelperDelegate:
207 // invoked and removes all but the first navigation. 49 virtual void SwapTabContents(TabContents* old_tc,
208 void SetLastHistoryURLAndPrune(const GURL& url); 50 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 51
222 // content::WebContentsDelegate: 52 // 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; 53 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; 54 virtual bool ShouldFocusPageAfterCrash() OVERRIDE;
233 virtual void WebContentsFocused(WebContents* contents) OVERRIDE;
234 virtual void LostCapture() OVERRIDE; 55 virtual void LostCapture() OVERRIDE;
235 // If the user drags, we won't get a mouse up (at least on Linux). Commit the 56 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, 57 virtual bool CanDownload(content::RenderViewHost* render_view_host,
240 int request_id, 58 int request_id,
241 const std::string& request_method) OVERRIDE; 59 const std::string& request_method) OVERRIDE;
242 virtual void HandleMouseUp() OVERRIDE; 60 virtual void HandleMouseUp() OVERRIDE;
243 virtual void HandleMouseActivate() OVERRIDE; 61 virtual void HandleMouseActivate() OVERRIDE;
62 virtual void DragEnded() OVERRIDE;
244 virtual bool OnGoToEntryOffset(int offset) OVERRIDE; 63 virtual bool OnGoToEntryOffset(int offset) OVERRIDE;
245 virtual bool ShouldAddNavigationToHistory( 64 virtual bool ShouldAddNavigationToHistory(
246 const history::HistoryAddPageArgs& add_page_args, 65 const history::HistoryAddPageArgs& add_page_args,
247 content::NavigationType navigation_type) OVERRIDE; 66 content::NavigationType navigation_type) OVERRIDE;
248 67
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: 68 // content::WebContentsObserver:
69 virtual void DidFinishLoad(int64 frame_id,
70 const GURL& validated_url,
71 bool is_main_frame) OVERRIDE;
258 virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE; 72 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 73
267 private: 74 private:
268 typedef std::vector<scoped_refptr<history::HistoryAddPageArgs> >
269 AddPageVector;
270
271 // Message from renderer indicating the page has suggestions. 75 // Message from renderer indicating the page has suggestions.
272 void OnSetSuggestions( 76 void OnSetSuggestions(
273 int32 page_id, 77 int page_id,
274 const std::vector<std::string>& suggestions, 78 const std::vector<std::string>& suggestions,
275 InstantCompleteBehavior behavior); 79 InstantCompleteBehavior behavior);
276 80
277 // Messages from the renderer when we've determined whether the page supports 81 // Message from the renderer determining whether it supports the Instant API.
278 // instant. 82 void OnInstantSupportDetermined(int page_id, bool result);
279 void OnInstantSupportDetermined(int32 page_id, bool result);
280 83
281 void CommitFromMouseReleaseIfNecessary(); 84 void CommitFromMouseReleaseIfNecessary();
85 void MaybeSetAndNotifyInstantSupportDetermined(bool supports_instant);
282 86
283 InstantLoader* loader_; 87 InstantLoader* loader_;
284 88
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. 89 // True if the mouse is down from an activate.
302 bool is_mouse_down_from_activate_; 90 bool is_mouse_down_from_activate_;
303 91
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); 92 DISALLOW_COPY_AND_ASSIGN(WebContentsDelegateImpl);
308 }; 93 };
309 94
310 InstantLoader::WebContentsDelegateImpl::WebContentsDelegateImpl( 95 InstantLoader::WebContentsDelegateImpl::WebContentsDelegateImpl(
311 InstantLoader* loader) 96 InstantLoader* loader)
312 : content::WebContentsObserver(loader->preview_contents()->web_contents()), 97 : content::WebContentsObserver(loader->preview_contents_->web_contents()),
313 loader_(loader), 98 loader_(loader),
314 registered_render_widget_host_(NULL), 99 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 } 100 }
322 101
323 void InstantLoader::WebContentsDelegateImpl::PrepareForNewLoad() { 102 bool InstantLoader::WebContentsDelegateImpl::ShouldFocusConstrainedWindow() {
324 user_typed_before_load_ = false; 103 // Return false so that constrained windows are not initially focused. If we
325 waiting_for_new_page_ = true; 104 // did otherwise the preview would prematurely get committed when focus goes
326 add_page_vector_.clear(); 105 // to the constrained window.
327 UnregisterForPaintNotifications(); 106 return false;
328 } 107 }
329 108
330 void InstantLoader::WebContentsDelegateImpl::PreviewPainted() { 109 void InstantLoader::WebContentsDelegateImpl::SwapTabContents(
331 loader_->PreviewPainted(); 110 TabContents* old_tc,
332 } 111 TabContents* new_tc) {
333 112 // If this is being called, something is swapping in to our preview_contents_
334 void InstantLoader::WebContentsDelegateImpl::SetLastHistoryURLAndPrune( 113 // before we've added it to the tab strip.
335 const GURL& url) { 114 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 } 115 }
469 116
470 bool InstantLoader::WebContentsDelegateImpl::ShouldSuppressDialogs() { 117 bool InstantLoader::WebContentsDelegateImpl::ShouldSuppressDialogs() {
471 // Any message shown during instant cancels instant, so we suppress them. 118 // Any message shown during Instant cancels Instant, so we suppress them.
472 return true; 119 return true;
473 } 120 }
474 121
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() { 122 bool InstantLoader::WebContentsDelegateImpl::ShouldFocusPageAfterCrash() {
486 return false; 123 return false;
487 } 124 }
488 125
489 void InstantLoader::WebContentsDelegateImpl::WebContentsFocused(
490 WebContents* contents) {
491 loader_->delegate_->InstantLoaderContentsFocused();
492 }
493
494 void InstantLoader::WebContentsDelegateImpl::LostCapture() { 126 void InstantLoader::WebContentsDelegateImpl::LostCapture() {
495 CommitFromMouseReleaseIfNecessary(); 127 CommitFromMouseReleaseIfNecessary();
496 } 128 }
497 129
498 void InstantLoader::WebContentsDelegateImpl::DragEnded() { 130 void InstantLoader::WebContentsDelegateImpl::WebContentsFocused(
499 CommitFromMouseReleaseIfNecessary(); 131 content::WebContents* contents) {
132 loader_->loader_delegate_->InstantLoaderContentsFocused(loader_);
500 } 133 }
501 134
502 bool InstantLoader::WebContentsDelegateImpl::CanDownload( 135 bool InstantLoader::WebContentsDelegateImpl::CanDownload(
503 RenderViewHost* render_view_host, 136 content::RenderViewHost* render_view_host,
504 int request_id, 137 int request_id,
505 const std::string& request_method) { 138 const std::string& request_method) {
506 // Downloads are disabled. 139 // Downloads are disabled.
507 return false; 140 return false;
508 } 141 }
509 142
510 void InstantLoader::WebContentsDelegateImpl::HandleMouseUp() { 143 void InstantLoader::WebContentsDelegateImpl::HandleMouseUp() {
511 CommitFromMouseReleaseIfNecessary(); 144 CommitFromMouseReleaseIfNecessary();
512 } 145 }
513 146
514 void InstantLoader::WebContentsDelegateImpl::HandleMouseActivate() { 147 void InstantLoader::WebContentsDelegateImpl::HandleMouseActivate() {
515 is_mouse_down_from_activate_ = true; 148 is_mouse_down_from_activate_ = true;
516 } 149 }
517 150
151 void InstantLoader::WebContentsDelegateImpl::DragEnded() {
152 // If the user drags, we won't get a mouse up (at least on Linux). Commit the
153 // Instant result when the drag ends, so that during the drag the page won't
154 // move around.
155 CommitFromMouseReleaseIfNecessary();
156 }
157
518 bool InstantLoader::WebContentsDelegateImpl::OnGoToEntryOffset(int offset) { 158 bool InstantLoader::WebContentsDelegateImpl::OnGoToEntryOffset(int offset) {
519 return false; 159 return false;
520 } 160 }
521 161
522 bool InstantLoader::WebContentsDelegateImpl::ShouldAddNavigationToHistory( 162 bool InstantLoader::WebContentsDelegateImpl::ShouldAddNavigationToHistory(
523 const history::HistoryAddPageArgs& add_page_args, 163 const history::HistoryAddPageArgs& add_page_args,
524 content::NavigationType navigation_type) { 164 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; 165 return false;
535 } 166 }
536 167
537 // If this is being called, something is swapping in to our preview_contents_ 168 void InstantLoader::WebContentsDelegateImpl::DidFinishLoad(
538 // before we've added it to the tab strip. 169 int64 frame_id,
539 void InstantLoader::WebContentsDelegateImpl::SwapTabContents( 170 const GURL& validated_url,
540 TabContents* old_tc, 171 bool is_main_frame) {
541 TabContents* new_tc) { 172 if (is_main_frame && !loader_->supports_instant_) {
542 loader_->ReplacePreviewContents(old_tc, new_tc); 173 Send(new ChromeViewMsg_DetermineIfPageSupportsInstant(routing_id()));
543 } 174 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 } 175 }
560 } 176 }
561 177
562 bool InstantLoader::WebContentsDelegateImpl::OnMessageReceived( 178 bool InstantLoader::WebContentsDelegateImpl::OnMessageReceived(
563 const IPC::Message& message) { 179 const IPC::Message& message) {
564 bool handled = true; 180 bool handled = true;
565 IPC_BEGIN_MESSAGE_MAP(WebContentsDelegateImpl, message) 181 IPC_BEGIN_MESSAGE_MAP(WebContentsDelegateImpl, message)
566 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetSuggestions, OnSetSuggestions) 182 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetSuggestions, OnSetSuggestions)
567 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_InstantSupportDetermined, 183 IPC_MESSAGE_HANDLER(ChromeViewHostMsg_InstantSupportDetermined,
568 OnInstantSupportDetermined) 184 OnInstantSupportDetermined)
569 IPC_MESSAGE_UNHANDLED(handled = false) 185 IPC_MESSAGE_UNHANDLED(handled = false)
570 IPC_END_MESSAGE_MAP() 186 IPC_END_MESSAGE_MAP()
571 return handled; 187 return handled;
572 } 188 }
573 189
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( 190 void InstantLoader::WebContentsDelegateImpl::OnSetSuggestions(
590 int32 page_id, 191 int32 page_id,
591 const std::vector<std::string>& suggestions, 192 const std::vector<std::string>& suggestions,
592 InstantCompleteBehavior behavior) { 193 InstantCompleteBehavior behavior) {
593 TabContents* source = loader_->preview_contents(); 194 content::NavigationEntry* entry = loader_->preview_contents_->web_contents()->
594 NavigationEntry* entry = 195 GetController().GetActiveEntry();
595 source->web_contents()->GetController().GetActiveEntry(); 196 if (entry && page_id == entry->GetPageID()) {
596 if (!entry || page_id != entry->GetPageID()) 197 MaybeSetAndNotifyInstantSupportDetermined(true);
597 return; 198 loader_->loader_delegate_->SetSuggestions(loader_, suggestions, behavior);
598 199 }
599 if (suggestions.empty())
600 loader_->SetCompleteSuggestedText(string16(), behavior);
601 else
602 loader_->SetCompleteSuggestedText(UTF8ToUTF16(suggestions[0]), behavior);
603 } 200 }
604 201
605 void InstantLoader::WebContentsDelegateImpl::OnInstantSupportDetermined( 202 void InstantLoader::WebContentsDelegateImpl::OnInstantSupportDetermined(
606 int32 page_id, 203 int page_id,
607 bool result) { 204 bool result) {
608 WebContents* source = loader_->preview_contents()->web_contents(); 205 content::NavigationEntry* entry = loader_->preview_contents_->web_contents()->
609 if (!source->GetController().GetActiveEntry() || 206 GetController().GetActiveEntry();
610 page_id != source->GetController().GetActiveEntry()->GetPageID()) 207 if (entry && page_id == entry->GetPageID())
208 MaybeSetAndNotifyInstantSupportDetermined(result);
209 }
210
211
212 void InstantLoader::WebContentsDelegateImpl
213 ::CommitFromMouseReleaseIfNecessary() {
214 if (is_mouse_down_from_activate_) {
215 is_mouse_down_from_activate_ = false;
216 loader_->loader_delegate_->CommitInstantLoader(loader_);
217 }
218 }
219
220 void InstantLoader::WebContentsDelegateImpl
221 ::MaybeSetAndNotifyInstantSupportDetermined(bool supports_instant) {
222 // If we already determined that the loader supports Instant, nothing to do.
223 if (loader_->supports_instant_)
611 return; 224 return;
612 225
613 content::Details<const bool> details(&result); 226 loader_->supports_instant_ = supports_instant;
227 loader_->loader_delegate_->InstantSupportDetermined(loader_,
228 supports_instant);
229 content::Details<const bool> details(&supports_instant);
614 content::NotificationService::current()->Notify( 230 content::NotificationService::current()->Notify(
615 chrome::NOTIFICATION_INSTANT_SUPPORT_DETERMINED, 231 chrome::NOTIFICATION_INSTANT_SUPPORT_DETERMINED,
616 content::NotificationService::AllSources(), 232 content::NotificationService::AllSources(),
617 details); 233 details);
618 234
619 if (result) 235 // If the page doesn't support the Instant API, InstantController schedules
620 loader_->PageFinishedLoading(); 236 // the loader for destruction. Stop sending the controller any more messages,
621 else 237 // by severing the connection from the WebContents to us (its delegate).
622 loader_->PageDoesntSupportInstant(user_typed_before_load_); 238 if (!supports_instant)
623 } 239 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 } 240 }
632 241
633 // InstantLoader --------------------------------------------------------------- 242 // InstantLoader ---------------------------------------------------------------
634 243
635 InstantLoader::InstantLoader(InstantLoaderDelegate* delegate, 244 InstantLoader::InstantLoader(InstantLoaderDelegate* delegate,
636 TemplateURLID id, 245 const string16& loader_id,
637 const std::string& group) 246 const GURL& instant_url,
638 : delegate_(delegate), 247 const TabContents* tab_contents)
639 template_url_id_(id), 248 : loader_delegate_(delegate),
640 ready_(false), 249 loader_id_(loader_id),
641 http_status_ok_(true), 250 preview_contents_(new TabContents(content::WebContents::Create(
642 last_transition_type_(content::PAGE_TRANSITION_LINK), 251 tab_contents->profile(), NULL, MSG_ROUTING_NONE,
643 verbatim_(false), 252 tab_contents->web_contents(),
644 needs_reload_(false), 253 tab_contents->web_contents()->GetController().
645 group_(group) { 254 GetSessionStorageNamespace()))),
255 preview_delegate_(new WebContentsDelegateImpl(
256 ALLOW_THIS_IN_INITIALIZER_LIST(this))),
257 supports_instant_(false),
258 instant_url_(instant_url) {
259 SetupPreviewContents();
260 preview_contents_->web_contents()->GetController().LoadURL(instant_url,
261 content::Referrer(), content::PAGE_TRANSITION_GENERATED,
262 "X-Purpose: Instant");
263 preview_contents_->web_contents()->WasHidden();
646 } 264 }
647 265
648 InstantLoader::~InstantLoader() { 266 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()) 267 if (preview_contents())
654 AddPreviewUsageForHistogram(template_url_id_, PREVIEW_DELETED, group_); 268 preview_contents_->web_contents()->SetDelegate(NULL);
655 preview_contents_.reset();
656 } 269 }
657 270
658 bool InstantLoader::Update(TabContents* tab_contents, 271 void InstantLoader::Update(const std::string& user_text, bool verbatim) {
659 const TemplateURL* template_url, 272 // TODO: Support real cursor position.
660 const GURL& url, 273 content::RenderViewHost* rvh =
661 content::PageTransition transition_type, 274 preview_contents_->web_contents()->GetRenderViewHost();
662 const string16& user_text, 275 rvh->Send(new ChromeViewMsg_SearchBoxChange(rvh->GetRoutingID(), user_text,
663 bool verbatim, 276 verbatim, user_text.size(), user_text.size()));
664 string16* suggested_text) {
665 DCHECK(!url.is_empty() && url.is_valid());
666
667 // Strip leading ?.
668 string16 new_user_text =
669 !user_text.empty() && (UTF16ToWide(user_text)[0] == L'?') ?
670 user_text.substr(1) : user_text;
671
672 // We should preserve the transition type regardless of whether we're already
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 } 277 }
755 278
756 void InstantLoader::SetOmniboxBounds(const gfx::Rect& bounds) { 279 void InstantLoader::SetOmniboxBounds(const gfx::Rect& bounds) {
757 if (omnibox_bounds_ == bounds) 280 content::RenderViewHost* rvh =
758 return; 281 preview_contents_->web_contents()->GetRenderViewHost();
759 282 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 } 283 }
781 284
782 bool InstantLoader::IsMouseDownFromActivate() { 285 TabContents* InstantLoader::ReleasePreviewContents(InstantCommitType type,
783 return preview_tab_contents_delegate_.get() && 286 const std::string& text) {
784 preview_tab_contents_delegate_->is_mouse_down_from_activate(); 287 content::RenderViewHost* rvh =
785 } 288 preview_contents_->web_contents()->GetRenderViewHost();
786 289 if (type == INSTANT_COMMIT_PRESSED_ENTER) {
787 TabContents* InstantLoader::ReleasePreviewContents( 290 rvh->Send(new ChromeViewMsg_SearchBoxSubmit(rvh->GetRoutingID(), text));
788 InstantCommitType type, 291 } else {
789 TabContents* tab_contents) { 292 rvh->Send(new ChromeViewMsg_SearchBoxCancel(rvh->GetRoutingID(), text));
790 if (!preview_contents_.get())
791 return NULL;
792
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 } 293 }
808 omnibox_bounds_ = gfx::Rect(); 294 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(); 295 return preview_contents_.release();
855 } 296 }
856 297
857 bool InstantLoader::ShouldCommitInstantOnMouseUp() { 298 bool InstantLoader::IsMouseDownFromActivate() const {
858 return delegate_->ShouldCommitInstantOnMouseUp(); 299 return preview_delegate_->is_mouse_down_from_activate();
859 } 300 }
860 301
861 void InstantLoader::CommitInstantLoader() { 302 #if defined(OS_MACOSX)
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 }
889
890 void InstantLoader::Observe(int type, 303 void InstantLoader::Observe(int type,
891 const content::NotificationSource& source, 304 const content::NotificationSource& source,
892 const content::NotificationDetails& details) { 305 const content::NotificationDetails& details) {
893 #if defined(OS_MACOSX)
894 if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) { 306 if (type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED) {
895 if (preview_contents_->web_contents()->GetRenderWidgetHostView()) { 307 if (content::RenderWidgetHostView* rwhv =
896 preview_contents_->web_contents()->GetRenderWidgetHostView()-> 308 preview_contents_->web_contents()->GetRenderWidgetHostView()) {
897 SetTakesFocusOnlyOnMouseDown(true); 309 rwhv->SetTakesFocusOnlyOnMouseDown(true);
898 } 310 }
899 return; 311 return;
900 } 312 }
313 NOTREACHED();
314 }
901 #endif 315 #endif
902 if (type == content::NOTIFICATION_NAV_ENTRY_COMMITTED) { 316
903 content::LoadCommittedDetails* load_details = 317 void InstantLoader::SetupPreviewContents() {
904 content::Details<content::LoadCommittedDetails>(details).ptr(); 318 content::WebContents* new_contents = preview_contents_->web_contents();
905 if (load_details->is_main_frame) { 319 WebContentsDelegateImpl* new_delegate = preview_delegate_.get();
906 if (load_details->http_status_code == kHostBlacklistStatusCode) { 320 new_contents->SetDelegate(new_delegate);
907 delegate_->AddToBlacklist(this, load_details->entry->GetURL()); 321
908 } else { 322 // Disable popups and such (mainly to avoid losing focus and committing the
909 SetHTTPStatusOK(load_details->http_status_code == 200); 323 // preview prematurely).
910 } 324 preview_contents_->blocked_content_tab_helper()->SetAllContentsBlocked(true);
911 } 325 preview_contents_->constrained_window_tab_helper()->set_delegate(
912 return; 326 new_delegate);
327 preview_contents_->content_settings()->SetPopupsBlocked(true);
328 preview_contents_->core_tab_helper()->set_delegate(new_delegate);
329 if (ThumbnailGenerator* tg = preview_contents_->thumbnail_generator())
330 tg->set_enabled(false);
331
332 #if defined(OS_MACOSX)
333 // If |preview_contents_| does not currently have a RWHV, we will call
334 // |SetTakesFocusOnlyOnMouseDown| as a result of the RENDER_VIEW_HOST_CHANGED
335 // notification.
336 if (content::RenderWidgetHostView* rwhv =
337 new_contents->GetRenderWidgetHostView()) {
338 rwhv->SetTakesFocusOnlyOnMouseDown(true);
913 } 339 }
914 340 registrar_.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
915 NOTREACHED() << "Got a notification we didn't register for."; 341 content::Source<content::NavigationController>(
342 &new_contents->GetController()));
343 #endif
916 } 344 }
917 345
918 void InstantLoader::SetCompleteSuggestedText( 346 void InstantLoader::CleanupPreviewContents() {
919 const string16& complete_suggested_text, 347 content::WebContents* old_contents = preview_contents_->web_contents();
920 InstantCompleteBehavior behavior) { 348 old_contents->SetDelegate(NULL);
921 if (!is_showing_instant()) { 349
922 // We're not trying to use the instant API with this page. Ignore it. 350 preview_contents_->blocked_content_tab_helper()->SetAllContentsBlocked(false);
923 return; 351 preview_contents_->constrained_window_tab_helper()->set_delegate(NULL);
352 preview_contents_->content_settings()->SetPopupsBlocked(false);
353 preview_contents_->core_tab_helper()->set_delegate(NULL);
354 if (ThumbnailGenerator* tg = preview_contents_->thumbnail_generator())
355 tg->set_enabled(true);
356
357 #if defined(OS_MACOSX)
358 if (content::RenderWidgetHostView* rwhv =
359 old_contents->GetRenderWidgetHostView()) {
360 rwhv->SetTakesFocusOnlyOnMouseDown(false);
924 } 361 }
925 362 registrar_.Remove(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED,
926 ShowPreview(); 363 content::Source<content::NavigationController>(
927 364 &old_contents->GetController()));
928 if (complete_suggested_text == complete_suggested_text_) 365 #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 }
965
966 void InstantLoader::PreviewPainted() {
967 // If instant is supported then we wait for the first suggest result before
968 // showing the page.
969 if (!template_url_id_)
970 ShowPreview();
971 }
972
973 void InstantLoader::SetHTTPStatusOK(bool is_ok) {
974 if (is_ok == http_status_ok_)
975 return;
976
977 http_status_ok_ = is_ok;
978 if (ready_)
979 delegate_->InstantStatusChanged(this);
980 }
981
982 void InstantLoader::ShowPreview() {
983 if (!ready_) {
984 ready_ = true;
985 delegate_->InstantStatusChanged(this);
986 AddPreviewUsageForHistogram(template_url_id_, PREVIEW_SHOWN, group_);
987 }
988 }
989
990 void InstantLoader::PageFinishedLoading() {
991 frame_load_observer_.reset();
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 } 366 }
1051 367
1052 void InstantLoader::ReplacePreviewContents(TabContents* old_tc, 368 void InstantLoader::ReplacePreviewContents(TabContents* old_tc,
1053 TabContents* new_tc) { 369 TabContents* new_tc) {
1054 DCHECK(old_tc == preview_contents_); 370 DCHECK(old_tc == preview_contents_);
1055 // We release here without deleting so that the caller still has reponsibility 371 CleanupPreviewContents();
1056 // for deleting the TabContents. 372 // We release here without deleting so that the caller still has the
373 // responsibility for deleting the TabContents.
1057 ignore_result(preview_contents_.release()); 374 ignore_result(preview_contents_.release());
1058 preview_contents_.reset(new_tc); 375 preview_contents_.reset(new_tc);
1059 session_storage_namespace_ = GetSessionStorageNamespace(new_tc); 376 SetupPreviewContents();
1060 377 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 } 378 }
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