Don't preload rarely seen large images
[chromium-blink-merge.git] / components / html_viewer / html_document.cc
blob8604821ba35bed43ec87fd8829e4fc8bf8b961a2
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/html_viewer/html_document.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/location.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/stl_util.h"
13 #include "base/strings/string_util.h"
14 #include "base/thread_task_runner_handle.h"
15 #include "components/devtools_service/public/cpp/switches.h"
16 #include "components/html_viewer/blink_input_events_type_converters.h"
17 #include "components/html_viewer/blink_url_request_type_converters.h"
18 #include "components/html_viewer/devtools_agent_impl.h"
19 #include "components/html_viewer/global_state.h"
20 #include "components/html_viewer/media_factory.h"
21 #include "components/html_viewer/web_layer_tree_view_impl.h"
22 #include "components/html_viewer/web_storage_namespace_impl.h"
23 #include "components/html_viewer/web_url_loader_impl.h"
24 #include "components/view_manager/public/cpp/view.h"
25 #include "components/view_manager/public/cpp/view_manager.h"
26 #include "components/view_manager/public/cpp/view_property.h"
27 #include "components/view_manager/public/interfaces/surfaces.mojom.h"
28 #include "mojo/application/public/cpp/application_impl.h"
29 #include "mojo/application/public/cpp/connect.h"
30 #include "mojo/application/public/interfaces/shell.mojom.h"
31 #include "mojo/converters/geometry/geometry_type_converters.h"
32 #include "skia/ext/refptr.h"
33 #include "third_party/WebKit/public/platform/Platform.h"
34 #include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h"
35 #include "third_party/WebKit/public/platform/WebSize.h"
36 #include "third_party/WebKit/public/web/WebConsoleMessage.h"
37 #include "third_party/WebKit/public/web/WebDocument.h"
38 #include "third_party/WebKit/public/web/WebElement.h"
39 #include "third_party/WebKit/public/web/WebInputEvent.h"
40 #include "third_party/WebKit/public/web/WebLocalFrame.h"
41 #include "third_party/WebKit/public/web/WebRemoteFrame.h"
42 #include "third_party/WebKit/public/web/WebRemoteFrameClient.h"
43 #include "third_party/WebKit/public/web/WebScriptSource.h"
44 #include "third_party/WebKit/public/web/WebSettings.h"
45 #include "third_party/WebKit/public/web/WebView.h"
46 #include "third_party/mojo/src/mojo/public/cpp/system/data_pipe.h"
47 #include "third_party/skia/include/core/SkCanvas.h"
48 #include "third_party/skia/include/core/SkColor.h"
49 #include "third_party/skia/include/core/SkDevice.h"
50 #include "ui/gfx/geometry/dip_util.h"
51 #include "ui/gfx/geometry/size.h"
53 using blink::WebString;
54 using mojo::AxProvider;
55 using mojo::Rect;
56 using mojo::ServiceProviderPtr;
57 using mojo::URLResponsePtr;
58 using mojo::View;
59 using mojo::ViewManager;
60 using mojo::WeakBindToRequest;
62 namespace html_viewer {
63 namespace {
65 bool EnableRemoteDebugging() {
66 return base::CommandLine::ForCurrentProcess()->HasSwitch(
67 devtools_service::kRemoteDebuggingPort);
70 // WebRemoteFrameClient implementation used for OOPIFs.
71 // TODO(sky): this needs to talk to browser by way of an interface.
72 class RemoteFrameClientImpl : public blink::WebRemoteFrameClient {
73 public:
74 explicit RemoteFrameClientImpl(mojo::View* view) : view_(view) {}
75 ~RemoteFrameClientImpl() {}
77 // WebRemoteFrameClient methods:
78 virtual void postMessageEvent(blink::WebLocalFrame* source_frame,
79 blink::WebRemoteFrame* target_frame,
80 blink::WebSecurityOrigin target_origin,
81 blink::WebDOMMessageEvent event) {}
82 virtual void initializeChildFrame(const blink::WebRect& frame_rect,
83 float scale_factor) {
84 mojo::Rect rect;
85 rect.x = frame_rect.x;
86 rect.y = frame_rect.y;
87 rect.width = frame_rect.width;
88 rect.height = frame_rect.height;
89 view_->SetBounds(rect);
91 virtual void navigate(const blink::WebURLRequest& request,
92 bool should_replace_current_entry) {}
93 virtual void reload(bool ignore_cache, bool is_client_redirect) {}
95 virtual void forwardInputEvent(const blink::WebInputEvent* event) {}
97 private:
98 mojo::View* const view_;
100 DISALLOW_COPY_AND_ASSIGN(RemoteFrameClientImpl);
103 void ConfigureSettings(blink::WebSettings* settings) {
104 settings->setCookieEnabled(true);
105 settings->setDefaultFixedFontSize(13);
106 settings->setDefaultFontSize(16);
107 settings->setLoadsImagesAutomatically(true);
108 settings->setJavaScriptEnabled(true);
111 mojo::Target WebNavigationPolicyToNavigationTarget(
112 blink::WebNavigationPolicy policy) {
113 switch (policy) {
114 case blink::WebNavigationPolicyCurrentTab:
115 return mojo::TARGET_SOURCE_NODE;
116 case blink::WebNavigationPolicyNewBackgroundTab:
117 case blink::WebNavigationPolicyNewForegroundTab:
118 case blink::WebNavigationPolicyNewWindow:
119 case blink::WebNavigationPolicyNewPopup:
120 return mojo::TARGET_NEW_NODE;
121 default:
122 return mojo::TARGET_DEFAULT;
126 bool CanNavigateLocally(blink::WebFrame* frame,
127 const blink::WebURLRequest& request) {
128 // For now, we just load child frames locally.
129 if (frame->parent())
130 return true;
132 // If we have extraData() it means we already have the url response
133 // (presumably because we are being called via Navigate()). In that case we
134 // can go ahead and navigate locally.
135 if (request.extraData())
136 return true;
138 // Otherwise we don't know if we're the right app to handle this request. Ask
139 // host to do the navigation for us.
140 return false;
143 } // namespace
145 HTMLDocument::CreateParams::CreateParams(
146 mojo::ApplicationImpl* html_document_app,
147 mojo::ApplicationConnection* connection,
148 mojo::URLResponsePtr response,
149 GlobalState* global_state,
150 const DeleteCallback& delete_callback)
151 : html_document_app(html_document_app),
152 connection(connection),
153 response(response.Pass()),
154 global_state(global_state),
155 delete_callback(delete_callback) {
158 HTMLDocument::CreateParams::~CreateParams() {
161 HTMLDocument::HTMLDocument(HTMLDocument::CreateParams* params)
162 : app_refcount_(params->html_document_app->app_lifetime_helper()
163 ->CreateAppRefCount()),
164 html_document_app_(params->html_document_app),
165 response_(params->response.Pass()),
166 navigator_host_(params->connection->GetServiceProvider()),
167 web_view_(nullptr),
168 root_(nullptr),
169 view_manager_client_factory_(params->html_document_app->shell(), this),
170 global_state_(params->global_state),
171 delete_callback_(params->delete_callback) {
172 params->connection->AddService(
173 static_cast<InterfaceFactory<mojo::AxProvider>*>(this));
174 params->connection->AddService(&view_manager_client_factory_);
176 if (global_state_->did_init())
177 Load(response_.Pass());
180 void HTMLDocument::Destroy() {
181 // See comment in header for a description of lifetime.
182 if (root_) {
183 // Deleting the ViewManager calls back to OnViewManagerDestroyed() and
184 // triggers deletion.
185 delete root_->view_manager();
186 } else {
187 delete this;
191 HTMLDocument::~HTMLDocument() {
192 delete_callback_.Run(this);
194 STLDeleteElements(&ax_providers_);
195 STLDeleteElements(&ax_provider_requests_);
197 if (web_view_)
198 web_view_->close();
199 if (root_)
200 root_->RemoveObserver(this);
203 void HTMLDocument::OnEmbed(View* root) {
204 DCHECK(!global_state_->is_headless());
205 root_ = root;
206 root_->AddObserver(this);
207 UpdateFocus();
209 InitGlobalStateAndLoadIfNecessary();
212 void HTMLDocument::OnViewManagerDestroyed(ViewManager* view_manager) {
213 delete this;
216 void HTMLDocument::Create(mojo::ApplicationConnection* connection,
217 mojo::InterfaceRequest<AxProvider> request) {
218 if (!did_finish_load_) {
219 // Cache AxProvider interface requests until the document finishes loading.
220 auto cached_request = new mojo::InterfaceRequest<AxProvider>();
221 *cached_request = request.Pass();
222 ax_provider_requests_.insert(cached_request);
223 } else {
224 ax_providers_.insert(
225 new AxProviderImpl(web_view_, request.Pass()));
229 void HTMLDocument::Load(URLResponsePtr response) {
230 DCHECK(!web_view_);
231 web_view_ = blink::WebView::create(this);
232 touch_handler_.reset(new TouchHandler(web_view_));
233 web_layer_tree_view_impl_->set_widget(web_view_);
234 ConfigureSettings(web_view_->settings());
236 blink::WebLocalFrame* main_frame =
237 blink::WebLocalFrame::create(blink::WebTreeScopeType::Document, this);
238 web_view_->setMainFrame(main_frame);
240 // TODO(yzshen): http://crbug.com/498986 Creating DevToolsAgentImpl instances
241 // causes html_viewer_apptests flakiness currently. Before we fix that we
242 // cannot enable remote debugging (which is required by Telemetry tests) on
243 // the bots.
244 if (EnableRemoteDebugging()) {
245 devtools_agent_.reset(
246 new DevToolsAgentImpl(main_frame, html_document_app_->shell()));
249 GURL url(response->url);
251 WebURLRequestExtraData* extra_data = new WebURLRequestExtraData;
252 extra_data->synthetic_response = response.Pass();
254 blink::WebURLRequest web_request;
255 web_request.initialize();
256 web_request.setURL(url);
257 web_request.setExtraData(extra_data);
259 web_view_->mainFrame()->loadRequest(web_request);
260 UpdateFocus();
263 void HTMLDocument::UpdateWebviewSizeFromViewSize() {
264 web_view_->setDeviceScaleFactor(global_state_->device_pixel_ratio());
265 const gfx::Size size_in_pixels(root_->bounds().width, root_->bounds().height);
266 const gfx::Size size_in_dips = gfx::ConvertSizeToDIP(
267 root_->viewport_metrics().device_pixel_ratio, size_in_pixels);
268 web_view_->resize(
269 blink::WebSize(size_in_dips.width(), size_in_dips.height()));
270 web_layer_tree_view_impl_->setViewportSize(size_in_pixels);
273 void HTMLDocument::InitGlobalStateAndLoadIfNecessary() {
274 DCHECK(root_);
275 if (root_->viewport_metrics().device_pixel_ratio == 0.f)
276 return;
278 if (!web_view_) {
279 global_state_->InitIfNecessary(
280 root_->viewport_metrics().size_in_pixels.To<gfx::Size>(),
281 root_->viewport_metrics().device_pixel_ratio);
282 Load(response_.Pass());
285 UpdateWebviewSizeFromViewSize();
286 web_layer_tree_view_impl_->set_view(root_);
289 blink::WebStorageNamespace* HTMLDocument::createSessionStorageNamespace() {
290 return new WebStorageNamespaceImpl();
293 void HTMLDocument::initializeLayerTreeView() {
294 if (global_state_->is_headless()) {
295 web_layer_tree_view_impl_.reset(
296 new WebLayerTreeViewImpl(global_state_->compositor_thread(), nullptr,
297 nullptr, nullptr, nullptr));
298 return;
301 mojo::URLRequestPtr request(mojo::URLRequest::New());
302 request->url = mojo::String::From("mojo:surfaces_service");
303 mojo::SurfacePtr surface;
304 html_document_app_->ConnectToService(request.Pass(), &surface);
306 // TODO(jamesr): Should be mojo:gpu_service
307 mojo::URLRequestPtr request2(mojo::URLRequest::New());
308 request2->url = mojo::String::From("mojo:view_manager");
309 mojo::GpuPtr gpu_service;
310 html_document_app_->ConnectToService(request2.Pass(), &gpu_service);
311 web_layer_tree_view_impl_.reset(new WebLayerTreeViewImpl(
312 global_state_->compositor_thread(),
313 global_state_->gpu_memory_buffer_manager(),
314 global_state_->raster_thread_helper()->task_graph_runner(),
315 surface.Pass(), gpu_service.Pass()));
318 blink::WebLayerTreeView* HTMLDocument::layerTreeView() {
319 return web_layer_tree_view_impl_.get();
322 blink::WebMediaPlayer* HTMLDocument::createMediaPlayer(
323 blink::WebLocalFrame* frame,
324 const blink::WebURL& url,
325 blink::WebMediaPlayerClient* client,
326 blink::WebContentDecryptionModule* initial_cdm) {
327 return global_state_->media_factory()->CreateMediaPlayer(
328 frame, url, client, initial_cdm, html_document_app_->shell());
331 blink::WebFrame* HTMLDocument::createChildFrame(
332 blink::WebLocalFrame* parent,
333 blink::WebTreeScopeType scope,
334 const blink::WebString& frameName,
335 blink::WebSandboxFlags sandboxFlags) {
336 blink::WebLocalFrame* child_frame = blink::WebLocalFrame::create(scope, this);
337 parent->appendChild(child_frame);
338 return child_frame;
341 void HTMLDocument::frameDetached(blink::WebFrame* frame) {
342 frameDetached(frame, DetachType::Remove);
345 void HTMLDocument::frameDetached(blink::WebFrame* frame, DetachType type) {
346 DCHECK(type == DetachType::Remove);
347 if (frame->parent())
348 frame->parent()->removeChild(frame);
350 if (devtools_agent_ && frame == devtools_agent_->frame())
351 devtools_agent_.reset();
353 // |frame| is invalid after here.
354 frame->close();
357 blink::WebCookieJar* HTMLDocument::cookieJar(blink::WebLocalFrame* frame) {
358 // TODO(darin): Blink does not fallback to the Platform provided WebCookieJar.
359 // Either it should, as it once did, or we should find another solution here.
360 return blink::Platform::current()->cookieJar();
363 blink::WebNavigationPolicy HTMLDocument::decidePolicyForNavigation(
364 const NavigationPolicyInfo& info) {
365 // TODO(yzshen): Remove this check once the browser is able to navigate an
366 // existing html_viewer instance and about:blank page support is ready.
367 if (devtools_agent_ && devtools_agent_->frame() == info.frame &&
368 devtools_agent_->handling_page_navigate_request()) {
369 return info.defaultPolicy;
372 std::string frame_name = info.frame ? info.frame->assignedName().utf8() : "";
374 if (CanNavigateLocally(info.frame, info.urlRequest))
375 return info.defaultPolicy;
377 if (navigator_host_.get()) {
378 mojo::URLRequestPtr url_request = mojo::URLRequest::From(info.urlRequest);
379 navigator_host_->RequestNavigate(
380 WebNavigationPolicyToNavigationTarget(info.defaultPolicy),
381 url_request.Pass());
384 return blink::WebNavigationPolicyIgnore;
387 void HTMLDocument::didAddMessageToConsole(
388 const blink::WebConsoleMessage& message,
389 const blink::WebString& source_name,
390 unsigned source_line,
391 const blink::WebString& stack_trace) {
392 VLOG(1) << "[" << source_name.utf8() << "(" << source_line << ")] "
393 << message.text.utf8();
396 void HTMLDocument::didFinishLoad(blink::WebLocalFrame* frame) {
397 // TODO(msw): Notify AxProvider clients of updates on child frame loads.
398 did_finish_load_ = true;
399 // Bind any pending AxProviderImpl interface requests.
400 for (auto it : ax_provider_requests_)
401 ax_providers_.insert(new AxProviderImpl(web_view_, it->Pass()));
402 STLDeleteElements(&ax_provider_requests_);
405 void HTMLDocument::didNavigateWithinPage(
406 blink::WebLocalFrame* frame,
407 const blink::WebHistoryItem& history_item,
408 blink::WebHistoryCommitType commit_type) {
409 if (navigator_host_.get())
410 navigator_host_->DidNavigateLocally(history_item.urlString().utf8());
413 blink::WebEncryptedMediaClient* HTMLDocument::encryptedMediaClient() {
414 return global_state_->media_factory()->GetEncryptedMediaClient();
417 void HTMLDocument::OnViewBoundsChanged(View* view,
418 const Rect& old_bounds,
419 const Rect& new_bounds) {
420 DCHECK_EQ(view, root_);
421 UpdateWebviewSizeFromViewSize();
424 void HTMLDocument::OnViewViewportMetricsChanged(
425 mojo::View* view,
426 const mojo::ViewportMetrics& old_metrics,
427 const mojo::ViewportMetrics& new_metrics) {
428 InitGlobalStateAndLoadIfNecessary();
431 void HTMLDocument::OnViewDestroyed(View* view) {
432 DCHECK_EQ(view, root_);
433 root_ = nullptr;
436 void HTMLDocument::OnViewInputEvent(View* view, const mojo::EventPtr& event) {
437 if (event->pointer_data) {
438 // Blink expects coordintes to be in DIPs.
439 event->pointer_data->x /= global_state_->device_pixel_ratio();
440 event->pointer_data->y /= global_state_->device_pixel_ratio();
441 event->pointer_data->screen_x /= global_state_->device_pixel_ratio();
442 event->pointer_data->screen_y /= global_state_->device_pixel_ratio();
445 if ((event->action == mojo::EVENT_TYPE_POINTER_DOWN ||
446 event->action == mojo::EVENT_TYPE_POINTER_UP ||
447 event->action == mojo::EVENT_TYPE_POINTER_CANCEL ||
448 event->action == mojo::EVENT_TYPE_POINTER_MOVE) &&
449 event->pointer_data->kind == mojo::POINTER_KIND_TOUCH) {
450 touch_handler_->OnTouchEvent(*event);
451 return;
453 scoped_ptr<blink::WebInputEvent> web_event =
454 event.To<scoped_ptr<blink::WebInputEvent>>();
455 if (web_event)
456 web_view_->handleInputEvent(*web_event);
459 void HTMLDocument::OnViewFocusChanged(mojo::View* gained_focus,
460 mojo::View* lost_focus) {
461 UpdateFocus();
464 void HTMLDocument::UpdateFocus() {
465 if (!web_view_)
466 return;
467 bool is_focused = root_ && root_->HasFocus();
468 web_view_->setFocus(is_focused);
469 web_view_->setIsActive(is_focused);
472 } // namespace html_viewer