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

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

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

Powered by Google App Engine
This is Rietveld 408576698