提交 cb5cca79 编写于 作者: A Adam Barth

Merge pull request #2072 from abarth/rm_sky_viewer

Remove sky_viewer.mojo
......@@ -8,10 +8,6 @@ group("default") {
deps = [
"//sky",
]
if (!is_ios && !is_mac) {
# Mojo shell does not exist on iOS or Mac
deps += [ "//services/sky" ]
}
}
group("dist") {
......
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//mojo/public/mojo_application.gni")
import("//mojo/public/tools/bindings/mojom.gni")
mojo_native_application("sky") {
output_name = "sky_viewer"
sources = [
"content_handler_impl.cc",
"content_handler_impl.h",
"converters/basic_types.cc",
"converters/basic_types.h",
"converters/input_event_types.cc",
"converters/input_event_types.h",
"dart_library_provider_impl.cc",
"dart_library_provider_impl.h",
"document_view.cc",
"document_view.h",
"internals.cc",
"internals.h",
"platform_impl.cc",
"platform_impl.h",
"runtime_flags.cc",
"runtime_flags.h",
"viewer.cc",
]
deps = [
"//mojo/application",
"//mojo/common:tracing_impl",
"//mojo/converters/geometry",
"//mojo/public/cpp/bindings",
"//mojo/public/cpp/system",
"//mojo/public/cpp/utility",
"//mojo/public/interfaces/application",
"//mojo/services/content_handler/interfaces",
"//mojo/services/gpu/interfaces",
"//mojo/services/input_events/interfaces",
"//mojo/services/navigation/interfaces",
"//mojo/services/network/interfaces",
"//mojo/services/service_registry/interfaces",
"//mojo/services/surfaces/interfaces",
"//mojo/services/view_manager/cpp",
"//mojo/services/view_manager/interfaces",
"//services/asset_bundle:lib",
"//services/sky/compositor",
"//skia",
"//sky/engine/public/sky",
"//sky/engine/tonic",
"//sky/engine/web",
"//sky/shell/dart",
"//third_party/icu",
"//url",
]
if (!is_mac && !is_ios) {
# Mac and iOS need to use the system-provided ICU
deps += [ "//mojo/icu" ]
}
}
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
source_set("compositor") {
sources = [
"layer_client.cc",
"layer_client.h",
"layer_host.cc",
"layer_host.h",
"layer_host_client.cc",
"layer_host_client.h",
"rasterizer.cc",
"rasterizer.h",
"rasterizer_bitmap.cc",
"rasterizer_bitmap.h",
"rasterizer_ganesh.cc",
"rasterizer_ganesh.h",
"resource_manager.cc",
"resource_manager.h",
"surface_holder.cc",
"surface_holder.h",
"texture_cache.cc",
"texture_cache.h",
"texture_layer.cc",
"texture_layer.h",
]
deps = [
"//base",
"//mojo/application",
"//mojo/converters/geometry",
"//mojo/gpu",
"//mojo/public/c/gpu",
"//mojo/public/cpp/bindings",
"//mojo/public/cpp/environment",
"//mojo/public/cpp/system",
"//mojo/public/cpp/utility",
"//mojo/public/interfaces/application",
"//mojo/services/geometry/interfaces",
"//mojo/services/surfaces/cpp",
"//mojo/services/surfaces/interfaces",
"//mojo/services/surfaces/interfaces:surface_id",
"//mojo/skia",
"//skia",
"//third_party/libpng",
"//ui/gfx",
"//ui/gfx/geometry",
]
}
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/layer_client.h"
namespace sky {
LayerClient::~LayerClient() {
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_LAYER_CLIENT_H_
#define SKY_VIEWER_COMPOSITOR_LAYER_CLIENT_H_
class SkCanvas;
namespace gfx {
class Rect;
}
namespace sky {
class LayerClient {
public:
virtual void PaintContents(SkCanvas* canvas, const gfx::Rect& clip) = 0;
protected:
virtual ~LayerClient();
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_LAYER_CLIENT_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/layer_host.h"
#include "base/message_loop/message_loop.h"
#include "base/trace_event/trace_event.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/gpu/gl_context.h"
#include "mojo/services/surfaces/cpp/surfaces_utils.h"
#include "mojo/skia/ganesh_context.h"
#include "services/sky/compositor/texture_layer.h"
namespace sky {
LayerHost::LayerHost(LayerHostClient* client)
: client_(client),
state_(kReadyForFrame),
frame_requested_(false),
surface_holder_(this, client->GetShell()),
gl_context_owner_(client->GetShell()),
ganesh_context_(gl_context()),
resource_manager_(gl_context()),
weak_factory_(this) {
}
LayerHost::~LayerHost() {
}
void LayerHost::SetNeedsAnimate() {
if (frame_requested_)
return;
frame_requested_ = true;
if (state_ == kReadyForFrame)
BeginFrameSoon();
}
void LayerHost::SetRootLayer(scoped_refptr<TextureLayer> layer) {
DCHECK(!root_layer_.get());
root_layer_ = layer;
}
void LayerHost::OnSurfaceIdAvailable(mojo::SurfaceIdPtr surface_id) {
client_->OnSurfaceIdAvailable(surface_id.Pass());
}
void LayerHost::ReturnResources(
mojo::Array<mojo::ReturnedResourcePtr> resources) {
resource_manager_.ReturnResources(resources.Pass());
}
void LayerHost::BeginFrameSoon() {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&LayerHost::BeginFrame, weak_factory_.GetWeakPtr()));
}
void LayerHost::BeginFrame() {
TRACE_EVENT0("flutter", "LayerHost::BeginFrame");
DCHECK(frame_requested_);
frame_requested_ = false;
DCHECK_EQ(state_, kReadyForFrame);
state_ = kWaitingForFrameAcknowldgement;
client_->BeginFrame(base::TimeTicks::Now());
// If the root layer is empty, there's no reason to draw into it. (In fact,
// Ganesh will get upset if we try.) Instead, we just schedule the ack that
// the frame is complete.
if (root_layer_->size().IsEmpty()) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&LayerHost::DidCompleteFrame, weak_factory_.GetWeakPtr()));
return;
}
{
mojo::GaneshContext::Scope scope(&ganesh_context_);
ganesh_context_.gr()->resetContext();
root_layer_->Display();
}
// We may have culled the root layer down to nothing which is equivalent to
// the empty size case above.
//
// TODO(jamesr): This needs to have proper flow control as well to avoid
// spinning when we have nothing to draw.
if (!root_layer_->HaveTexture()) {
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&LayerHost::DidCompleteFrame, weak_factory_.GetWeakPtr()));
return;
}
Upload(root_layer_.get());
}
void LayerHost::Upload(TextureLayer* layer) {
TRACE_EVENT0("flutter", "LayerHost::Upload");
gfx::Size size = layer->size();
surface_holder_.SetSize(size);
mojo::FramePtr frame = mojo::Frame::New();
frame->resources.resize(0u);
mojo::Rect bounds;
bounds.width = size.width();
bounds.height = size.height();
mojo::PassPtr pass = mojo::CreateDefaultPass(1, bounds);
pass->quads.resize(0u);
pass->shared_quad_states.push_back(mojo::CreateDefaultSQS(
mojo::TypeConverter<mojo::Size, gfx::Size>::Convert(size)));
mojo::TransferableResourcePtr resource =
resource_manager_.CreateTransferableResource(layer);
mojo::QuadPtr quad = mojo::Quad::New();
quad->material = mojo::Material::TEXTURE_CONTENT;
mojo::RectPtr rect = mojo::Rect::New();
rect->width = size.width();
rect->height = size.height();
quad->rect = rect.Clone();
quad->opaque_rect = rect.Clone();
quad->visible_rect = rect.Clone();
quad->needs_blending = true;
quad->shared_quad_state_index = 0u;
mojo::TextureQuadStatePtr texture_state = mojo::TextureQuadState::New();
texture_state->resource_id = resource->id;
texture_state->premultiplied_alpha = true;
texture_state->uv_top_left = mojo::PointF::New();
texture_state->uv_bottom_right = mojo::PointF::New();
texture_state->uv_bottom_right->x = 1.f;
texture_state->uv_bottom_right->y = 1.f;
texture_state->background_color = mojo::Color::New();
texture_state->background_color->rgba = 0;
for (int i = 0; i < 4; ++i)
texture_state->vertex_opacity.push_back(1.f);
texture_state->flipped = false;
frame->resources.push_back(resource.Pass());
quad->texture_quad_state = texture_state.Pass();
pass->quads.push_back(quad.Pass());
frame->passes.push_back(pass.Pass());
surface_holder_.SubmitFrame(
frame.Pass(),
base::Bind(&LayerHost::DidCompleteFrame, weak_factory_.GetWeakPtr()));
}
void LayerHost::DidCompleteFrame() {
DCHECK_EQ(state_, kWaitingForFrameAcknowldgement);
state_ = kReadyForFrame;
if (frame_requested_)
BeginFrame();
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_LAYER_HOST_H_
#define SKY_VIEWER_COMPOSITOR_LAYER_HOST_H_
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "mojo/gpu/gl_context_owner.h"
#include "mojo/skia/ganesh_context.h"
#include "services/sky/compositor/layer_host_client.h"
#include "services/sky/compositor/resource_manager.h"
#include "services/sky/compositor/surface_holder.h"
namespace sky {
class ResourceManager;
class TextureLayer;
class LayerHostClient;
class LayerHost : public SurfaceHolder::Client {
public:
explicit LayerHost(LayerHostClient* client);
~LayerHost() override;
LayerHostClient* client() const { return client_; }
const base::WeakPtr<mojo::GLContext>& gl_context() const {
return gl_context_owner_.context();
}
mojo::GaneshContext* ganesh_context() const {
return const_cast<mojo::GaneshContext*>(&ganesh_context_);
}
ResourceManager* resource_manager() const {
return const_cast<ResourceManager*>(&resource_manager_);
}
void SetNeedsAnimate();
void SetRootLayer(scoped_refptr<TextureLayer> layer);
private:
enum State {
kReadyForFrame,
kWaitingForFrameAcknowldgement,
};
// SurfaceHolder::Client
void OnSurfaceIdAvailable(mojo::SurfaceIdPtr surface_id) override;
void ReturnResources(
mojo::Array<mojo::ReturnedResourcePtr> resources) override;
void BeginFrameSoon();
void BeginFrame();
void Upload(TextureLayer* layer);
void DidCompleteFrame();
LayerHostClient* client_;
State state_;
bool frame_requested_;
SurfaceHolder surface_holder_;
mojo::GLContextOwner gl_context_owner_;
mojo::GaneshContext ganesh_context_;
ResourceManager resource_manager_;
scoped_refptr<TextureLayer> root_layer_;
base::WeakPtrFactory<LayerHost> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(LayerHost);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_LAYER_HOST_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/layer_host_client.h"
namespace sky {
LayerHostClient::~LayerHostClient() {
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_LAYER_HOST_CLIENT_H_
#define SKY_VIEWER_COMPOSITOR_LAYER_HOST_CLIENT_H_
#include "base/time/time.h"
#include "mojo/services/surfaces/interfaces/surface_id.mojom.h"
namespace mojo {
class Shell;
}
namespace sky {
class LayerHostClient {
public:
virtual mojo::Shell* GetShell() = 0;
virtual void BeginFrame(base::TimeTicks frame_time) = 0;
virtual void OnSurfaceIdAvailable(mojo::SurfaceIdPtr surface_id) = 0;
protected:
virtual ~LayerHostClient();
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_LAYER_HOST_CLIENT_H_
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/rasterizer.h"
namespace sky {
Rasterizer::Rasterizer() {
}
Rasterizer::~Rasterizer() {
}
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_RASTERIZER_H_
#define SKY_VIEWER_COMPOSITOR_RASTERIZER_H_
#include "base/memory/scoped_ptr.h"
#include "mojo/gpu/gl_texture.h"
class SkPicture;
namespace sky {
class Rasterizer {
public:
Rasterizer();
virtual ~Rasterizer();
virtual scoped_ptr<mojo::GLTexture> Rasterize(SkPicture* picture) = 0;
private:
DISALLOW_COPY_AND_ASSIGN(Rasterizer);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_RASTERIZER_H_
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/rasterizer_bitmap.h"
#include "services/sky/compositor/layer_client.h"
#include "services/sky/compositor/layer_host.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/geometry/rect.h"
namespace sky {
RasterizerBitmap::RasterizerBitmap(LayerHost* host) : host_(host) {
DCHECK(host_);
}
RasterizerBitmap::~RasterizerBitmap() {
}
void RasterizerBitmap::GetPixelsForTesting(std::vector<unsigned char>* pixels) {
gfx::PNGCodec::EncodeBGRASkBitmap(bitmap_, true, pixels);
}
scoped_ptr<mojo::GLTexture> RasterizerBitmap::Rasterize(SkPicture* picture) {
auto size = picture->cullRect();
bitmap_.allocN32Pixels(size.width(), size.height());
SkBitmapDevice device(bitmap_);
SkCanvas canvas(&device);
canvas.clear(SK_ColorBLACK);
canvas.drawPicture(picture);
canvas.flush();
return host_->resource_manager()->CreateTexture(
gfx::Size(size.width(), size.height()));
}
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_DISPLAY_RASTERIZER_BITMAP_H_
#define SKY_VIEWER_COMPOSITOR_DISPLAY_RASTERIZER_BITMAP_H_
#include "services/sky/compositor/rasterizer.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace sky {
class LayerHost;
class RasterizerBitmap : public Rasterizer {
public:
explicit RasterizerBitmap(LayerHost* host);
~RasterizerBitmap() override;
scoped_ptr<mojo::GLTexture> Rasterize(SkPicture* picture) override;
void GetPixelsForTesting(std::vector<unsigned char>* pixels);
private:
LayerHost* host_;
SkBitmap bitmap_;
DISALLOW_COPY_AND_ASSIGN(RasterizerBitmap);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_DISPLAY_RASTERIZER_BITMAP_H_
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/rasterizer_ganesh.h"
#include "base/trace_event/trace_event.h"
#include "mojo/skia/ganesh_surface.h"
#include "services/sky/compositor/layer_host.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPicture.h"
namespace sky {
RasterizerGanesh::RasterizerGanesh(LayerHost* host) : host_(host) {
DCHECK(host_);
}
RasterizerGanesh::~RasterizerGanesh() {
}
scoped_ptr<mojo::GLTexture> RasterizerGanesh::Rasterize(SkPicture* picture) {
TRACE_EVENT0("flutter", "RasterizerGanesh::Rasterize");
SkRect cull_rect = picture->cullRect();
gfx::Size size(cull_rect.width(), cull_rect.height());
if (size.IsEmpty())
return nullptr;
mojo::GaneshSurface surface(host_->ganesh_context(),
host_->resource_manager()->CreateTexture(size));
SkCanvas* canvas = surface.canvas();
canvas->clear(SK_ColorBLACK);
canvas->drawPicture(picture);
canvas->flush();
return surface.TakeTexture();
}
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_DISPLAY_RASTERIZER_GANESH_H_
#define SKY_VIEWER_COMPOSITOR_DISPLAY_RASTERIZER_GANESH_H_
#include "services/sky/compositor/rasterizer.h"
namespace sky {
class LayerHost;
class RasterizerGanesh : public Rasterizer {
public:
explicit RasterizerGanesh(LayerHost* host);
~RasterizerGanesh() override;
scoped_ptr<mojo::GLTexture> Rasterize(SkPicture* picture) override;
private:
LayerHost* host_;
DISALLOW_COPY_AND_ASSIGN(RasterizerGanesh);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_DISPLAY_RASTERIZER_GANESH_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/resource_manager.h"
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2.h>
#include <GLES2/gl2extmojo.h>
#include "base/logging.h"
#include "base/stl_util.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/gpu/gl_context.h"
#include "mojo/gpu/gl_texture.h"
#include "services/sky/compositor/texture_layer.h"
namespace sky {
ResourceManager::ResourceManager(base::WeakPtr<mojo::GLContext> gl_context)
: gl_context_(gl_context), next_resource_id_(0) {
}
ResourceManager::~ResourceManager() {
STLDeleteContainerPairSecondPointers(resource_to_texture_map_.begin(),
resource_to_texture_map_.end());
}
scoped_ptr<mojo::GLTexture> ResourceManager::CreateTexture(
const gfx::Size& size) {
scoped_ptr<mojo::GLTexture> texture = texture_cache_.GetTexture(size);
if (texture)
return texture.Pass();
gl_context_->MakeCurrent();
return make_scoped_ptr(new mojo::GLTexture(
gl_context_, mojo::TypeConverter<mojo::Size, gfx::Size>::Convert(size)));
}
mojo::TransferableResourcePtr ResourceManager::CreateTransferableResource(
TextureLayer* layer) {
scoped_ptr<mojo::GLTexture> texture = layer->GetTexture();
mojo::Size size = texture->size();
gl_context_->MakeCurrent();
glBindTexture(GL_TEXTURE_2D, texture->texture_id());
GLbyte mailbox[GL_MAILBOX_SIZE_CHROMIUM];
glGenMailboxCHROMIUM(mailbox);
glProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox);
GLuint sync_point = glInsertSyncPointCHROMIUM();
glFlush();
mojo::TransferableResourcePtr resource = mojo::TransferableResource::New();
resource->id = next_resource_id_++;
resource_to_texture_map_[resource->id] = texture.release();
resource->format = mojo::ResourceFormat::RGBA_8888;
resource->filter = GL_LINEAR;
resource->size = size.Clone();
resource->is_repeated = false;
resource->is_software = false;
mojo::MailboxHolderPtr mailbox_holder = mojo::MailboxHolder::New();
mailbox_holder->mailbox = mojo::Mailbox::New();
for (int i = 0; i < GL_MAILBOX_SIZE_CHROMIUM; ++i)
mailbox_holder->mailbox->name.push_back(mailbox[i]);
mailbox_holder->texture_target = GL_TEXTURE_2D;
mailbox_holder->sync_point = sync_point;
resource->mailbox_holder = mailbox_holder.Pass();
return resource.Pass();
}
void ResourceManager::ReturnResources(
mojo::Array<mojo::ReturnedResourcePtr> resources) {
DCHECK(resources.size());
gl_context_->MakeCurrent();
for (size_t i = 0u; i < resources.size(); ++i) {
mojo::ReturnedResourcePtr resource = resources[i].Pass();
DCHECK_EQ(1, resource->count);
auto iter = resource_to_texture_map_.find(resource->id);
if (iter == resource_to_texture_map_.end())
continue;
scoped_ptr<mojo::GLTexture> texture(iter->second);
DCHECK_NE(0u, texture->texture_id());
resource_to_texture_map_.erase(iter);
glWaitSyncPointCHROMIUM(resource->sync_point);
texture_cache_.PutTexture(texture.Pass());
}
}
} // namespace examples
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_RESOURCE_MANAGER_H_
#define SKY_VIEWER_COMPOSITOR_RESOURCE_MANAGER_H_
#include "base/containers/hash_tables.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/memory/weak_ptr.h"
#include "mojo/services/surfaces/interfaces/surfaces.mojom.h"
#include "services/sky/compositor/texture_cache.h"
namespace gfx {
class Size;
}
namespace mojo {
class GLContext;
class GLTexture;
}
namespace sky {
class LayerHost;
class TextureLayer;
class ResourceManager {
public:
explicit ResourceManager(base::WeakPtr<mojo::GLContext> gl_context);
~ResourceManager();
scoped_ptr<mojo::GLTexture> CreateTexture(const gfx::Size& size);
mojo::TransferableResourcePtr CreateTransferableResource(TextureLayer* layer);
void ReturnResources(mojo::Array<mojo::ReturnedResourcePtr> resources);
private:
base::WeakPtr<mojo::GLContext> gl_context_;
uint32_t next_resource_id_;
base::hash_map<uint32_t, mojo::GLTexture*> resource_to_texture_map_;
TextureCache texture_cache_;
DISALLOW_COPY_AND_ASSIGN(ResourceManager);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_RESOURCE_MANAGER_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/surface_holder.h"
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/interfaces/application/shell.mojom.h"
namespace sky {
SurfaceHolder::Client::~Client() {
}
SurfaceHolder::SurfaceHolder(Client* client, mojo::Shell* shell)
: client_(client),
id_namespace_(0u),
local_id_(0u),
returner_binding_(this),
weak_factory_(this) {
mojo::ServiceProviderPtr service_provider;
shell->ConnectToApplication("mojo:surfaces_service",
mojo::GetProxy(&service_provider), nullptr);
mojo::ConnectToService(service_provider.get(), &surface_);
surface_->GetIdNamespace(
base::Bind(&SurfaceHolder::SetIdNamespace, base::Unretained(this)));
mojo::ResourceReturnerPtr returner_ptr;
returner_binding_.Bind(GetProxy(&returner_ptr));
surface_->SetResourceReturner(returner_ptr.Pass());
}
SurfaceHolder::~SurfaceHolder() {
if (local_id_ != 0u)
surface_->DestroySurface(local_id_);
}
void SurfaceHolder::SubmitFrame(mojo::FramePtr frame,
const base::Closure& callback) {
surface_->SubmitFrame(local_id_, frame.Pass(), callback);
}
void SurfaceHolder::SetSize(const gfx::Size& size) {
if (local_id_ != 0u && size_ == size)
return;
if (local_id_ != 0u)
surface_->DestroySurface(local_id_);
local_id_++;
surface_->CreateSurface(local_id_);
size_ = size;
if (id_namespace_ != 0u)
SetQualifiedId();
}
void SurfaceHolder::SetQualifiedId() {
auto qualified_id = mojo::SurfaceId::New();
qualified_id->id_namespace = id_namespace_;
qualified_id->local = local_id_;
client_->OnSurfaceIdAvailable(qualified_id.Pass());
}
void SurfaceHolder::SetIdNamespace(uint32_t id_namespace) {
id_namespace_ = id_namespace;
if (local_id_ != 0u)
SetQualifiedId();
}
void SurfaceHolder::ReturnResources(
mojo::Array<mojo::ReturnedResourcePtr> resources) {
client_->ReturnResources(resources.Pass());
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_SURFACE_HOLDER_H_
#define SKY_VIEWER_COMPOSITOR_SURFACE_HOLDER_H_
#include "base/callback_forward.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/services/surfaces/interfaces/surface_id.mojom.h"
#include "mojo/services/surfaces/interfaces/surfaces.mojom.h"
#include "ui/gfx/geometry/rect.h"
namespace mojo {
class Shell;
}
namespace sky {
class SurfaceHolder : public mojo::ResourceReturner {
public:
class Client {
public:
virtual void OnSurfaceIdAvailable(mojo::SurfaceIdPtr surface_id) = 0;
virtual void ReturnResources(
mojo::Array<mojo::ReturnedResourcePtr> resources) = 0;
protected:
virtual ~Client();
};
explicit SurfaceHolder(Client* client, mojo::Shell* shell);
~SurfaceHolder() override;
void SetSize(const gfx::Size& size);
void SubmitFrame(mojo::FramePtr frame, const base::Closure& callback);
private:
// mojo::ResourceReturner
void ReturnResources(
mojo::Array<mojo::ReturnedResourcePtr> resources) override;
void SetIdNamespace(uint32_t id_namespace);
void SetQualifiedId();
Client* client_;
gfx::Size size_;
uint32_t id_namespace_;
uint32_t local_id_;
mojo::SurfacePtr surface_;
mojo::Binding<mojo::ResourceReturner> returner_binding_;
base::WeakPtrFactory<SurfaceHolder> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(SurfaceHolder);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_SURFACE_HOLDER_H_
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/texture_cache.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/gpu/gl_texture.h"
namespace sky {
TextureCache::TextureCache() {
}
TextureCache::~TextureCache() {
}
scoped_ptr<mojo::GLTexture> TextureCache::GetTexture(const gfx::Size& size) {
if (size != size_) {
available_textures_.clear();
size_ = size;
}
if (available_textures_.empty())
return nullptr;
scoped_ptr<mojo::GLTexture> texture(available_textures_.back());
available_textures_.back() = nullptr;
available_textures_.pop_back();
return texture.Pass();
}
void TextureCache::PutTexture(scoped_ptr<mojo::GLTexture> texture) {
if (texture->size() != size_)
return;
available_textures_.push_back(texture.release());
}
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_TEXTURE_CACHE_H_
#define SKY_VIEWER_COMPOSITOR_TEXTURE_CACHE_H_
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "ui/gfx/geometry/size.h"
namespace mojo {
class GLTexture;
}
namespace sky {
class TextureCache {
public:
TextureCache();
~TextureCache();
scoped_ptr<mojo::GLTexture> GetTexture(const gfx::Size& size);
void PutTexture(scoped_ptr<mojo::GLTexture> texture);
private:
gfx::Size size_;
ScopedVector<mojo::GLTexture> available_textures_;
DISALLOW_COPY_AND_ASSIGN(TextureCache);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_TEXTURE_CACHE_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/compositor/texture_layer.h"
#include "base/trace_event/trace_event.h"
#include "services/sky/compositor/layer_host.h"
#include "services/sky/compositor/rasterizer.h"
#include "sky/engine/wtf/RefPtr.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"
namespace sky {
TextureLayer::TextureLayer(LayerClient* client) : client_(client) {
}
TextureLayer::~TextureLayer() {
}
void TextureLayer::SetSize(const gfx::Size& size) {
size_ = size;
}
void TextureLayer::Display() {
TRACE_EVENT0("flutter", "Layer::Display");
DCHECK(rasterizer_);
RefPtr<SkPicture> picture = RecordPicture();
texture_ = rasterizer_->Rasterize(picture.get());
}
PassRefPtr<SkPicture> TextureLayer::RecordPicture() {
TRACE_EVENT0("flutter", "Layer::RecordPicture");
SkRTreeFactory factory;
SkPictureRecorder recorder;
SkCanvas* canvas = recorder.beginRecording(
size_.width(), size_.height(), &factory,
SkPictureRecorder::kComputeSaveLayerInfo_RecordFlag);
client_->PaintContents(canvas, gfx::Rect(size_));
return adoptRef(recorder.endRecordingAsPicture());
}
bool TextureLayer::HaveTexture() const {
return texture_;
}
scoped_ptr<mojo::GLTexture> TextureLayer::GetTexture() {
return texture_.Pass();
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_COMPOSITOR_TEXTURE_LAYER_H_
#define SKY_VIEWER_COMPOSITOR_TEXTURE_LAYER_H_
#include "base/memory/ref_counted.h"
#include "mojo/gpu/gl_texture.h"
#include "services/sky/compositor/layer_client.h"
#include "services/sky/compositor/rasterizer.h"
#include "sky/engine/wtf/PassRefPtr.h"
#include "third_party/skia/include/core/SkPicture.h"
#include "ui/gfx/geometry/rect.h"
namespace sky {
class LayerHost;
class TextureLayer : public base::RefCounted<TextureLayer> {
public:
explicit TextureLayer(LayerClient* client);
void SetSize(const gfx::Size& size);
void Display();
bool HaveTexture() const;
scoped_ptr<mojo::GLTexture> GetTexture();
const gfx::Size& size() const { return size_; }
void set_rasterizer(scoped_ptr<Rasterizer> rasterizer) {
rasterizer_ = rasterizer.Pass();
}
private:
friend class base::RefCounted<TextureLayer>;
~TextureLayer();
PassRefPtr<SkPicture> RecordPicture();
LayerClient* client_;
gfx::Size size_;
scoped_ptr<mojo::GLTexture> texture_;
scoped_ptr<Rasterizer> rasterizer_;
DISALLOW_COPY_AND_ASSIGN(TextureLayer);
};
} // namespace sky
#endif // SKY_VIEWER_COMPOSITOR_TEXTURE_LAYER_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/content_handler_impl.h"
#include "base/bind.h"
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/cpp/utility/run_loop.h"
#include "mojo/services/network/interfaces/network_service.mojom.h"
#include "services/sky/document_view.h"
namespace sky {
class SkyApplication : public mojo::Application {
public:
SkyApplication(mojo::InterfaceRequest<mojo::Application> application,
mojo::URLResponsePtr response)
: binding_(this, application.Pass()),
initial_response_(response.Pass()) {}
void Initialize(mojo::ShellPtr shell,
mojo::Array<mojo::String> args,
const mojo::String& url) override {
shell_ = shell.Pass();
mojo::ServiceProviderPtr service_provider;
shell_->ConnectToApplication("mojo:authenticated_network_service",
mojo::GetProxy(&service_provider), nullptr);
mojo::ConnectToService(service_provider.get(), &network_service_);
}
void AcceptConnection(const mojo::String& requestor_url,
mojo::InterfaceRequest<mojo::ServiceProvider> services,
mojo::ServiceProviderPtr exposed_services,
const mojo::String& url) override {
if (initial_response_) {
OnResponseReceived(mojo::URLLoaderPtr(), services.Pass(),
exposed_services.Pass(), initial_response_.Pass());
} else {
mojo::URLLoaderPtr loader;
network_service_->CreateURLLoader(mojo::GetProxy(&loader));
mojo::URLRequestPtr request(mojo::URLRequest::New());
request->url = url;
request->auto_follow_redirects = true;
// |loader| will be pass to the OnResponseReceived method through a
// callback. Because order of evaluation is undefined, a reference to the
// raw pointer is needed.
mojo::URLLoader* raw_loader = loader.get();
raw_loader->Start(
request.Pass(),
base::Bind(&SkyApplication::OnResponseReceived,
base::Unretained(this), base::Passed(&loader),
base::Passed(&services), base::Passed(&exposed_services)));
}
}
void RequestQuit() override {
mojo::RunLoop::current()->Quit();
}
private:
void OnResponseReceived(
mojo::URLLoaderPtr loader,
mojo::InterfaceRequest<mojo::ServiceProvider> services,
mojo::ServiceProviderPtr exposed_services,
mojo::URLResponsePtr response) {
new DocumentView(services.Pass(), exposed_services.Pass(), response.Pass(),
shell_.get());
}
mojo::StrongBinding<mojo::Application> binding_;
mojo::ShellPtr shell_;
mojo::NetworkServicePtr network_service_;
mojo::URLResponsePtr initial_response_;
};
ContentHandlerImpl::ContentHandlerImpl(
mojo::InterfaceRequest<mojo::ContentHandler> request)
: binding_(this, request.Pass()) {
}
ContentHandlerImpl::~ContentHandlerImpl() {
}
void ContentHandlerImpl::StartApplication(
mojo::InterfaceRequest<mojo::Application> application,
mojo::URLResponsePtr response) {
new SkyApplication(application.Pass(), response.Pass());
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_SKY_CONTENT_HANDLER_IMPL_H_
#define SERVICES_SKY_CONTENT_HANDLER_IMPL_H_
#include "base/message_loop/message_loop.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/interfaces/application/shell.mojom.h"
#include "mojo/services/content_handler/interfaces/content_handler.mojom.h"
namespace sky {
class DocumentView;
class ContentHandlerImpl : public mojo::ContentHandler {
public:
explicit ContentHandlerImpl(
mojo::InterfaceRequest<mojo::ContentHandler> request);
~ContentHandlerImpl() override;
private:
// Overridden from ContentHandler:
void StartApplication(mojo::InterfaceRequest<mojo::Application> application,
mojo::URLResponsePtr response) override;
mojo::StrongBinding<mojo::ContentHandler> binding_;
DISALLOW_COPY_AND_ASSIGN(ContentHandlerImpl);
};
} // namespace sky
#endif // SERVICES_SKY_CONTENT_HANDLER_IMPL_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/converters/basic_types.h"
#include "mojo/public/cpp/bindings/string.h"
#include "sky/engine/public/platform/WebString.h"
using blink::WebString;
namespace mojo {
// static
String TypeConverter<String, WebString>::Convert(const WebString& str) {
return String(str.utf8());
}
// static
WebString TypeConverter<WebString, String>::Convert(const String& str) {
return WebString::fromUTF8(str.get());
}
} // namespace mojo
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_CONVERTERS_BASIC_TYPES_H_
#define SKY_VIEWER_CONVERTERS_BASIC_TYPES_H_
#include "mojo/public/cpp/bindings/array.h"
#include "mojo/public/cpp/bindings/type_converter.h"
#include "sky/engine/public/platform/WebVector.h"
namespace blink {
class WebString;
}
namespace mojo {
class String;
template<>
struct TypeConverter<String, blink::WebString> {
static String Convert(const blink::WebString& str);
};
template<>
struct TypeConverter<blink::WebString, String> {
static blink::WebString Convert(const String& str);
};
template<typename T, typename U>
struct TypeConverter<Array<T>, blink::WebVector<U> > {
static Array<T> Convert(const blink::WebVector<U>& vector) {
Array<T> array(vector.size());
for (size_t i = 0; i < vector.size(); ++i)
array[i] = TypeConverter<T, U>::Convert(vector[i]);
return array.Pass();
}
};
} // namespace mojo
#endif // SKY_VIEWER_CONVERTERS_BASIC_TYPES_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/converters/input_event_types.h"
#include "base/logging.h"
#include "base/time/time.h"
#include "mojo/services/input_events/interfaces/input_event_constants.mojom.h"
#include "sky/engine/public/platform/WebInputEvent.h"
namespace sky {
namespace {
int EventFlagsToWebInputEventModifiers(mojo::EventFlags event_flags) {
int flags = static_cast<int>(event_flags);
return
(flags & static_cast<int>(mojo::EventFlags::SHIFT_DOWN) ?
blink::WebInputEvent::ShiftKey : 0) |
(flags & static_cast<int>(mojo::EventFlags::CONTROL_DOWN) ?
blink::WebInputEvent::ControlKey : 0) |
(flags & static_cast<int>(mojo::EventFlags::CAPS_LOCK_DOWN) ?
blink::WebInputEvent::CapsLockOn : 0) |
(flags & static_cast<int>(mojo::EventFlags::ALT_DOWN) ?
blink::WebInputEvent::AltKey : 0) |
(flags & static_cast<int>(mojo::EventFlags::LEFT_MOUSE_BUTTON) ?
blink::WebInputEvent::LeftButtonDown : 0) |
(flags & static_cast<int>(mojo::EventFlags::MIDDLE_MOUSE_BUTTON) ?
blink::WebInputEvent::MiddleButtonDown : 0) |
(flags & static_cast<int>(mojo::EventFlags::RIGHT_MOUSE_BUTTON) ?
blink::WebInputEvent::RightButtonDown : 0);
}
scoped_ptr<blink::WebInputEvent> BuildWebKeyboardEvent(
const mojo::EventPtr& event,
float device_pixel_ratio) {
scoped_ptr<blink::WebKeyboardEvent> web_event(new blink::WebKeyboardEvent);
web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
web_event->timeStampMS =
base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();
switch (event->action) {
case mojo::EventType::KEY_PRESSED:
web_event->type = event->key_data->is_char ? blink::WebInputEvent::Char :
blink::WebInputEvent::KeyDown;
break;
case mojo::EventType::KEY_RELEASED:
web_event->type = blink::WebInputEvent::KeyUp;
break;
default:
NOTREACHED();
}
web_event->key = static_cast<int>(event->key_data->windows_key_code);
web_event->charCode = event->key_data->text;
web_event->unmodifiedCharCode = event->key_data->unmodified_text;
return web_event.Pass();
}
scoped_ptr<blink::WebInputEvent> BuildWebWheelEvent(
const mojo::EventPtr& event, float device_pixel_ratio) {
scoped_ptr<blink::WebWheelEvent> web_event(new blink::WebWheelEvent);
web_event->modifiers = EventFlagsToWebInputEventModifiers(event->flags);
web_event->timeStampMS =
base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();
web_event->type = blink::WebInputEvent::WheelEvent;
web_event->x = event->pointer_data->x / device_pixel_ratio;
web_event->y = event->pointer_data->y / device_pixel_ratio;
// The times 100 is arbitrary. Need a better way to deal.
web_event->offsetX =
event->pointer_data->horizontal_wheel * 100 / device_pixel_ratio;
web_event->offsetY =
event->pointer_data->vertical_wheel * 100 / device_pixel_ratio;
return web_event.Pass();
}
} // namespace
bool IsPointerEvent(const mojo::EventPtr& event) {
return ((event->action == mojo::EventType::POINTER_DOWN ||
event->action == mojo::EventType::POINTER_UP ||
event->action == mojo::EventType::POINTER_CANCEL ||
event->action == mojo::EventType::POINTER_MOVE) &&
event->pointer_data->horizontal_wheel == 0 &&
event->pointer_data->vertical_wheel == 0);
}
scoped_ptr<blink::WebInputEvent> ConvertEvent(const mojo::EventPtr& event,
float device_pixel_ratio) {
if (event->action == mojo::EventType::POINTER_DOWN ||
event->action == mojo::EventType::POINTER_UP ||
event->action == mojo::EventType::POINTER_CANCEL ||
event->action == mojo::EventType::POINTER_MOVE) {
if (event->pointer_data->horizontal_wheel != 0 ||
event->pointer_data->vertical_wheel != 0) {
return BuildWebWheelEvent(event, device_pixel_ratio);
}
} else if ((event->action == mojo::EventType::KEY_PRESSED ||
event->action == mojo::EventType::KEY_RELEASED) &&
event->key_data) {
return BuildWebKeyboardEvent(event, device_pixel_ratio);
}
return nullptr;
}
pointer::PointerPacketPtr ConvertPointerEvent(const mojo::EventPtr& event,
float device_pixel_ratio) {
pointer::PointerPacketPtr packet = pointer::PointerPacket::New();
pointer::PointerPtr pointer = pointer::Pointer::New();
pointer->time_stamp =
base::TimeDelta::FromInternalValue(event->time_stamp).InMillisecondsF();
switch (event->action) {
case mojo::EventType::POINTER_DOWN:
pointer->type = pointer::PointerType::DOWN;
break;
case mojo::EventType::POINTER_MOVE:
pointer->type = pointer::PointerType::MOVE;
break;
case mojo::EventType::POINTER_UP:
pointer->type = pointer::PointerType::UP;
break;
case mojo::EventType::POINTER_CANCEL:
// FIXME: What mouse event should we listen to in order to learn when the
// mouse moves out of the mojo::View?
pointer->type = pointer::PointerType::CANCEL;
break;
default:
NOTIMPLEMENTED() << "Received unexpected event: " << event->action;
break;
}
if (event->pointer_data->kind == mojo::PointerKind::TOUCH) {
pointer->kind = pointer::PointerKind::TOUCH;
pointer->pointer = event->pointer_data->pointer_id;
} else {
pointer->kind = pointer::PointerKind::MOUSE;
// Set the buttons according to http://www.w3.org/TR/pointerevents/
int buttons = 0;
int flags = static_cast<int>(event->flags);
if (flags & static_cast<int>(mojo::EventFlags::LEFT_MOUSE_BUTTON))
buttons |= (1 << 0);
if (flags & static_cast<int>(mojo::EventFlags::RIGHT_MOUSE_BUTTON))
buttons |= (1 << 1);
if (flags & static_cast<int>(mojo::EventFlags::MIDDLE_MOUSE_BUTTON))
buttons |= (1 << 2);
pointer->buttons = buttons;
}
pointer->x = event->pointer_data->x / device_pixel_ratio;
pointer->y = event->pointer_data->y / device_pixel_ratio;
pointer->pressure = event->pointer_data->pressure;
pointer->radius_major = event->pointer_data->radius_major;
pointer->radius_minor = event->pointer_data->radius_minor;
pointer->orientation = event->pointer_data->orientation;
packet->pointers.push_back(pointer.Pass());
return packet;
}
} // namespace mojo
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_VIEWER_CONVERTERS_INPUT_EVENT_TYPES_H_
#define SKY_VIEWER_CONVERTERS_INPUT_EVENT_TYPES_H_
#include "base/memory/scoped_ptr.h"
#include "mojo/services/input_events/interfaces/input_events.mojom.h"
#include "sky/services/pointer/pointer.mojom.h"
namespace blink {
class WebInputEvent;
}
namespace sky {
bool IsPointerEvent(const mojo::EventPtr& event);
scoped_ptr<blink::WebInputEvent> ConvertEvent(const mojo::EventPtr& event,
float device_pixel_ratio);
pointer::PointerPacketPtr ConvertPointerEvent(const mojo::EventPtr& event,
float device_pixel_ratio);
}
#endif // SKY_VIEWER_CONVERTERS_INPUT_EVENT_TYPES_H_
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/dart_library_provider_impl.h"
namespace sky {
DartLibraryProviderImpl::PrefetchedLibrary::PrefetchedLibrary() {
}
DartLibraryProviderImpl::PrefetchedLibrary::~PrefetchedLibrary() {
}
DartLibraryProviderImpl::DartLibraryProviderImpl(
mojo::NetworkService* network_service,
scoped_ptr<PrefetchedLibrary> prefetched)
: shell::DartLibraryProviderNetwork(network_service),
prefetched_library_(prefetched.Pass()) {
}
DartLibraryProviderImpl::~DartLibraryProviderImpl() {
}
void DartLibraryProviderImpl::GetLibraryAsStream(
const std::string& name,
blink::DataPipeConsumerCallback callback) {
if (prefetched_library_ && prefetched_library_->name == name) {
mojo::ScopedDataPipeConsumerHandle pipe = prefetched_library_->pipe.Pass();
prefetched_library_ = nullptr;
callback.Run(pipe.Pass());
return;
}
shell::DartLibraryProviderNetwork::GetLibraryAsStream(name, callback);
}
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_SKY_DART_LIBRARY_PROVIDER_IMPL_H_
#define SERVICES_SKY_DART_LIBRARY_PROVIDER_IMPL_H_
#include "base/memory/scoped_ptr.h"
#include "sky/shell/dart/dart_library_provider_network.h"
namespace sky {
class DartLibraryProviderImpl : public shell::DartLibraryProviderNetwork {
public:
struct PrefetchedLibrary {
PrefetchedLibrary();
~PrefetchedLibrary();
std::string name;
mojo::ScopedDataPipeConsumerHandle pipe;
};
explicit DartLibraryProviderImpl(mojo::NetworkService* network_service,
scoped_ptr<PrefetchedLibrary> prefetched);
~DartLibraryProviderImpl() override;
private:
void GetLibraryAsStream(const std::string& name,
blink::DataPipeConsumerCallback callback) override;
scoped_ptr<PrefetchedLibrary> prefetched_library_;
DISALLOW_COPY_AND_ASSIGN(DartLibraryProviderImpl);
};
} // namespace sky
#endif // SERVICES_SKY_DART_LIBRARY_PROVIDER_IMPL_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/document_view.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/message_loop/message_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_util.h"
#include "base/thread_task_runner_handle.h"
#include "mojo/converters/geometry/geometry_type_converters.h"
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/interfaces/application/shell.mojom.h"
#include "mojo/services/surfaces/cpp/surfaces_utils.h"
#include "mojo/services/surfaces/interfaces/quads.mojom.h"
#include "services/asset_bundle/asset_unpacker_job.h"
#include "services/sky/compositor/layer_host.h"
#include "services/sky/compositor/rasterizer_bitmap.h"
#include "services/sky/compositor/rasterizer_ganesh.h"
#include "services/sky/compositor/texture_layer.h"
#include "services/sky/converters/input_event_types.h"
#include "services/sky/dart_library_provider_impl.h"
#include "services/sky/internals.h"
#include "services/sky/runtime_flags.h"
#include "skia/ext/refptr.h"
#include "sky/compositor/paint_context.h"
#include "sky/engine/public/platform/Platform.h"
#include "sky/engine/public/platform/WebInputEvent.h"
#include "sky/engine/public/web/Sky.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColor.h"
#include "third_party/skia/include/core/SkDevice.h"
using mojo::asset_bundle::AssetUnpackerJob;
namespace sky {
namespace {
const char kSnapshotKey[] = "snapshot_blob.bin";
} // namespace
DocumentView::DocumentView(
mojo::InterfaceRequest<mojo::ServiceProvider> exported_services,
mojo::ServiceProviderPtr imported_services,
mojo::URLResponsePtr response,
mojo::Shell* shell)
: response_(response.Pass()),
exported_services_(exported_services.Pass()),
imported_services_(imported_services.Pass()),
shell_(shell),
bitmap_rasterizer_(nullptr),
event_dispatcher_binding_(this),
weak_factory_(this) {
InitServiceRegistry();
InitViewport();
}
DocumentView::~DocumentView() {
}
base::WeakPtr<DocumentView> DocumentView::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void DocumentView::InitViewport() {
mojo::ServiceProviderPtr viewport_service_provider;
shell_->ConnectToApplication("mojo:native_viewport_service",
mojo::GetProxy(&viewport_service_provider),
nullptr);
mojo::ConnectToService(viewport_service_provider.get(), &viewport_service_);
viewport_service_.set_connection_error_handler(
base::Bind(&DocumentView::OnViewportConnectionError,
base::Unretained(this)));
mojo::NativeViewportEventDispatcherPtr dispatcher;
event_dispatcher_binding_.Bind(GetProxy(&dispatcher));
viewport_service_->SetEventDispatcher(dispatcher.Pass());
// Match the Nexus 5 aspect ratio initially.
auto size = mojo::Size::New();
size->width = 320;
size->height = 640;
auto requested_configuration = mojo::SurfaceConfiguration::New();
viewport_service_->Create(size.Clone(),
requested_configuration.Pass(),
base::Bind(&DocumentView::OnViewportCreated,
base::Unretained(this)));
}
void DocumentView::OnViewportConnectionError() {
delete this;
}
void DocumentView::OnViewportCreated(mojo::ViewportMetricsPtr metrics) {
viewport_service_->Show();
mojo::ContextProviderPtr onscreen_context_provider;
viewport_service_->GetContextProvider(GetProxy(&onscreen_context_provider));
mojo::ServiceProviderPtr surfaces_service_provider;
shell_->ConnectToApplication("mojo:surfaces_service",
mojo::GetProxy(&surfaces_service_provider),
nullptr);
mojo::DisplayFactoryPtr display_factory;
mojo::ConnectToService(surfaces_service_provider.get(), &display_factory);
display_factory->Create(onscreen_context_provider.Pass(),
nullptr, GetProxy(&display_));
Load(response_.Pass());
UpdateViewportMetrics(metrics.Pass());
RequestUpdatedViewportMetrics();
}
void DocumentView::OnViewportMetricsChanged(mojo::ViewportMetricsPtr metrics) {
UpdateViewportMetrics(metrics.Pass());
RequestUpdatedViewportMetrics();
}
void DocumentView::RequestUpdatedViewportMetrics() {
viewport_service_->RequestMetrics(
base::Bind(&DocumentView::OnViewportMetricsChanged,
base::Unretained(this)));
}
void DocumentView::LoadFromSnapshotStream(
String name, mojo::ScopedDataPipeConsumerHandle snapshot) {
if (sky_view_) {
sky_view_->RunFromSnapshot(name, snapshot.Pass());
}
}
void DocumentView::Load(mojo::URLResponsePtr response) {
sky_view_ = blink::SkyView::Create(this);
layer_host_.reset(new LayerHost(this));
root_layer_ = make_scoped_refptr(new TextureLayer(this));
root_layer_->set_rasterizer(CreateRasterizer());
layer_host_->SetRootLayer(root_layer_);
String name = String::fromUTF8(response->url);
sky_view_->CreateView(name);
AssetUnpackerJob* unpacker = new AssetUnpackerJob(
mojo::GetProxy(&root_bundle_),
base::MessageLoop::current()->task_runner());
unpacker->Unpack(response->body.Pass());
root_bundle_->GetAsStream(kSnapshotKey,
base::Bind(&DocumentView::LoadFromSnapshotStream,
weak_factory_.GetWeakPtr(), name));
}
scoped_ptr<Rasterizer> DocumentView::CreateRasterizer() {
if (!RuntimeFlags::Get().testing())
return make_scoped_ptr(new RasterizerGanesh(layer_host_.get()));
// TODO(abarth): If we have more than one layer, we'll need to re-think how
// we capture pixels for testing;
DCHECK(!bitmap_rasterizer_);
bitmap_rasterizer_ = new RasterizerBitmap(layer_host_.get());
return make_scoped_ptr(bitmap_rasterizer_);
}
void DocumentView::GetPixelsForTesting(std::vector<unsigned char>* pixels) {
DCHECK(RuntimeFlags::Get().testing()) << "Requires testing runtime flag";
DCHECK(root_layer_) << "The root layer owns the rasterizer";
return bitmap_rasterizer_->GetPixelsForTesting(pixels);
}
mojo::ScopedMessagePipeHandle DocumentView::TakeRootBundleHandle() {
return root_bundle_.PassInterface().PassHandle();
}
mojo::ScopedMessagePipeHandle DocumentView::TakeServicesProvidedToEmbedder() {
// TODO(jeffbrown): Stubbed out until we migrate from native viewport
// to a new view system that supports embedding again.
return mojo::ScopedMessagePipeHandle();
}
mojo::ScopedMessagePipeHandle DocumentView::TakeServicesProvidedByEmbedder() {
// TODO(jeffbrown): Stubbed out until we migrate from native viewport
// to a new view system that supports embedding again.
return mojo::ScopedMessagePipeHandle();
}
mojo::ScopedMessagePipeHandle DocumentView::TakeServiceRegistry() {
return service_registry_.PassInterface().PassHandle();
}
mojo::Shell* DocumentView::GetShell() {
return shell_;
}
void DocumentView::BeginFrame(base::TimeTicks frame_time) {
if (sky_view_) {
std::unique_ptr<compositor::LayerTree> layer_tree = sky_view_->BeginFrame(frame_time);
if (layer_tree)
current_layer_tree_ = std::move(layer_tree);
root_layer_->SetSize(sky_view_->display_metrics().physical_size);
}
}
void DocumentView::OnSurfaceIdAvailable(mojo::SurfaceIdPtr surface_id) {
mojo::FramePtr frame = mojo::Frame::New();
frame->resources.resize(0u);
mojo::Rect bounds;
bounds.width = viewport_metrics_->size->width;
bounds.height = viewport_metrics_->size->height;
mojo::PassPtr pass = mojo::CreateDefaultPass(1, bounds);
pass->shared_quad_states.push_back(mojo::CreateDefaultSQS(
*viewport_metrics_->size));
mojo::QuadPtr quad = mojo::Quad::New();
quad->material = mojo::Material::SURFACE_CONTENT;
quad->rect = bounds.Clone();
quad->opaque_rect = bounds.Clone();
quad->visible_rect = bounds.Clone();
quad->shared_quad_state_index = 0u;
quad->surface_quad_state = mojo::SurfaceQuadState::New();
quad->surface_quad_state->surface = surface_id.Pass();
pass->quads.push_back(quad.Pass());
frame->passes.push_back(pass.Pass());
display_->SubmitFrame(frame.Pass(), base::Bind(&base::DoNothing));
}
void DocumentView::PaintContents(SkCanvas* canvas, const gfx::Rect& clip) {
if (current_layer_tree_) {
compositor::PaintContext::ScopedFrame frame =
paint_context_.AcquireFrame(*canvas);
current_layer_tree_->root_layer()->Paint(frame);
}
}
void DocumentView::DidCreateIsolate(Dart_Isolate isolate) {
Internals::Create(isolate, this);
}
mojo::NavigatorHost* DocumentView::NavigatorHost() {
return navigator_host_.get();
}
void DocumentView::UpdateViewportMetrics(
mojo::ViewportMetricsPtr viewport_metrics) {
viewport_metrics_ = viewport_metrics.Pass();
if (sky_view_) {
blink::SkyDisplayMetrics metrics;
metrics.physical_size = blink::WebSize(
viewport_metrics_->size->width,
viewport_metrics_->size->height);
metrics.device_pixel_ratio = viewport_metrics_->device_pixel_ratio;
sky_view_->SetDisplayMetrics(metrics);
}
}
void DocumentView::OnEvent(mojo::EventPtr event,
const mojo::Callback<void()>& callback) {
HandleInputEvent(event.Pass());
callback.Run();
}
void DocumentView::HandleInputEvent(mojo::EventPtr event) {
if (!viewport_metrics_)
return;
float device_pixel_ratio = viewport_metrics_->device_pixel_ratio;
if (IsPointerEvent(event)) {
pointer::PointerPacketPtr packet =
ConvertPointerEvent(event, device_pixel_ratio);
sky_view_->HandlePointerPacket(packet);
} else {
scoped_ptr<blink::WebInputEvent> web_event =
ConvertEvent(event, device_pixel_ratio);
if (!web_event)
return;
if (sky_view_)
sky_view_->HandleInputEvent(*web_event);
}
}
void DocumentView::StartDebuggerInspectorBackend() {
// FIXME: Do we need this for dart?
}
void DocumentView::InitServiceRegistry() {
if (imported_services_)
mojo::ConnectToService(imported_services_.get(), &service_registry_);
}
void DocumentView::ScheduleFrame() {
DCHECK(sky_view_);
layer_host_->SetNeedsAnimate();
}
void DocumentView::Render(std::unique_ptr<compositor::LayerTree> layer_tree) {
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_SKY_DOCUMENT_VIEW_H_
#define SERVICES_SKY_DOCUMENT_VIEW_H_
#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "mojo/public/cpp/application/lazy_interface_ptr.h"
#include "mojo/public/cpp/application/service_provider_impl.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "mojo/public/interfaces/application/application.mojom.h"
#include "mojo/services/asset_bundle/interfaces/asset_bundle.mojom.h"
#include "mojo/services/content_handler/interfaces/content_handler.mojom.h"
#include "mojo/services/native_viewport/interfaces/native_viewport.mojom.h"
#include "mojo/services/navigation/interfaces/navigation.mojom.h"
#include "mojo/services/network/interfaces/url_loader.mojom.h"
#include "mojo/services/service_registry/interfaces/service_registry.mojom.h"
#include "mojo/services/surfaces/interfaces/display.mojom.h"
#include "services/sky/compositor/layer_client.h"
#include "services/sky/compositor/layer_host_client.h"
#include "sky/compositor/layer_tree.h"
#include "sky/engine/public/platform/ServiceProvider.h"
#include "sky/engine/public/sky/sky_view.h"
#include "sky/engine/public/sky/sky_view_client.h"
namespace sky {
class DartLibraryProviderImpl;
class LayerHost;
class Rasterizer;
class RasterizerBitmap;
class TextureLayer;
class DocumentView : public blink::ServiceProvider,
public blink::SkyViewClient,
public mojo::NativeViewportEventDispatcher,
public sky::LayerClient,
public sky::LayerHostClient {
public:
DocumentView(mojo::InterfaceRequest<mojo::ServiceProvider> exported_services,
mojo::ServiceProviderPtr imported_services,
mojo::URLResponsePtr response,
mojo::Shell* shell);
~DocumentView() override;
base::WeakPtr<DocumentView> GetWeakPtr();
mojo::Shell* shell() const { return shell_; }
// sky::LayerHostClient
mojo::Shell* GetShell() override;
void BeginFrame(base::TimeTicks frame_time) override;
void OnSurfaceIdAvailable(mojo::SurfaceIdPtr surface_id) override;
// sky::LayerClient
void PaintContents(SkCanvas* canvas, const gfx::Rect& clip) override;
// SkyViewClient methods:
void ScheduleFrame() override;
void Render(std::unique_ptr<compositor::LayerTree> layer_tree) override;
void StartDebuggerInspectorBackend();
void GetPixelsForTesting(std::vector<unsigned char>* pixels);
mojo::ScopedMessagePipeHandle TakeRootBundleHandle();
mojo::ScopedMessagePipeHandle TakeServicesProvidedToEmbedder();
mojo::ScopedMessagePipeHandle TakeServicesProvidedByEmbedder();
mojo::ScopedMessagePipeHandle TakeServiceRegistry();
private:
// SkyViewClient methods:
void DidCreateIsolate(Dart_Isolate isolate) override;
// Services methods:
mojo::NavigatorHost* NavigatorHost() override;
// NativeViewportEventDispatcher methods:
void OnEvent(mojo::EventPtr event,
const mojo::Callback<void()>& callback) override;
void OnViewportConnectionError();
void OnViewportCreated(mojo::ViewportMetricsPtr metrics);
void OnViewportMetricsChanged(mojo::ViewportMetricsPtr metrics);
void RequestUpdatedViewportMetrics();
void Load(mojo::URLResponsePtr response);
float GetDevicePixelRatio() const;
scoped_ptr<Rasterizer> CreateRasterizer();
void LoadFromSnapshotStream(String name,
mojo::ScopedDataPipeConsumerHandle snapshot);
void UpdateViewportMetrics(mojo::ViewportMetricsPtr viewport_metrics);
void HandleInputEvent(mojo::EventPtr event);
void InitServiceRegistry();
void InitViewport();
mojo::URLResponsePtr response_;
mojo::ServiceProviderImpl exported_services_;
mojo::ServiceProviderPtr imported_services_;
mojo::NativeViewportPtr viewport_service_;
mojo::Shell* shell_;
mojo::asset_bundle::AssetBundlePtr root_bundle_;
mojo::NavigatorHostPtr navigator_host_;
std::unique_ptr<blink::SkyView> sky_view_;
scoped_ptr<DartLibraryProviderImpl> library_provider_;
scoped_ptr<LayerHost> layer_host_;
scoped_refptr<TextureLayer> root_layer_;
std::unique_ptr<compositor::LayerTree> current_layer_tree_; // TODO(abarth): Integrate //sky/compositor and //services/sky/compositor.
compositor::PaintContext paint_context_;
RasterizerBitmap* bitmap_rasterizer_; // Used for pixel tests.
mojo::ServiceRegistryPtr service_registry_;
mojo::Binding<NativeViewportEventDispatcher> event_dispatcher_binding_;
mojo::ViewportMetricsPtr viewport_metrics_;
mojo::DisplayPtr display_;
base::WeakPtrFactory<DocumentView> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(DocumentView);
};
} // namespace sky
#endif // SERVICES_SKY_DOCUMENT_VIEW_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/internals.h"
#include <limits>
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/cpp/bindings/array.h"
#include "services/sky/document_view.h"
#include "services/sky/runtime_flags.h"
#include "sky/engine/tonic/dart_converter.h"
#include "sky/engine/tonic/dart_error.h"
#include "sky/engine/tonic/dart_library_natives.h"
using namespace blink;
namespace sky {
namespace {
int kInternalsKey = 0;
Internals* GetInternals() {
DartState* state = DartState::Current();
return static_cast<Internals*>(state->GetUserData(&kInternalsKey));
}
void TakeRootBundleHandle(Dart_NativeArguments args) {
Dart_SetIntegerReturnValue(args,
GetInternals()->TakeRootBundleHandle().value());
}
void TakeShellProxyHandle(Dart_NativeArguments args) {
Dart_SetIntegerReturnValue(args,
GetInternals()->TakeShellProxyHandle().value());
}
void TakeServicesProvidedByEmbedder(Dart_NativeArguments args) {
Dart_SetIntegerReturnValue(
args, GetInternals()->TakeServicesProvidedByEmbedder().value());
}
void TakeServicesProvidedToEmbedder(Dart_NativeArguments args) {
Dart_SetIntegerReturnValue(
args, GetInternals()->TakeServicesProvidedToEmbedder().value());
}
void TakeServiceRegistry(Dart_NativeArguments args) {
Dart_SetIntegerReturnValue(
args, GetInternals()->TakeServiceRegistry().value());
}
static DartLibraryNatives* g_natives;
void EnsureNatives() {
if (g_natives)
return;
g_natives = new DartLibraryNatives();
g_natives->Register({
{"takeRootBundleHandle", TakeRootBundleHandle, 0, true},
{"takeServiceRegistry", TakeServiceRegistry, 0, true},
{"takeServicesProvidedByEmbedder", TakeServicesProvidedByEmbedder, 0, true},
{"takeServicesProvidedToEmbedder", TakeServicesProvidedToEmbedder, 0, true},
{"takeShellProxyHandle", TakeShellProxyHandle, 0, true},
});
}
Dart_NativeFunction GetNativeFunction(Dart_Handle name,
int argument_count,
bool* auto_setup_scope) {
return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope);
}
const uint8_t* GetSymbol(Dart_NativeFunction native_function) {
return g_natives->GetSymbol(native_function);
}
} // namespace
void Internals::Create(Dart_Isolate isolate, DocumentView* document_view) {
EnsureNatives();
DartState* state = DartState::From(isolate);
state->SetUserData(&kInternalsKey, new Internals(document_view));
Dart_Handle library = Dart_LookupLibrary(ToDart("dart:ui_internals"));
CHECK(!LogIfError(library));
CHECK(!LogIfError(Dart_SetNativeResolver(
library, GetNativeFunction, GetSymbol)));
}
Internals::Internals(DocumentView* document_view)
: document_view_(document_view->GetWeakPtr()),
shell_binding_(this) {
}
Internals::~Internals() {
}
mojo::Handle Internals::TakeRootBundleHandle() {
if (!document_view_)
return mojo::Handle();
return document_view_->TakeRootBundleHandle().release();
}
mojo::Handle Internals::TakeServicesProvidedToEmbedder() {
if (!document_view_)
return mojo::Handle();
return document_view_->TakeServicesProvidedToEmbedder().release();
}
mojo::Handle Internals::TakeServicesProvidedByEmbedder() {
if (!document_view_)
return mojo::Handle();
return document_view_->TakeServicesProvidedByEmbedder().release();
}
mojo::Handle Internals::TakeServiceRegistry() {
if (!document_view_)
return mojo::Handle();
return document_view_->TakeServiceRegistry().release();
}
// Returns a MessagePipe handle that's connected to this Shell. The caller
// owns the handle and is expected to use it to create the JS Application for
// the DocumentView.
mojo::Handle Internals::TakeShellProxyHandle() {
mojo::ShellPtr shell;
if (!shell_binding_.is_bound())
shell_binding_.Bind(GetProxy(&shell));
return shell.PassInterface().PassHandle().release();
}
void Internals::ConnectToApplication(
const mojo::String& application_url,
mojo::InterfaceRequest<mojo::ServiceProvider> services,
mojo::ServiceProviderPtr exposed_services) {
if (document_view_) {
document_view_->shell()->ConnectToApplication(
application_url, services.Pass(), exposed_services.Pass());
}
}
} // namespace sky
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_SKY_INTERNALS_H_
#define SERVICES_SKY_INTERNALS_H_
#include "base/memory/weak_ptr.h"
#include "base/supports_user_data.h"
#include "dart/runtime/include/dart_api.h"
#include "mojo/public/cpp/bindings/binding.h"
#include "mojo/public/interfaces/application/shell.mojom.h"
namespace sky {
class DocumentView;
class Internals : public base::SupportsUserData::Data,
public mojo::Shell {
public:
~Internals() override;
static void Create(Dart_Isolate isolate, DocumentView* document_view);
// mojo::Shell method:
void ConnectToApplication(
const mojo::String& application_url,
mojo::InterfaceRequest<mojo::ServiceProvider> services,
mojo::ServiceProviderPtr exposed_services) override;
mojo::Handle TakeShellProxyHandle();
mojo::Handle TakeRootBundleHandle();
mojo::Handle TakeServicesProvidedToEmbedder();
mojo::Handle TakeServicesProvidedByEmbedder();
mojo::Handle TakeServiceRegistry();
private:
explicit Internals(DocumentView* document_view);
base::WeakPtr<DocumentView> document_view_;
mojo::Binding<mojo::Shell> shell_binding_;
MOJO_DISALLOW_COPY_AND_ASSIGN(Internals);
};
} // namespace sky
#endif // SERVICES_SKY_INTERNALS_H_
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/platform_impl.h"
#include "base/bind.h"
#include "mojo/message_pump/message_pump_mojo.h"
namespace sky {
namespace {
scoped_ptr<base::MessagePump> CreateMessagePumpMojo() {
return make_scoped_ptr(new mojo::common::MessagePumpMojo);
}
} // namespace
PlatformImpl::PlatformImpl()
: ui_task_runner_(base::MessageLoop::current()->task_runner()) {
base::Thread::Options options;
options.message_pump_factory = base::Bind(&CreateMessagePumpMojo);
io_thread_.reset(new base::Thread("io_thread"));
io_thread_->StartWithOptions(options);
io_task_runner_ = io_thread_->message_loop()->task_runner();
}
PlatformImpl::~PlatformImpl() {
}
blink::WebString PlatformImpl::defaultLocale() {
return blink::WebString::fromUTF8("en-US");
}
base::SingleThreadTaskRunner* PlatformImpl::GetUITaskRunner() {
return ui_task_runner_.get();
}
base::SingleThreadTaskRunner* PlatformImpl::GetIOTaskRunner() {
return io_task_runner_.get();
}
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_SKY_PLATFORM_PLATFORM_IMPL_H_
#define SERVICES_SKY_PLATFORM_PLATFORM_IMPL_H_
#include "base/message_loop/message_loop.h"
#include "sky/engine/public/platform/Platform.h"
#include "base/threading/thread.h"
namespace sky {
class PlatformImpl : public blink::Platform {
public:
explicit PlatformImpl();
~PlatformImpl() override;
// blink::Platform methods:
blink::WebString defaultLocale() override;
base::SingleThreadTaskRunner* GetUITaskRunner() override;
base::SingleThreadTaskRunner* GetIOTaskRunner() override;
private:
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
scoped_ptr<base::Thread> io_thread_;
DISALLOW_COPY_AND_ASSIGN(PlatformImpl);
};
} // namespace sky
#endif // SERVICES_SKY_PLATFORM_PLATFORM_IMPL_H_
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/sky/runtime_flags.h"
#include "base/logging.h"
#include "mojo/public/cpp/application/application_impl.h"
namespace sky {
namespace {
bool initialized = false;
RuntimeFlags flags;
// Load the viewer in testing mode so we can dump pixels.
const char kTesting[] = "--testing";
// Instruct the DartVM to report type errors.
const char kEnableCheckedMode[] = "--enable-checked-mode";
} // namespace
void RuntimeFlags::Initialize(mojo::ApplicationImpl* app) {
DCHECK(!initialized);
flags.testing_ = app->HasArg(kTesting);
flags.enable_checked_mode_ = app->HasArg(kEnableCheckedMode);
initialized = true;
}
const RuntimeFlags& RuntimeFlags::Get() {
DCHECK(initialized);
return flags;
}
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SERVICES_SKY_RUNTIME_FLAGS_H_
#define SERVICES_SKY_RUNTIME_FLAGS_H_
namespace mojo {
class ApplicationImpl;
}
namespace sky {
class RuntimeFlags {
public:
static void Initialize(mojo::ApplicationImpl* app);
static const RuntimeFlags& Get();
bool testing() const { return testing_; }
bool enable_checked_mode() const { return enable_checked_mode_; }
private:
bool testing_ = false;
bool enable_checked_mode_ = false;
};
} // namespace sky
#endif // SERVICES_SKY_RUNTIME_FLAGS_H_
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/files/file_path.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread.h"
#include "mojo/application/application_runner_chromium.h"
#include "mojo/common/tracing_impl.h"
#include "mojo/icu/icu.h"
#include "mojo/public/c/system/main.h"
#include "mojo/public/cpp/application/application_connection.h"
#include "mojo/public/cpp/application/application_delegate.h"
#include "mojo/public/cpp/application/application_impl.h"
#include "mojo/public/cpp/application/interface_factory_impl.h"
#include "mojo/services/content_handler/interfaces/content_handler.mojom.h"
#include "services/sky/content_handler_impl.h"
#include "services/sky/document_view.h"
#include "services/sky/platform_impl.h"
#include "services/sky/runtime_flags.h"
#include "sky/engine/public/web/Sky.h"
#include "sky/engine/public/web/WebRuntimeFeatures.h"
namespace sky {
class Viewer : public mojo::ApplicationDelegate,
public mojo::InterfaceFactory<mojo::ContentHandler> {
public:
Viewer() {}
~Viewer() override { blink::shutdown(); }
private:
// Overridden from ApplicationDelegate:
void Initialize(mojo::ApplicationImpl* app) override {
RuntimeFlags::Initialize(app);
blink::WebRuntimeFeatures::enableObservatory(
!RuntimeFlags::Get().testing());
blink::WebRuntimeFeatures::enableDartCheckedMode(
RuntimeFlags::Get().enable_checked_mode());
platform_impl_.reset(new PlatformImpl());
blink::initialize(platform_impl_.get());
mojo::icu::Initialize(app);
tracing_.Initialize(app);
}
bool ConfigureIncomingConnection(
mojo::ApplicationConnection* connection) override {
connection->AddService<mojo::ContentHandler>(this);
return true;
}
// Overridden from InterfaceFactory<ContentHandler>
void Create(mojo::ApplicationConnection* connection,
mojo::InterfaceRequest<mojo::ContentHandler> request) override {
new ContentHandlerImpl(request.Pass());
}
scoped_ptr<PlatformImpl> platform_impl_;
mojo::TracingImpl tracing_;
DISALLOW_COPY_AND_ASSIGN(Viewer);
};
} // namespace sky
MojoResult MojoMain(MojoHandle application_request) {
mojo::ApplicationRunnerChromium runner(new sky::Viewer);
return runner.Run(application_request);
}
......@@ -4,20 +4,6 @@
root_dist_dir = "$root_build_dir/dist"
copy("sky_viewer") {
sources = [
"$root_build_dir/sky_viewer.mojo",
]
if (is_linux || is_android) {
sources += [ "$root_build_dir/symbols/libsky_viewer_library.so" ]
}
outputs = [ "$root_dist_dir/viewer/{{source_file_part}}" ]
deps = [
"//services/sky",
]
}
copy("sky_shell") {
if (is_android) {
sources = [
......@@ -99,9 +85,7 @@ if (is_android) {
}
group("dist") {
deps = [
":sky_viewer",
]
deps = []
if (!is_ios && !is_mac) {
deps += [ ":sky_shell" ]
......
......@@ -6,8 +6,6 @@ source_set("dart") {
sources = [
"dart_library_provider_files.cc",
"dart_library_provider_files.h",
"dart_library_provider_network.cc",
"dart_library_provider_network.h",
]
deps = [
......@@ -16,7 +14,6 @@ source_set("dart") {
"//dart/runtime:libdart",
"//mojo/data_pipe_utils",
"//mojo/public/cpp/application",
"//mojo/services/network/interfaces",
"//sky/engine/tonic",
"//sky/engine/wtf",
"//url",
......
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/shell/dart/dart_library_provider_network.h"
#include "base/bind.h"
#include "base/strings/string_util.h"
#include "sky/engine/tonic/dart_converter.h"
#include "url/gurl.h"
namespace sky {
namespace shell {
namespace {
mojo::URLLoaderPtr Fetch(mojo::NetworkService* network_service,
const std::string& url,
base::Callback<void(mojo::URLResponsePtr)> callback) {
mojo::URLLoaderPtr loader;
network_service->CreateURLLoader(GetProxy(&loader));
mojo::URLRequestPtr request = mojo::URLRequest::New();
request->url = url;
request->auto_follow_redirects = true;
loader->Start(request.Pass(), callback);
return loader.Pass();
}
} // namespace
class DartLibraryProviderNetwork::Job {
public:
Job(DartLibraryProviderNetwork* provider,
const std::string& name,
blink::DataPipeConsumerCallback callback)
: provider_(provider), callback_(callback), weak_factory_(this) {
url_loader_ =
Fetch(provider_->network_service(), name,
base::Bind(&Job::OnReceivedResponse, weak_factory_.GetWeakPtr()));
}
private:
void OnReceivedResponse(mojo::URLResponsePtr response) {
mojo::ScopedDataPipeConsumerHandle data;
if (response->status_code == 200)
data = response->body.Pass();
callback_.Run(data.Pass());
provider_->jobs_.remove(this);
// We're deleted now.
}
DartLibraryProviderNetwork* provider_;
blink::DataPipeConsumerCallback callback_;
mojo::URLLoaderPtr url_loader_;
base::WeakPtrFactory<Job> weak_factory_;
};
DartLibraryProviderNetwork::DartLibraryProviderNetwork(
mojo::NetworkService* network_service)
: network_service_(network_service) {
}
DartLibraryProviderNetwork::~DartLibraryProviderNetwork() {
}
void DartLibraryProviderNetwork::GetLibraryAsStream(
const std::string& name,
blink::DataPipeConsumerCallback callback) {
jobs_.add(adoptPtr(new Job(this, name, callback)));
}
Dart_Handle DartLibraryProviderNetwork::CanonicalizeURL(Dart_Handle library,
Dart_Handle url) {
std::string string = blink::StdStringFromDart(url);
if (base::StartsWithASCII(string, "dart:", true))
return url;
// TODO(abarth): The package root should be configurable.
if (base::StartsWithASCII(string, "package:", true))
base::ReplaceFirstSubstringAfterOffset(&string, 0, "package:", "/packages/");
GURL library_url(blink::StdStringFromDart(Dart_LibraryUrl(library)));
GURL resolved_url = library_url.Resolve(string);
return blink::StdStringToDart(resolved_url.spec());
}
} // namespace shell
} // namespace sky
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SKY_SHELL_DART_DART_LIBRARY_PROVIDER_NETWORK_H_
#define SKY_SHELL_DART_DART_LIBRARY_PROVIDER_NETWORK_H_
#include "mojo/services/network/interfaces/network_service.mojom.h"
#include "sky/engine/tonic/dart_library_provider.h"
#include "sky/engine/wtf/HashSet.h"
#include "sky/engine/wtf/OwnPtr.h"
namespace sky {
namespace shell {
class DartLibraryProviderNetwork : public blink::DartLibraryProvider {
public:
explicit DartLibraryProviderNetwork(mojo::NetworkService* network_service);
~DartLibraryProviderNetwork() override;
mojo::NetworkService* network_service() const { return network_service_; }
protected:
// |DartLibraryProvider| implementation:
void GetLibraryAsStream(const std::string& name,
blink::DataPipeConsumerCallback callback) override;
Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url) override;
private:
class Job;
mojo::NetworkService* network_service_;
HashSet<OwnPtr<Job>> jobs_;
DISALLOW_COPY_AND_ASSIGN(DartLibraryProviderNetwork);
};
} // namespace shell
} // namespace sky
#endif // SKY_SHELL_DART_DART_LIBRARY_PROVIDER_NETWORK_H_
......@@ -34,7 +34,6 @@ mojo_native_application("mojo") {
"//mojo/services/native_viewport/interfaces",
"//mojo/services/service_registry/interfaces",
"//services/asset_bundle:lib",
"//services/sky/compositor",
"//skia",
"//sky/engine/public/sky",
"//sky/engine/tonic",
......
......@@ -17,7 +17,6 @@
#include "sky/engine/public/web/Sky.h"
#include "sky/engine/public/web/WebRuntimeFeatures.h"
#include "sky/shell/dart/dart_library_provider_files.h"
#include "sky/shell/dart/dart_library_provider_network.h"
#include "sky/shell/shell.h"
#include "sky/shell/ui/animator.h"
#include "sky/shell/ui/internals.h"
......
......@@ -50,8 +50,6 @@ ARTIFACTS = {
Artifact('shell', 'SkyShell.apk'),
Artifact('shell', 'flutter.mojo'),
Artifact('shell', 'libflutter_library.so'),
Artifact('viewer', 'sky_viewer.mojo'),
Artifact('viewer', 'libsky_viewer_library.so'),
],
'linux-x64': [
Artifact('shell', 'icudtl.dat'),
......@@ -59,8 +57,6 @@ ARTIFACTS = {
Artifact('shell', 'sky_snapshot'),
Artifact('shell', 'flutter.mojo'),
Artifact('shell', 'libflutter_library.so'),
Artifact('viewer', 'sky_viewer.mojo'),
Artifact('viewer', 'libsky_viewer_library.so'),
]
}
......
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from skypy.find_tests import find_tests
from skypy.paths import Paths
import argparse
import os
import re
import requests
import skypy.configuration as configuration
import skypy.skyserver
import subprocess
SUPPORTED_MIME_TYPES = [
'text/sky',
'application/dart',
]
HTTP_PORT = 9999
URL_ROOT = 'http://localhost:%s/' % HTTP_PORT
DASHBOARD_URL = 'https://chromeperf.appspot.com/add_point'
BENCHMARKS_DIR = 'benchmarks'
def values_from_output(output):
# Parse out the raw values from the PerfRunner output:
# values 90, 89, 93 ms
# We'll probably need a fancier parser at some point.
match = re.search(r'values (.+) ms', output, flags=re.MULTILINE)
return map(float, match.group(1).split(', '))
def create_json_blob(values):
revision = subprocess.check_output(["git", "show-ref", "HEAD", "-s"]).strip()
return {
"master": "master.mojo.perf",
"bot": "sky-release",
"point_id": 123456, # FIXME: We need to generate a monotonicly increasing number somehow.
"versions": {
"mojo": revision
},
"chart_data": {
"format_version": "1.0",
"benchmark_name": "layout.simple-blocks",
"charts": {
"warm_times": {
"traces": {
"layout.simple-blocks": {
"type": "list_of_scalar_values",
"values": values,
},
}
}
}
}
}
def send_json_to_dashboard(json):
requests.post(DASHBOARD_URL, params={ 'data': json })
class PerfHarness(object):
def __init__(self, args):
self._sky_server = None
self.paths = Paths(os.path.join('out', 'Debug'))
self.args = args
def _start_server(self):
# TODO(eseidel): Shouldn't this just use skyserver.py?
return subprocess.Popen([
SkyServer.sky_server_path(),
self.paths.src_root,
str(HTTP_PORT),
'-t', self.args.configuration
])
def _sky_tester_command(self, url):
content_handlers = ['%s,%s' % (mime_type, 'mojo:sky_viewer')
for mime_type in SUPPORTED_MIME_TYPES]
return [
self.paths.mojo_shell_path,
'--args-for=mojo:native_viewport_service --use-headless-config --use-osmesa',
'--args-for=mojo:window_manager %s' % url,
'--content-handlers=%s' % ','.join(content_handlers),
'--url-mappings=mojo:window_manager=mojo:sky_tester',
'mojo:window_manager',
]
def _url_for_path(self, path):
return URL_ROOT + os.path.relpath(path, self.paths.src_root)
def _run_tests(self, path):
url = self._url_for_path(path)
output = subprocess.check_output(
self._sky_tester_command(url),
stderr=subprocess.STDOUT)
values = values_from_output(output)
print os.path.basename(path), "=>", values
# FIXME: Upload JSON blob to results server:
# json = create_json_blob(values)
# send_json_to_dashboard(json)
def main(self):
self._start_server()
map(self._run_tests, find_tests(os.path.join(self.paths.sky_root, BENCHMARKS_DIR)))
def shutdown(self):
if self._sky_server:
self._sky_server.terminate()
def main():
parser = argparse.ArgumentParser(description='Sky performance tester')
configuration.add_arguments(parser)
args = parser.parse_args()
harness = PerfHarness(args)
try:
harness.main()
except (KeyboardInterrupt, SystemExit):
pass
finally:
harness.shutdown()
if __name__ == '__main__':
main()
#!mojo mojo:sky_viewer
<html>
<head>
<meta charset="utf-8">
<title>Credits</title>
<import src="/packages/sky/framework/elements/sky-scrollable.sky" />
<style>
body {
background-color: white;
font-size: 84%;
max-width: 1020px;
}
.page-title {
font-size: 164%;
font-weight: bold;
margin-top: 26px; /* Avoid Android status bar */
}
.product {
background-color: #c3d9ff;
border-radius: 5px;
margin-top: 16px;
overflow: auto;
padding: 2px;
}
.product .title {
float: left;
font-size: 110%;
font-weight: bold;
margin: 3px;
}
.product .homepage {
float: right;
margin: 3px;
text-align: right;
}
.product .homepage::after {
content: " - ";
}
.product .show {
float: right;
margin: 3px;
text-align: right;
}
.licence {
background-color: #e8eef7;
border-radius: 3px;
clear: both;
padding: 16px;
}
.licence h3 {
margin-top: 0;
}
.licence pre {
white-space: pre;
}
.dialog #print-link,
.dialog .homepage {
display: none;
}
sky-scrollable {
height: -webkit-fill-available;
}
pre, span, a {
display: paragraph;
}
</style>
</head>
<body>
<sky-scrollable>
<span class="page-title" style="float:left;">Credits</span>
<div style="clear:both; overflow:auto;"><!-- Chromium <3s the following projects -->
{{entries}}
</div>
</sky-scrollable>
</body>
</html>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册