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

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

Powered by Google App Engine
This is Rietveld 408576698