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

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