diff --git a/DEPS b/DEPS index 2cce6ebae8..e2435b6efb 100644 --- a/DEPS +++ b/DEPS @@ -43,6 +43,8 @@ allowed_hosts = [ ] deps = { + 'src': 'https://github.com/flutter/buildroot.git' + '@' + '9a9f454f5f454c6c01ee3814daa151b0fd49df85', + # Fuchsia compatibility # # The dependencies in this section should match the layout in the Fuchsia gn diff --git a/engine/src/flutter/BUILD.gn b/engine/src/flutter/BUILD.gn index f608a6841b..b05d6bb460 100644 --- a/engine/src/flutter/BUILD.gn +++ b/engine/src/flutter/BUILD.gn @@ -3,16 +3,16 @@ # found in the LICENSE file. # This target will be built if no target is specified when invoking ninja. -group("default") { +group("flutter") { testonly = true deps = [ - "//sky", + "//flutter/sky", ] if (is_ios) { deps += [ - "//sky/services/dynamic:sdk_lib_archive", - "//sky/shell:flutter_framework", + "//flutter/services/dynamic:sdk_lib_archive", + "//flutter/sky/shell:flutter_framework", ] } } @@ -21,6 +21,6 @@ group("dist") { testonly = true deps = [ - "//sky/dist", + "//flutter/sky/dist", ] } diff --git a/engine/src/flutter/assets/BUILD.gn b/engine/src/flutter/assets/BUILD.gn new file mode 100644 index 0000000000..6541b8acd1 --- /dev/null +++ b/engine/src/flutter/assets/BUILD.gn @@ -0,0 +1,33 @@ +# 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. + +import("//mojo/public/mojo_application.gni") + +source_set("assets") { + sources = [ + "directory_asset_bundle.cc", + "directory_asset_bundle.h", + "unique_unzipper.cc", + "unique_unzipper.h", + "unzip_job.cc", + "unzip_job.h", + "zip_asset_bundle.cc", + "zip_asset_bundle.h", + "zip_asset_store.cc", + "zip_asset_store.h", + ] + + deps = [ + "//flutter/glue", + "//lib/ftl", + "//mojo/public/cpp/bindings:callback", + "//mojo/public/cpp/system", + "//mojo/public/cpp/bindings:utility", + "//third_party/zlib:minizip", + ] + + public_deps = [ + "//mojo/services/asset_bundle/interfaces", + ] +} diff --git a/engine/src/flutter/assets/directory_asset_bundle.cc b/engine/src/flutter/assets/directory_asset_bundle.cc new file mode 100644 index 0000000000..a922953afe --- /dev/null +++ b/engine/src/flutter/assets/directory_asset_bundle.cc @@ -0,0 +1,51 @@ +// Copyright 2016 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 "flutter/assets/directory_asset_bundle.h" + +#include +#include + +#include + +#include "flutter/glue/data_pipe_utils.h" +#include "lib/ftl/files/eintr_wrapper.h" +#include "lib/ftl/files/path.h" +#include "lib/ftl/files/unique_fd.h" + +namespace blink { + +void DirectoryAssetBundle::GetAsStream( + const mojo::String& asset_name, + const mojo::Callback& callback) { + mojo::DataPipe pipe; + callback.Run(std::move(pipe.consumer_handle)); + + std::string asset_path = + files::SimplifyPath(directory_ + "/" + asset_name.get()); + if (asset_path.find(directory_) != 0u) { + FTL_LOG(ERROR) << "Asset name '" << asset_name + << "' attempted to traverse outside asset bundle."; + return; + } + + // TODO(abarth): Consider moving the |open| call to task_runner_. + ftl::UniqueFD fd(HANDLE_EINTR(open(asset_path.c_str(), O_RDONLY))); + if (fd.get() < 0) + return; + glue::CopyFromFileDescriptor(std::move(fd), std::move(pipe.producer_handle), + task_runner_.get(), [](bool ignored) {}); +} + +DirectoryAssetBundle::~DirectoryAssetBundle() {} + +DirectoryAssetBundle::DirectoryAssetBundle( + mojo::InterfaceRequest request, + std::string directory, + ftl::RefPtr task_runner) + : binding_(this, std::move(request)), + directory_(std::move(directory)), + task_runner_(std::move(task_runner)) {} + +} // namespace blink diff --git a/engine/src/flutter/assets/directory_asset_bundle.h b/engine/src/flutter/assets/directory_asset_bundle.h new file mode 100644 index 0000000000..98f90b7396 --- /dev/null +++ b/engine/src/flutter/assets/directory_asset_bundle.h @@ -0,0 +1,42 @@ +// Copyright 2016 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 FLUTTER_ASSETS_DIRECTORY_ASSET_BUNDLE_H_ +#define FLUTTER_ASSETS_DIRECTORY_ASSET_BUNDLE_H_ + +#include "lib/ftl/macros.h" +#include "lib/ftl/tasks/task_runner.h" +#include "mojo/public/cpp/bindings/interface_request.h" +#include "mojo/public/cpp/bindings/strong_binding.h" +#include "mojo/public/cpp/environment/async_waiter.h" +#include "mojo/services/asset_bundle/interfaces/asset_bundle.mojom.h" + +namespace blink { + +// A mojo service that serves assets out of a directory. +class DirectoryAssetBundle : public mojo::asset_bundle::AssetBundle { + public: + DirectoryAssetBundle(mojo::InterfaceRequest request, + std::string directory, + ftl::RefPtr task_runner); + + // mojo::assert_bundle::AssetBundle implementation: + void GetAsStream( + const mojo::String& asset_name, + const mojo::Callback& callback) + override; + + private: + ~DirectoryAssetBundle() override; + + mojo::StrongBinding binding_; + const std::string directory_; + ftl::RefPtr task_runner_; + + FTL_DISALLOW_COPY_AND_ASSIGN(DirectoryAssetBundle); +}; + +} // namespace blink + +#endif // FLUTTER_ASSETS_DIRECTORY_ASSET_BUNDLE_H_ diff --git a/engine/src/flutter/assets/unique_unzipper.cc b/engine/src/flutter/assets/unique_unzipper.cc new file mode 100644 index 0000000000..2507e3d25b --- /dev/null +++ b/engine/src/flutter/assets/unique_unzipper.cc @@ -0,0 +1,15 @@ +// Copyright 2016 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 "flutter/assets/unique_unzipper.h" + +#include "third_party/zlib/contrib/minizip/unzip.h" + +namespace blink { + +void UniqueUnzipperTraits::Free(void* file) { + unzClose(file); +} + +} // namespace blink diff --git a/engine/src/flutter/assets/unique_unzipper.h b/engine/src/flutter/assets/unique_unzipper.h new file mode 100644 index 0000000000..7c592fb61d --- /dev/null +++ b/engine/src/flutter/assets/unique_unzipper.h @@ -0,0 +1,22 @@ +// Copyright 2016 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 FLUTTER_ASSETS_UNIQUE_UNZIPPER_H_ +#define FLUTTER_ASSETS_UNIQUE_UNZIPPER_H_ + +#include "lib/ftl/memory/unique_object.h" + +namespace blink { + +struct UniqueUnzipperTraits { + static inline void* InvalidValue() { return nullptr; } + static inline bool IsValid(void* value) { return value != InvalidValue(); } + static void Free(void* file); +}; + +using UniqueUnzipper = ftl::UniqueObject; + +} // namespace blink + +#endif // FLUTTER_ASSETS_UNIQUE_UNZIPPER_H_ diff --git a/engine/src/flutter/assets/unzip_job.cc b/engine/src/flutter/assets/unzip_job.cc new file mode 100644 index 0000000000..39475156fc --- /dev/null +++ b/engine/src/flutter/assets/unzip_job.cc @@ -0,0 +1,97 @@ +// Copyright 2016 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 "flutter/assets/unzip_job.h" + +#include + +#include "mojo/public/cpp/environment/environment.h" +#include "third_party/zlib/contrib/minizip/unzip.h" + +namespace blink { + +UnzipJob::UnzipJob(std::string zip_path, + std::string asset_name, + mojo::ScopedDataPipeProducerHandle producer, + ftl::RefPtr task_runner) + : zip_path_(std::move(zip_path)), + asset_name_(std::move(asset_name)), + producer_(std::move(producer)), + task_runner_(std::move(task_runner)), + waiter_(mojo::Environment::GetDefaultAsyncWaiter()), + wait_id_(0) { + task_runner_->PostTask([this]() { Start(); }); +} + +UnzipJob::~UnzipJob() {} + +void UnzipJob::Start() { + zip_file_.reset(unzOpen2(zip_path_.c_str(), nullptr)); + + if (!zip_file_.is_valid()) { + FTL_LOG(ERROR) << "Unable to open ZIP file: " << zip_path_; + delete this; + return; + } + + int result = unzLocateFile(zip_file_.get(), asset_name_.c_str(), 0); + if (result != UNZ_OK) { + FTL_LOG(WARNING) << "Requested asset '" << asset_name_ + << "' does not exist."; + delete this; + return; + } + + result = unzOpenCurrentFile(zip_file_.get()); + if (result != UNZ_OK) { + FTL_LOG(WARNING) << "unzOpenCurrentFile failed, error=" << result; + delete this; + return; + } + + OnHandleReady(MOJO_RESULT_OK); +} + +void UnzipJob::OnHandleReady(MojoResult result) { + if (result == MOJO_RESULT_OK) { + void* buffer = nullptr; + uint32_t size = 0; + result = mojo::BeginWriteDataRaw(producer_.get(), &buffer, &size, + MOJO_WRITE_DATA_FLAG_NONE); + if (result == MOJO_RESULT_OK) { + FTL_DCHECK(size < static_cast(std::numeric_limits::max())); + ssize_t bytes_read = unzReadCurrentFile(zip_file_.get(), buffer, size); + result = mojo::EndWriteDataRaw(producer_.get(), + std::max(0l, bytes_read)); + if (bytes_read < 0) { + FTL_LOG(WARNING) << "Asset unzip failed, error=" << bytes_read; + delete this; + } else if (result != MOJO_RESULT_OK) { + FTL_LOG(WARNING) << "Mojo EndWrite failed, error=" << result; + delete this; + } else if (bytes_read < size) { + // Reached EOF. Stop the process. + delete this; + } else { + task_runner_->PostTask([this]() { OnHandleReady(MOJO_RESULT_OK); }); + } + return; + } + } + if (result == MOJO_RESULT_SHOULD_WAIT) { + wait_id_ = + waiter_->AsyncWait(producer_.get().value(), MOJO_HANDLE_SIGNAL_WRITABLE, + MOJO_DEADLINE_INDEFINITE, &WaitComplete, this); + return; + } + delete this; +} + +void UnzipJob::WaitComplete(void* context, MojoResult result) { + UnzipJob* job = static_cast(context); + job->wait_id_ = 0; + job->OnHandleReady(result); +} + +} // namespace blink diff --git a/engine/src/flutter/assets/unzip_job.h b/engine/src/flutter/assets/unzip_job.h new file mode 100644 index 0000000000..36dfbebb1a --- /dev/null +++ b/engine/src/flutter/assets/unzip_job.h @@ -0,0 +1,47 @@ +// Copyright 2016 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 FLUTTER_ASSETS_UNZIP_JOB_H_ +#define FLUTTER_ASSETS_UNZIP_JOB_H_ + +#include +#include + +#include "flutter/assets/unique_unzipper.h" +#include "lib/ftl/macros.h" +#include "lib/ftl/memory/ref_counted.h" +#include "lib/ftl/tasks/task_runner.h" +#include "mojo/public/cpp/environment/async_waiter.h" +#include "mojo/services/asset_bundle/interfaces/asset_bundle.mojom.h" + +namespace blink { + +class UnzipJob { + public: + UnzipJob(std::string zip_path, + std::string asset_name, + mojo::ScopedDataPipeProducerHandle producer, + ftl::RefPtr task_runner); + ~UnzipJob(); + + private: + void Start(); + void OnHandleReady(MojoResult result); + static void WaitComplete(void* context, MojoResult result); + + const std::string zip_path_; + const std::string asset_name_; + mojo::ScopedDataPipeProducerHandle producer_; + ftl::RefPtr task_runner_; + UniqueUnzipper zip_file_; + + const MojoAsyncWaiter* waiter_; + MojoAsyncWaitID wait_id_; + + FTL_DISALLOW_COPY_AND_ASSIGN(UnzipJob); +}; + +} // namespace blink + +#endif // FLUTTER_ASSETS_UNZIP_JOB_H_ diff --git a/engine/src/flutter/assets/zip_asset_bundle.cc b/engine/src/flutter/assets/zip_asset_bundle.cc new file mode 100644 index 0000000000..245095a985 --- /dev/null +++ b/engine/src/flutter/assets/zip_asset_bundle.cc @@ -0,0 +1,26 @@ +// Copyright 2016 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 "flutter/assets/zip_asset_bundle.h" + +#include + +namespace blink { + +void ZipAssetBundle::GetAsStream( + const mojo::String& asset_name, + const mojo::Callback& callback) { + mojo::DataPipe pipe; + callback.Run(std::move(pipe.consumer_handle)); + store_->GetAsStream(asset_name.get(), std::move(pipe.producer_handle)); +} + +ZipAssetBundle::ZipAssetBundle( + mojo::InterfaceRequest request, + ftl::RefPtr store) + : binding_(this, std::move(request)), store_(std::move(store)) {} + +ZipAssetBundle::~ZipAssetBundle() {} + +} // namespace blink diff --git a/engine/src/flutter/assets/zip_asset_bundle.h b/engine/src/flutter/assets/zip_asset_bundle.h new file mode 100644 index 0000000000..cd35bd9d5b --- /dev/null +++ b/engine/src/flutter/assets/zip_asset_bundle.h @@ -0,0 +1,36 @@ +// Copyright 2016 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 FLUTTER_ASSETS_ZIP_ASSET_BUNDLE_H_ +#define FLUTTER_ASSETS_ZIP_ASSET_BUNDLE_H_ + +#include "flutter/assets/zip_asset_store.h" +#include "mojo/public/cpp/bindings/interface_request.h" +#include "mojo/public/cpp/bindings/strong_binding.h" +#include "mojo/services/asset_bundle/interfaces/asset_bundle.mojom.h" + +namespace blink { + +class ZipAssetBundle : public mojo::asset_bundle::AssetBundle { + public: + ZipAssetBundle( + mojo::InterfaceRequest request, + ftl::RefPtr store); + + // mojo::assert_bundle::AssetBundle implementation: + void GetAsStream( + const mojo::String& asset_name, + const mojo::Callback& callback) + override; + + private: + ~ZipAssetBundle() override; + + mojo::StrongBinding binding_; + ftl::RefPtr store_; +}; + +} // namespace blink + +#endif // FLUTTER_ASSETS_ZIP_ASSET_BUNDLE_H_ diff --git a/engine/src/flutter/assets/zip_asset_store.cc b/engine/src/flutter/assets/zip_asset_store.cc new file mode 100644 index 0000000000..fff0085a31 --- /dev/null +++ b/engine/src/flutter/assets/zip_asset_store.cc @@ -0,0 +1,87 @@ +// Copyright 2016 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 "flutter/assets/zip_asset_store.h" + +#include +#include + +#include + +#include "flutter/assets/unique_unzipper.h" +#include "flutter/assets/unzip_job.h" +#include "flutter/glue/data_pipe_utils.h" +#include "lib/ftl/files/eintr_wrapper.h" +#include "lib/ftl/files/unique_fd.h" +#include "third_party/zlib/contrib/minizip/unzip.h" + +namespace blink { + +ZipAssetStore::ZipAssetStore(std::string zip_path, + ftl::RefPtr task_runner) + : zip_path_(std::move(zip_path)), task_runner_(std::move(task_runner)) {} + +ZipAssetStore::~ZipAssetStore() {} + +void ZipAssetStore::AddOverlayFile(std::string asset_name, + std::string file_path) { + overlay_files_.emplace(std::move(asset_name), std::move(file_path)); +} + +void ZipAssetStore::GetAsStream(const std::string& asset_name, + mojo::ScopedDataPipeProducerHandle producer) { + auto overlay = overlay_files_.find(asset_name); + if (overlay != overlay_files_.end()) { + // TODO(abarth): Consider moving the |open| call to task_runner_. + ftl::UniqueFD fd(HANDLE_EINTR(open(overlay->second.c_str(), O_RDONLY))); + if (fd.get() < 0) + return; + glue::CopyFromFileDescriptor(std::move(fd), std::move(producer), + task_runner_.get(), [](bool ignored) {}); + } else { + new UnzipJob(zip_path_, asset_name, std::move(producer), task_runner_); + } +} + +bool ZipAssetStore::GetAsBuffer(const std::string& asset_name, + std::vector* data) { + UniqueUnzipper zip_file(unzOpen2(zip_path_.c_str(), nullptr)); + if (!zip_file.is_valid()) { + FTL_LOG(ERROR) << "Unable to open ZIP file: " << zip_path_; + return false; + } + + int result = unzLocateFile(zip_file.get(), asset_name.c_str(), 0); + if (result != UNZ_OK) { + return false; + } + + unz_file_info file_info; + result = unzGetCurrentFileInfo(zip_file.get(), &file_info, nullptr, 0, + nullptr, 0, nullptr, 0); + if (result != UNZ_OK) { + FTL_LOG(WARNING) << "unzGetCurrentFileInfo failed, error=" << result; + return false; + } + + result = unzOpenCurrentFile(zip_file.get()); + if (result != UNZ_OK) { + FTL_LOG(WARNING) << "unzOpenCurrentFile failed, error=" << result; + return false; + } + + data->resize(file_info.uncompressed_size); + int total_read = 0; + while (total_read < static_cast(data->size())) { + int bytes_read = unzReadCurrentFile( + zip_file.get(), data->data() + total_read, data->size() - total_read); + if (bytes_read <= 0) + return false; + total_read += bytes_read; + } + + return true; +} + +} // namespace blink diff --git a/engine/src/flutter/assets/zip_asset_store.h b/engine/src/flutter/assets/zip_asset_store.h new file mode 100644 index 0000000000..5bc7132149 --- /dev/null +++ b/engine/src/flutter/assets/zip_asset_store.h @@ -0,0 +1,40 @@ +// Copyright 2016 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 FLUTTER_ASSETS_ZIP_ASSET_STORE_H_ +#define FLUTTER_ASSETS_ZIP_ASSET_STORE_H_ + +#include +#include + +#include "lib/ftl/macros.h" +#include "lib/ftl/memory/ref_counted.h" +#include "lib/ftl/tasks/task_runner.h" +#include "mojo/public/cpp/system/data_pipe.h" + +namespace blink { + +class ZipAssetStore : public ftl::RefCountedThreadSafe { + public: + ZipAssetStore(std::string zip_path, ftl::RefPtr task_runner); + ~ZipAssetStore(); + + // Serve this asset from another file instead of using the ZIP contents. + void AddOverlayFile(std::string asset_name, std::string file_path); + + void GetAsStream(const std::string& asset_name, + mojo::ScopedDataPipeProducerHandle producer); + bool GetAsBuffer(const std::string& asset_name, std::vector* data); + + private: + const std::string zip_path_; + ftl::RefPtr task_runner_; + std::map overlay_files_; + + FTL_DISALLOW_COPY_AND_ASSIGN(ZipAssetStore); +}; + +} // namespace blink + +#endif // FLUTTER_ASSETS_ZIP_ASSET_STORE_H_ diff --git a/engine/src/flutter/flow/BUILD.gn b/engine/src/flutter/flow/BUILD.gn index a5ef7f5c7b..206040fd8d 100644 --- a/engine/src/flutter/flow/BUILD.gn +++ b/engine/src/flutter/flow/BUILD.gn @@ -44,10 +44,10 @@ source_set("flow") { ] deps = [ - "//glue", + "//flutter/glue", "//lib/ftl", "//mojo/services/gfx/composition/interfaces", "//mojo/skia", - "//skia", + "//flutter/skia", ] } diff --git a/engine/src/flutter/flow/compositor_context.cc b/engine/src/flutter/flow/compositor_context.cc index 7c1b75e57f..8e4ac1458d 100644 --- a/engine/src/flutter/flow/compositor_context.cc +++ b/engine/src/flutter/flow/compositor_context.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/compositor_context.h" +#include "flutter/flow/compositor_context.h" #include "third_party/skia/include/core/SkCanvas.h" diff --git a/engine/src/flutter/flow/compositor_context.h b/engine/src/flutter/flow/compositor_context.h index 8ede656d55..97629adaf0 100644 --- a/engine/src/flutter/flow/compositor_context.h +++ b/engine/src/flutter/flow/compositor_context.h @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_COMPOSITOR_CONTEXT_H_ -#define FLOW_COMPOSITOR_CONTEXT_H_ +#ifndef FLUTTER_FLOW_COMPOSITOR_CONTEXT_H_ +#define FLUTTER_FLOW_COMPOSITOR_CONTEXT_H_ #include #include -#include "flow/instrumentation.h" -#include "flow/raster_cache.h" +#include "flutter/flow/instrumentation.h" +#include "flutter/flow/raster_cache.h" #include "lib/ftl/macros.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPictureRecorder.h" @@ -72,4 +72,4 @@ class CompositorContext { } // namespace flow -#endif // FLOW_COMPOSITOR_CONTEXT_H_ +#endif // FLUTTER_FLOW_COMPOSITOR_CONTEXT_H_ diff --git a/engine/src/flutter/flow/instrumentation.cc b/engine/src/flutter/flow/instrumentation.cc index 6c139a561d..83f8136487 100644 --- a/engine/src/flutter/flow/instrumentation.cc +++ b/engine/src/flutter/flow/instrumentation.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/instrumentation.h" +#include "flutter/flow/instrumentation.h" #include diff --git a/engine/src/flutter/flow/instrumentation.h b/engine/src/flutter/flow/instrumentation.h index eb3c89d20c..d4a8c2b82b 100644 --- a/engine/src/flutter/flow/instrumentation.h +++ b/engine/src/flutter/flow/instrumentation.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_INSTRUMENTATION_H_ -#define FLOW_INSTRUMENTATION_H_ +#ifndef FLUTTER_FLOW_INSTRUMENTATION_H_ +#define FLUTTER_FLOW_INSTRUMENTATION_H_ #include @@ -67,4 +67,4 @@ class Counter { } // namespace flow -#endif // FLOW_INSTRUMENTATION_H_ +#endif // FLUTTER_FLOW_INSTRUMENTATION_H_ diff --git a/engine/src/flutter/flow/layers/backdrop_filter_layer.cc b/engine/src/flutter/flow/layers/backdrop_filter_layer.cc index f267c5edf0..2079b0047e 100644 --- a/engine/src/flutter/flow/layers/backdrop_filter_layer.cc +++ b/engine/src/flutter/flow/layers/backdrop_filter_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/backdrop_filter_layer.h" +#include "flutter/flow/layers/backdrop_filter_layer.h" #include "third_party/skia/include/core/SkImageFilter.h" diff --git a/engine/src/flutter/flow/layers/backdrop_filter_layer.h b/engine/src/flutter/flow/layers/backdrop_filter_layer.h index e16d82b598..e38891234f 100644 --- a/engine/src/flutter/flow/layers/backdrop_filter_layer.h +++ b/engine/src/flutter/flow/layers/backdrop_filter_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_BACKDROP_FILTER_LAYER_H_ -#define FLOW_LAYERS_BACKDROP_FILTER_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_BACKDROP_FILTER_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_BACKDROP_FILTER_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { @@ -27,4 +27,4 @@ class BackdropFilterLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_BACKDROP_FILTER_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_BACKDROP_FILTER_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/child_scene_layer.cc b/engine/src/flutter/flow/layers/child_scene_layer.cc index 3ef8ff2f74..84db5ab9b5 100644 --- a/engine/src/flutter/flow/layers/child_scene_layer.cc +++ b/engine/src/flutter/flow/layers/child_scene_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/child_scene_layer.h" +#include "flutter/flow/layers/child_scene_layer.h" #include "mojo/skia/type_converters.h" diff --git a/engine/src/flutter/flow/layers/child_scene_layer.h b/engine/src/flutter/flow/layers/child_scene_layer.h index d88cac4017..c2461caa2d 100644 --- a/engine/src/flutter/flow/layers/child_scene_layer.h +++ b/engine/src/flutter/flow/layers/child_scene_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_CHILD_SCENE_LAYER_H_ -#define FLOW_LAYERS_CHILD_SCENE_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_CHILD_SCENE_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_CHILD_SCENE_LAYER_H_ -#include "flow/layers/layer.h" +#include "flutter/flow/layers/layer.h" #include "mojo/services/gfx/composition/interfaces/scenes.mojom.h" namespace flow { @@ -46,4 +46,4 @@ class ChildSceneLayer : public Layer { } // namespace flow -#endif // FLOW_LAYERS_CHILD_SCENE_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_CHILD_SCENE_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/clip_path_layer.cc b/engine/src/flutter/flow/layers/clip_path_layer.cc index fa1622a539..9faf600002 100644 --- a/engine/src/flutter/flow/layers/clip_path_layer.cc +++ b/engine/src/flutter/flow/layers/clip_path_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/clip_path_layer.h" +#include "flutter/flow/layers/clip_path_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/clip_path_layer.h b/engine/src/flutter/flow/layers/clip_path_layer.h index 17838ed227..185f8b7be5 100644 --- a/engine/src/flutter/flow/layers/clip_path_layer.h +++ b/engine/src/flutter/flow/layers/clip_path_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_CLIP_PATH_LAYER_H_ -#define FLOW_LAYERS_CLIP_PATH_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_CLIP_PATH_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_CLIP_PATH_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { @@ -28,4 +28,4 @@ class ClipPathLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_CLIP_PATH_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_CLIP_PATH_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/clip_rect_layer.cc b/engine/src/flutter/flow/layers/clip_rect_layer.cc index 7c75644d9a..66db9c7d08 100644 --- a/engine/src/flutter/flow/layers/clip_rect_layer.cc +++ b/engine/src/flutter/flow/layers/clip_rect_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/clip_rect_layer.h" +#include "flutter/flow/layers/clip_rect_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/clip_rect_layer.h b/engine/src/flutter/flow/layers/clip_rect_layer.h index b23e2721b5..64d7dc4352 100644 --- a/engine/src/flutter/flow/layers/clip_rect_layer.h +++ b/engine/src/flutter/flow/layers/clip_rect_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_CLIP_RECT_LAYER_H_ -#define FLOW_LAYERS_CLIP_RECT_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_CLIP_RECT_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_CLIP_RECT_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { @@ -28,4 +28,4 @@ class ClipRectLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_CLIP_RECT_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_CLIP_RECT_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/clip_rrect_layer.cc b/engine/src/flutter/flow/layers/clip_rrect_layer.cc index 4ec794efe0..78b09d6452 100644 --- a/engine/src/flutter/flow/layers/clip_rrect_layer.cc +++ b/engine/src/flutter/flow/layers/clip_rrect_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/clip_rrect_layer.h" +#include "flutter/flow/layers/clip_rrect_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/clip_rrect_layer.h b/engine/src/flutter/flow/layers/clip_rrect_layer.h index 21137459a9..5dc4d8959d 100644 --- a/engine/src/flutter/flow/layers/clip_rrect_layer.h +++ b/engine/src/flutter/flow/layers/clip_rrect_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_CLIP_RRECT_LAYER_H_ -#define FLOW_LAYERS_CLIP_RRECT_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_CLIP_RRECT_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_CLIP_RRECT_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { @@ -28,4 +28,4 @@ class ClipRRectLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_CLIP_RRECT_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_CLIP_RRECT_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/color_filter_layer.cc b/engine/src/flutter/flow/layers/color_filter_layer.cc index 9abcd62bcc..9040019ce0 100644 --- a/engine/src/flutter/flow/layers/color_filter_layer.cc +++ b/engine/src/flutter/flow/layers/color_filter_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/color_filter_layer.h" +#include "flutter/flow/layers/color_filter_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/color_filter_layer.h b/engine/src/flutter/flow/layers/color_filter_layer.h index 05c57085dc..1fbd1ec897 100644 --- a/engine/src/flutter/flow/layers/color_filter_layer.h +++ b/engine/src/flutter/flow/layers/color_filter_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_COLOR_FILTER_LAYER_H_ -#define FLOW_LAYERS_COLOR_FILTER_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_COLOR_FILTER_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_COLOR_FILTER_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { @@ -32,4 +32,4 @@ class ColorFilterLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_COLOR_FILTER_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_COLOR_FILTER_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/container_layer.cc b/engine/src/flutter/flow/layers/container_layer.cc index ee29d74d87..684e98815f 100644 --- a/engine/src/flutter/flow/layers/container_layer.cc +++ b/engine/src/flutter/flow/layers/container_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/container_layer.h b/engine/src/flutter/flow/layers/container_layer.h index 37ede5b11f..1663b35fd4 100644 --- a/engine/src/flutter/flow/layers/container_layer.h +++ b/engine/src/flutter/flow/layers/container_layer.h @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_CONTAINER_LAYER_H_ -#define FLOW_LAYERS_CONTAINER_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_CONTAINER_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_CONTAINER_LAYER_H_ #include -#include "flow/layers/layer.h" +#include "flutter/flow/layers/layer.h" namespace flow { @@ -35,4 +35,4 @@ class ContainerLayer : public Layer { } // namespace flow -#endif // FLOW_LAYERS_CONTAINER_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_CONTAINER_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/layer.cc b/engine/src/flutter/flow/layers/layer.cc index 5b2434745e..3bbcec8abd 100644 --- a/engine/src/flutter/flow/layers/layer.cc +++ b/engine/src/flutter/flow/layers/layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/layer.h" +#include "flutter/flow/layers/layer.h" #include "third_party/skia/include/core/SkColorFilter.h" diff --git a/engine/src/flutter/flow/layers/layer.h b/engine/src/flutter/flow/layers/layer.h index 8b551b694d..342223c9eb 100644 --- a/engine/src/flutter/flow/layers/layer.h +++ b/engine/src/flutter/flow/layers/layer.h @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_LAYER_H_ -#define FLOW_LAYERS_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_LAYER_H_ #include #include -#include "flow/instrumentation.h" -#include "flow/raster_cache.h" -#include "glue/trace_event.h" +#include "flutter/flow/instrumentation.h" +#include "flutter/flow/raster_cache.h" +#include "flutter/glue/trace_event.h" #include "lib/ftl/logging.h" #include "lib/ftl/macros.h" #include "third_party/skia/include/core/SkCanvas.h" @@ -85,4 +85,4 @@ class Layer { } // namespace flow -#endif // FLOW_LAYERS_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/layer_tree.cc b/engine/src/flutter/flow/layers/layer_tree.cc index f078137322..5bdd9c1a17 100644 --- a/engine/src/flutter/flow/layers/layer_tree.cc +++ b/engine/src/flutter/flow/layers/layer_tree.cc @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/layer_tree.h" +#include "flutter/flow/layers/layer_tree.h" -#include "glue/trace_event.h" -#include "flow/layers/layer.h" +#include "flutter/glue/trace_event.h" +#include "flutter/flow/layers/layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/layer_tree.h b/engine/src/flutter/flow/layers/layer_tree.h index 30252190cb..a205467475 100644 --- a/engine/src/flutter/flow/layers/layer_tree.h +++ b/engine/src/flutter/flow/layers/layer_tree.h @@ -2,15 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_LAYER_TREE_H_ -#define FLOW_LAYERS_LAYER_TREE_H_ +#ifndef FLUTTER_FLOW_LAYERS_LAYER_TREE_H_ +#define FLUTTER_FLOW_LAYERS_LAYER_TREE_H_ #include #include -#include "flow/compositor_context.h" -#include "flow/layers/layer.h" +#include "flutter/flow/compositor_context.h" +#include "flutter/flow/layers/layer.h" #include "lib/ftl/macros.h" #include "lib/ftl/time/time_delta.h" #include "third_party/skia/include/core/SkSize.h" @@ -75,4 +75,4 @@ class LayerTree { } // namespace flow -#endif // FLOW_LAYERS_LAYER_TREE_H_ +#endif // FLUTTER_FLOW_LAYERS_LAYER_TREE_H_ diff --git a/engine/src/flutter/flow/layers/opacity_layer.cc b/engine/src/flutter/flow/layers/opacity_layer.cc index 6fc68f493e..28b3f66fcc 100644 --- a/engine/src/flutter/flow/layers/opacity_layer.cc +++ b/engine/src/flutter/flow/layers/opacity_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/opacity_layer.h" +#include "flutter/flow/layers/opacity_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/opacity_layer.h b/engine/src/flutter/flow/layers/opacity_layer.h index 17a3edf03a..f5991b0aab 100644 --- a/engine/src/flutter/flow/layers/opacity_layer.h +++ b/engine/src/flutter/flow/layers/opacity_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_OPACITY_LAYER_H_ -#define FLOW_LAYERS_OPACITY_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_OPACITY_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_OPACITY_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { @@ -27,4 +27,4 @@ class OpacityLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_OPACITY_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_OPACITY_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/performance_overlay_layer.cc b/engine/src/flutter/flow/layers/performance_overlay_layer.cc index 77e676876d..66aa349bcb 100644 --- a/engine/src/flutter/flow/layers/performance_overlay_layer.cc +++ b/engine/src/flutter/flow/layers/performance_overlay_layer.cc @@ -6,7 +6,7 @@ #include #include -#include "flow/layers/performance_overlay_layer.h" +#include "flutter/flow/layers/performance_overlay_layer.h" namespace flow { namespace { diff --git a/engine/src/flutter/flow/layers/performance_overlay_layer.h b/engine/src/flutter/flow/layers/performance_overlay_layer.h index 51ec8eb956..1eaeb7c9a2 100644 --- a/engine/src/flutter/flow/layers/performance_overlay_layer.h +++ b/engine/src/flutter/flow/layers/performance_overlay_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_PERFORMANCE_OVERLAY_LAYER_H_ -#define FLOW_LAYERS_PERFORMANCE_OVERLAY_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_PERFORMANCE_OVERLAY_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_PERFORMANCE_OVERLAY_LAYER_H_ -#include "flow/layers/layer.h" +#include "flutter/flow/layers/layer.h" #include "lib/ftl/macros.h" namespace flow { @@ -29,4 +29,4 @@ class PerformanceOverlayLayer : public Layer { } // namespace flow -#endif // FLOW_LAYERS_PERFORMANCE_OVERLAY_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_PERFORMANCE_OVERLAY_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/picture_layer.cc b/engine/src/flutter/flow/layers/picture_layer.cc index cb36901b6a..2936314f5a 100644 --- a/engine/src/flutter/flow/layers/picture_layer.cc +++ b/engine/src/flutter/flow/layers/picture_layer.cc @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/picture_layer.h" +#include "flutter/flow/layers/picture_layer.h" -#include "flow/raster_cache.h" +#include "flutter/flow/raster_cache.h" #include "lib/ftl/logging.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/picture_layer.h b/engine/src/flutter/flow/layers/picture_layer.h index 4cd07967c3..c030578454 100644 --- a/engine/src/flutter/flow/layers/picture_layer.h +++ b/engine/src/flutter/flow/layers/picture_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_PICTURE_LAYER_H_ -#define FLOW_LAYERS_PICTURE_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_PICTURE_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_PICTURE_LAYER_H_ -#include "flow/layers/layer.h" +#include "flutter/flow/layers/layer.h" namespace flow { @@ -39,4 +39,4 @@ class PictureLayer : public Layer { } // namespace flow -#endif // FLOW_LAYERS_PICTURE_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_PICTURE_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/shader_mask_layer.cc b/engine/src/flutter/flow/layers/shader_mask_layer.cc index 5d57f616bc..446e745f79 100644 --- a/engine/src/flutter/flow/layers/shader_mask_layer.cc +++ b/engine/src/flutter/flow/layers/shader_mask_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/shader_mask_layer.h" +#include "flutter/flow/layers/shader_mask_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/shader_mask_layer.h b/engine/src/flutter/flow/layers/shader_mask_layer.h index 31a34b823b..4e32adfbfb 100644 --- a/engine/src/flutter/flow/layers/shader_mask_layer.h +++ b/engine/src/flutter/flow/layers/shader_mask_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_SHADER_MASK_LAYER_H_ -#define FLOW_LAYERS_SHADER_MASK_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_SHADER_MASK_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_SHADER_MASK_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" #include "third_party/skia/include/core/SkShader.h" @@ -37,4 +37,4 @@ class ShaderMaskLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_SHADER_MASK_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_SHADER_MASK_LAYER_H_ diff --git a/engine/src/flutter/flow/layers/transform_layer.cc b/engine/src/flutter/flow/layers/transform_layer.cc index 1b913c099d..2b7448ad9b 100644 --- a/engine/src/flutter/flow/layers/transform_layer.cc +++ b/engine/src/flutter/flow/layers/transform_layer.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/layers/transform_layer.h" +#include "flutter/flow/layers/transform_layer.h" namespace flow { diff --git a/engine/src/flutter/flow/layers/transform_layer.h b/engine/src/flutter/flow/layers/transform_layer.h index 9239a7cdc3..63439a410f 100644 --- a/engine/src/flutter/flow/layers/transform_layer.h +++ b/engine/src/flutter/flow/layers/transform_layer.h @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_LAYERS_TRANSFORM_LAYER_H_ -#define FLOW_LAYERS_TRANSFORM_LAYER_H_ +#ifndef FLUTTER_FLOW_LAYERS_TRANSFORM_LAYER_H_ +#define FLUTTER_FLOW_LAYERS_TRANSFORM_LAYER_H_ -#include "flow/layers/container_layer.h" +#include "flutter/flow/layers/container_layer.h" namespace flow { @@ -27,4 +27,4 @@ class TransformLayer : public ContainerLayer { } // namespace flow -#endif // FLOW_LAYERS_TRANSFORM_LAYER_H_ +#endif // FLUTTER_FLOW_LAYERS_TRANSFORM_LAYER_H_ diff --git a/engine/src/flutter/flow/open_gl.h b/engine/src/flutter/flow/open_gl.h index 13bcb0606f..b9beaad678 100644 --- a/engine/src/flutter/flow/open_gl.h +++ b/engine/src/flutter/flow/open_gl.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_OPEN_GL_H_ -#define FLOW_OPEN_GL_H_ +#ifndef FLUTTER_FLOW_OPEN_GL_H_ +#define FLUTTER_FLOW_OPEN_GL_H_ #include "lib/ftl/build_config.h" @@ -29,4 +29,4 @@ #endif -#endif // FLOW_OPEN_GL_H_ +#endif // FLUTTER_FLOW_OPEN_GL_H_ diff --git a/engine/src/flutter/flow/raster_cache.cc b/engine/src/flutter/flow/raster_cache.cc index a255eb16a9..8fcbc3b4b1 100644 --- a/engine/src/flutter/flow/raster_cache.cc +++ b/engine/src/flutter/flow/raster_cache.cc @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/raster_cache.h" +#include "flutter/flow/raster_cache.h" -#include "glue/trace_event.h" +#include "flutter/glue/trace_event.h" #include "lib/ftl/logging.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkImage.h" diff --git a/engine/src/flutter/flow/raster_cache.h b/engine/src/flutter/flow/raster_cache.h index a76d7264b9..6c9884026f 100644 --- a/engine/src/flutter/flow/raster_cache.h +++ b/engine/src/flutter/flow/raster_cache.h @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_RASTER_CACHE_H_ -#define FLOW_RASTER_CACHE_H_ +#ifndef FLUTTER_FLOW_RASTER_CACHE_H_ +#define FLUTTER_FLOW_RASTER_CACHE_H_ #include #include -#include "flow/instrumentation.h" +#include "flutter/flow/instrumentation.h" #include "lib/ftl/macros.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkSize.h" @@ -48,4 +48,4 @@ class RasterCache { } // namespace flow -#endif // FLOW_RASTER_CACHE_H_ +#endif // FLUTTER_FLOW_RASTER_CACHE_H_ diff --git a/engine/src/flutter/flow/texture_image.cc b/engine/src/flutter/flow/texture_image.cc index 184a247312..f7d1072d9f 100644 --- a/engine/src/flutter/flow/texture_image.cc +++ b/engine/src/flutter/flow/texture_image.cc @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "flow/open_gl.h" -#include "flow/texture_image.h" -#include "glue/trace_event.h" +#include "flutter/flow/open_gl.h" +#include "flutter/flow/texture_image.h" +#include "flutter/glue/trace_event.h" #include "third_party/skia/include/gpu/gl/GrGLTypes.h" namespace flow { diff --git a/engine/src/flutter/flow/texture_image.h b/engine/src/flutter/flow/texture_image.h index 18b6f2c31a..1596c7b79b 100644 --- a/engine/src/flutter/flow/texture_image.h +++ b/engine/src/flutter/flow/texture_image.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef FLOW_TEXTURE_IMAGE_H_ -#define FLOW_TEXTURE_IMAGE_H_ +#ifndef FLUTTER_FLOW_TEXTURE_IMAGE_H_ +#define FLUTTER_FLOW_TEXTURE_IMAGE_H_ #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkImageGenerator.h" @@ -17,4 +17,4 @@ sk_sp BitmapImageCreate(SkImageGenerator& generator); } // namespace flow -#endif // FLOW_TEXTURE_IMAGE_H_ +#endif // FLUTTER_FLOW_TEXTURE_IMAGE_H_ diff --git a/engine/src/flutter/glue/data_pipe_utils.cc b/engine/src/flutter/glue/data_pipe_utils.cc index 2412e032dc..de73cf0664 100644 --- a/engine/src/flutter/glue/data_pipe_utils.cc +++ b/engine/src/flutter/glue/data_pipe_utils.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "glue/data_pipe_utils.h" +#include "flutter/glue/data_pipe_utils.h" #include #include diff --git a/engine/src/flutter/glue/data_pipe_utils.h b/engine/src/flutter/glue/data_pipe_utils.h index 4ae71c425e..326054e62c 100644 --- a/engine/src/flutter/glue/data_pipe_utils.h +++ b/engine/src/flutter/glue/data_pipe_utils.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef GLUE_DATA_PIPE_FILES_H_ -#define GLUE_DATA_PIPE_FILES_H_ +#ifndef FLUTTER_GLU_DATA_PIPE_FILES_H_ +#define FLUTTER_GLU_DATA_PIPE_FILES_H_ #include @@ -35,4 +35,4 @@ void CopyFromFileDescriptor( } // namespace glue -#endif // GLUE_DATA_PIPE_FILES_H_ +#endif // FLUTTER_GLU_DATA_PIPE_FILES_H_ diff --git a/engine/src/flutter/glue/drain_data_pipe_job.cc b/engine/src/flutter/glue/drain_data_pipe_job.cc index 06fe05620d..89c985b73b 100644 --- a/engine/src/flutter/glue/drain_data_pipe_job.cc +++ b/engine/src/flutter/glue/drain_data_pipe_job.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "glue/drain_data_pipe_job.h" +#include "flutter/glue/drain_data_pipe_job.h" #include diff --git a/engine/src/flutter/glue/drain_data_pipe_job.h b/engine/src/flutter/glue/drain_data_pipe_job.h index 7baa1628ae..74d604475a 100644 --- a/engine/src/flutter/glue/drain_data_pipe_job.h +++ b/engine/src/flutter/glue/drain_data_pipe_job.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef GLUE_DRAIN_DATA_PIPE_JOB_H_ -#define GLUE_DRAIN_DATA_PIPE_JOB_H_ +#ifndef FLUTTER_GLU_DRAIN_DATA_PIPE_JOB_H_ +#define FLUTTER_GLU_DRAIN_DATA_PIPE_JOB_H_ #include #include @@ -32,4 +32,4 @@ class DrainDataPipeJob { } // namespace glue -#endif // GLUE_DRAIN_DATA_PIPE_JOB_H_ +#endif // FLUTTER_GLU_DRAIN_DATA_PIPE_JOB_H_ diff --git a/engine/src/flutter/glue/movable_wrapper.h b/engine/src/flutter/glue/movable_wrapper.h index 6ef7142054..03b3645aaf 100644 --- a/engine/src/flutter/glue/movable_wrapper.h +++ b/engine/src/flutter/glue/movable_wrapper.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef GLUE_MOVABLE_WRAPPER_H_ -#define GLUE_MOVABLE_WRAPPER_H_ +#ifndef FLUTTER_GLU_MOVABLE_WRAPPER_H_ +#define FLUTTER_GLU_MOVABLE_WRAPPER_H_ #include @@ -34,4 +34,4 @@ MovableWrapper WrapMovable(T object) { } // namespace glue -#endif // GLUE_MOVABLE_WRAPPER_H_ +#endif // FLUTTER_GLU_MOVABLE_WRAPPER_H_ diff --git a/engine/src/flutter/glue/stack_trace.cc b/engine/src/flutter/glue/stack_trace.cc index 7369f20bbe..9e9c1ef538 100644 --- a/engine/src/flutter/glue/stack_trace.cc +++ b/engine/src/flutter/glue/stack_trace.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "glue/stack_trace.h" +#include "flutter/glue/stack_trace.h" #include "base/debug/stack_trace.h" diff --git a/engine/src/flutter/glue/stack_trace.h b/engine/src/flutter/glue/stack_trace.h index f7129e1157..63a091672b 100644 --- a/engine/src/flutter/glue/stack_trace.h +++ b/engine/src/flutter/glue/stack_trace.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef GLUE_STACK_TRACE_H_ -#define GLUE_STACK_TRACE_H_ +#ifndef FLUTTER_GLU_STACK_TRACE_H_ +#define FLUTTER_GLU_STACK_TRACE_H_ namespace glue { @@ -11,4 +11,4 @@ void PrintStackTrace(); } // namespace glue -#endif // GLUE_STACK_TRACE_H_ +#endif // FLUTTER_GLU_STACK_TRACE_H_ diff --git a/engine/src/flutter/glue/task_runner_adaptor.cc b/engine/src/flutter/glue/task_runner_adaptor.cc index 97de71e404..8079aa4693 100644 --- a/engine/src/flutter/glue/task_runner_adaptor.cc +++ b/engine/src/flutter/glue/task_runner_adaptor.cc @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "glue/task_runner_adaptor.h" +#include "flutter/glue/task_runner_adaptor.h" #include diff --git a/engine/src/flutter/glue/task_runner_adaptor.h b/engine/src/flutter/glue/task_runner_adaptor.h index 0fad1ca998..2292527525 100644 --- a/engine/src/flutter/glue/task_runner_adaptor.h +++ b/engine/src/flutter/glue/task_runner_adaptor.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef GLUE_BASE_TASK_RUNNER_H_ -#define GLUE_BASE_TASK_RUNNER_H_ +#ifndef FLUTTER_GLU_BASE_TASK_RUNNER_H_ +#define FLUTTER_GLU_BASE_TASK_RUNNER_H_ #include "base/memory/ref_counted.h" #include "lib/ftl/tasks/task_runner.h" @@ -30,4 +30,4 @@ class TaskRunnerAdaptor : public ftl::TaskRunner { } // namespace glue -#endif // GLUE_BASE_TASK_RUNNER_H_ +#endif // FLUTTER_GLU_BASE_TASK_RUNNER_H_ diff --git a/engine/src/flutter/glue/thread.cc b/engine/src/flutter/glue/thread.cc index a250eec197..16d6c10a0a 100644 --- a/engine/src/flutter/glue/thread.cc +++ b/engine/src/flutter/glue/thread.cc @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "glue/thread.h" +#include "flutter/glue/thread.h" #include #include "base/threading/thread.h" -#include "glue/task_runner_adaptor.h" +#include "flutter/glue/task_runner_adaptor.h" namespace glue { diff --git a/engine/src/flutter/glue/thread.h b/engine/src/flutter/glue/thread.h index ec199433d5..bd6e68d27d 100644 --- a/engine/src/flutter/glue/thread.h +++ b/engine/src/flutter/glue/thread.h @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef GLUE_THREAD_H_ -#define GLUE_THREAD_H_ +#ifndef FLUTTER_GLU_THREAD_H_ +#define FLUTTER_GLU_THREAD_H_ #include @@ -31,4 +31,4 @@ class Thread { } // namespace glue -#endif // GLUE_THREAD_H_ +#endif // FLUTTER_GLU_THREAD_H_ diff --git a/engine/src/flutter/lib/jni/BUILD.gn b/engine/src/flutter/lib/jni/BUILD.gn new file mode 100644 index 0000000000..f7480a2eae --- /dev/null +++ b/engine/src/flutter/lib/jni/BUILD.gn @@ -0,0 +1,25 @@ +# Copyright 2016 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("jni") { + sources = [ + "dart_jni.cc", + "dart_jni.h", + "jni_api.cc", + "jni_api.h", + "jni_array.cc", + "jni_array.h", + "jni_class.cc", + "jni_class.h", + "jni_object.cc", + "jni_object.h", + "jni_string.cc", + "jni_string.h", + ] + + deps = [ + "//base", + "//flutter/tonic", + ] +} diff --git a/engine/src/flutter/lib/jni/dart_jni.cc b/engine/src/flutter/lib/jni/dart_jni.cc new file mode 100644 index 0000000000..ff0935d2a0 --- /dev/null +++ b/engine/src/flutter/lib/jni/dart_jni.cc @@ -0,0 +1,411 @@ +// Copyright 2016 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 "flutter/lib/jni/dart_jni.h" + +#include "base/android/jni_android.h" +#include "base/android/jni_string.h" +#include "base/logging.h" +#include "flutter/lib/jni/jni_api.h" +#include "flutter/lib/jni/jni_array.h" +#include "flutter/lib/jni/jni_class.h" +#include "flutter/lib/jni/jni_object.h" +#include "flutter/lib/jni/jni_string.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" + +namespace blink { + +using base::android::ScopedJavaGlobalRef; +using base::android::ScopedJavaLocalRef; +using tonic::DartConverter; +using tonic::StdStringToDart; +using tonic::ToDart; + +namespace { + +tonic::DartLibraryNatives* g_natives = nullptr; + +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); +} + +// Data cached from the Java VM. +struct DartJniJvmData { + ScopedJavaGlobalRef class_loader; + ScopedJavaGlobalRef class_clazz; + jmethodID class_loader_load_class_method_id; + jmethodID class_get_name_method_id; +}; + +DartJniJvmData* g_jvm_data = nullptr; +DartJniIsolateDataProvider g_isolate_data_provider = nullptr; + +DartJniIsolateData* IsolateData() { + return g_isolate_data_provider(); +} + +} // anonymous namespace + +// Check if a JNI API has thrown an exception. If so, convert it to a +// Dart exception. +bool CheckJniException(JNIEnv* env, Dart_Handle* exception) { + if (env->ExceptionCheck() == JNI_FALSE) + return false; + + jthrowable java_throwable = env->ExceptionOccurred(); + env->ExceptionClear(); + std::string info = base::android::GetJavaExceptionInfo(env, java_throwable); + + *exception = StdStringToDart(info); + return true; +} + +// Check if a Dart API returned an error handle. +bool CheckDartException(Dart_Handle result, Dart_Handle* exception) { + if (!Dart_IsError(result)) + return false; + + *exception = result; + return true; +} + +DART_NATIVE_CALLBACK_STATIC(JniApi, FromReflectedField); +DART_NATIVE_CALLBACK_STATIC(JniApi, FromReflectedMethod); +DART_NATIVE_CALLBACK_STATIC(JniApi, GetApplicationContext); +DART_NATIVE_CALLBACK_STATIC(JniApi, GetClassLoader); +DART_NATIVE_CALLBACK_STATIC(JniBooleanArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniByteArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniCharArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniClass, FromName); +DART_NATIVE_CALLBACK_STATIC(JniClass, FromClassObject); +DART_NATIVE_CALLBACK_STATIC(JniDoubleArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniFloatArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniIntArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniLongArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniObjectArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniShortArray, Create); +DART_NATIVE_CALLBACK_STATIC(JniString, Create); + +#define FOR_EACH_BINDING(V) \ + V(JniArray, GetLength) \ + V(JniBooleanArray, GetArrayElement) \ + V(JniBooleanArray, SetArrayElement) \ + V(JniByteArray, GetArrayElement) \ + V(JniByteArray, SetArrayElement) \ + V(JniCharArray, GetArrayElement) \ + V(JniCharArray, SetArrayElement) \ + V(JniClass, CallStaticBooleanMethod) \ + V(JniClass, CallStaticByteMethod) \ + V(JniClass, CallStaticCharMethod) \ + V(JniClass, CallStaticDoubleMethod) \ + V(JniClass, CallStaticFloatMethod) \ + V(JniClass, CallStaticIntMethod) \ + V(JniClass, CallStaticLongMethod) \ + V(JniClass, CallStaticObjectMethod) \ + V(JniClass, CallStaticShortMethod) \ + V(JniClass, CallStaticVoidMethod) \ + V(JniClass, GetFieldId) \ + V(JniClass, GetMethodId) \ + V(JniClass, GetStaticBooleanField) \ + V(JniClass, GetStaticByteField) \ + V(JniClass, GetStaticCharField) \ + V(JniClass, GetStaticDoubleField) \ + V(JniClass, GetStaticFieldId) \ + V(JniClass, GetStaticFloatField) \ + V(JniClass, GetStaticIntField) \ + V(JniClass, GetStaticLongField) \ + V(JniClass, GetStaticMethodId) \ + V(JniClass, GetStaticObjectField) \ + V(JniClass, GetStaticShortField) \ + V(JniClass, IsAssignable) \ + V(JniClass, NewObject) \ + V(JniClass, SetStaticBooleanField) \ + V(JniClass, SetStaticByteField) \ + V(JniClass, SetStaticCharField) \ + V(JniClass, SetStaticDoubleField) \ + V(JniClass, SetStaticFloatField) \ + V(JniClass, SetStaticIntField) \ + V(JniClass, SetStaticLongField) \ + V(JniClass, SetStaticObjectField) \ + V(JniClass, SetStaticShortField) \ + V(JniDoubleArray, GetArrayElement) \ + V(JniDoubleArray, SetArrayElement) \ + V(JniFloatArray, GetArrayElement) \ + V(JniFloatArray, SetArrayElement) \ + V(JniIntArray, GetArrayElement) \ + V(JniIntArray, SetArrayElement) \ + V(JniLongArray, GetArrayElement) \ + V(JniLongArray, SetArrayElement) \ + V(JniObject, CallBooleanMethod) \ + V(JniObject, CallByteMethod) \ + V(JniObject, CallCharMethod) \ + V(JniObject, CallDoubleMethod) \ + V(JniObject, CallFloatMethod) \ + V(JniObject, CallIntMethod) \ + V(JniObject, CallLongMethod) \ + V(JniObject, CallObjectMethod) \ + V(JniObject, CallShortMethod) \ + V(JniObject, CallVoidMethod) \ + V(JniObject, GetBooleanField) \ + V(JniObject, GetByteField) \ + V(JniObject, GetCharField) \ + V(JniObject, GetDoubleField) \ + V(JniObject, GetFloatField) \ + V(JniObject, GetIntField) \ + V(JniObject, GetLongField) \ + V(JniObject, GetObjectClass) \ + V(JniObject, GetObjectField) \ + V(JniObject, GetShortField) \ + V(JniObject, SetBooleanField) \ + V(JniObject, SetByteField) \ + V(JniObject, SetCharField) \ + V(JniObject, SetDoubleField) \ + V(JniObject, SetFloatField) \ + V(JniObject, SetIntField) \ + V(JniObject, SetLongField) \ + V(JniObject, SetObjectField) \ + V(JniObject, SetShortField) \ + V(JniObjectArray, GetArrayElement) \ + V(JniObjectArray, SetArrayElement) \ + V(JniShortArray, GetArrayElement) \ + V(JniShortArray, SetArrayElement) \ + V(JniString, GetText) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void DartJni::InitForGlobal(DartJniIsolateDataProvider provider) { + if (!g_isolate_data_provider) + g_isolate_data_provider = provider; + + if (!g_natives) { + g_natives = new tonic::DartLibraryNatives(); + g_natives->Register( + {DART_REGISTER_NATIVE_STATIC(JniApi, FromReflectedField), + DART_REGISTER_NATIVE_STATIC(JniApi, FromReflectedMethod), + DART_REGISTER_NATIVE_STATIC(JniApi, GetApplicationContext), + DART_REGISTER_NATIVE_STATIC(JniApi, GetClassLoader), + DART_REGISTER_NATIVE_STATIC(JniBooleanArray, Create), + DART_REGISTER_NATIVE_STATIC(JniByteArray, Create), + DART_REGISTER_NATIVE_STATIC(JniCharArray, Create), + DART_REGISTER_NATIVE_STATIC(JniClass, FromName), + DART_REGISTER_NATIVE_STATIC(JniClass, FromClassObject), + DART_REGISTER_NATIVE_STATIC(JniDoubleArray, Create), + DART_REGISTER_NATIVE_STATIC(JniFloatArray, Create), + DART_REGISTER_NATIVE_STATIC(JniIntArray, Create), + DART_REGISTER_NATIVE_STATIC(JniLongArray, Create), + DART_REGISTER_NATIVE_STATIC(JniObjectArray, Create), + DART_REGISTER_NATIVE_STATIC(JniShortArray, Create), + DART_REGISTER_NATIVE_STATIC(JniString, Create), + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); + } +} + +void DartJni::InitForIsolate() { + DCHECK(g_natives); + + Dart_Handle jni_library = Dart_LookupLibrary(ToDart("dart:jni")); + DART_CHECK_VALID(jni_library) + + DART_CHECK_VALID( + Dart_SetNativeResolver(jni_library, GetNativeFunction, GetSymbol)); + + Dart_Handle object_type = + Dart_GetType(jni_library, ToDart("JniObject"), 0, nullptr); + DART_CHECK_VALID(object_type); + IsolateData()->jni_object_type = Dart_NewPersistentHandle(object_type); + DART_CHECK_VALID(IsolateData()->jni_object_type); + + Dart_Handle float_type = + Dart_GetType(jni_library, ToDart("JniFloat"), 0, nullptr); + DART_CHECK_VALID(float_type); + IsolateData()->jni_float_type = Dart_NewPersistentHandle(float_type); + DART_CHECK_VALID(IsolateData()->jni_float_type); +} + +bool DartJni::InitJni() { + JNIEnv* env = base::android::AttachCurrentThread(); + + DCHECK(!g_jvm_data); + g_jvm_data = new DartJniJvmData(); + + g_jvm_data->class_loader.Reset(base::android::GetClassLoader(env)); + + ScopedJavaLocalRef class_loader_clazz( + env, env->FindClass("java/lang/ClassLoader")); + CHECK(!base::android::ClearException(env)); + + g_jvm_data->class_loader_load_class_method_id = + env->GetMethodID(class_loader_clazz.obj(), "loadClass", + "(Ljava/lang/String;)Ljava/lang/Class;"); + CHECK(!base::android::ClearException(env)); + + g_jvm_data->class_clazz.Reset(env, env->FindClass("java/lang/Class")); + CHECK(!base::android::ClearException(env)); + + g_jvm_data->class_get_name_method_id = env->GetMethodID( + g_jvm_data->class_clazz.obj(), "getName", "()Ljava/lang/String;"); + CHECK(!base::android::ClearException(env)); + + return true; +} + +void DartJni::OnThreadExit() { + base::android::DetachFromVM(); +} + +ScopedJavaLocalRef DartJni::GetClass(JNIEnv* env, const char* name) { + jobject clazz = env->CallObjectMethod( + g_jvm_data->class_loader.obj(), + g_jvm_data->class_loader_load_class_method_id, + base::android::ConvertUTF8ToJavaString(env, name).obj()); + + return ScopedJavaLocalRef(env, static_cast(clazz)); +} + +std::string DartJni::GetObjectClassName(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + DCHECK(clazz); + jstring name = static_cast( + env->CallObjectMethod(clazz, g_jvm_data->class_get_name_method_id)); + DCHECK(name); + + return base::android::ConvertJavaStringToUTF8(env, name); +} + +jstring DartJni::DartToJavaString(JNIEnv* env, + Dart_Handle dart_string, + Dart_Handle* exception) { + if (!Dart_IsString(dart_string)) { + *exception = ToDart("Argument must be a string"); + return nullptr; + } + + intptr_t length; + Dart_Handle result = Dart_StringLength(dart_string, &length); + if (CheckDartException(result, exception)) + return nullptr; + + std::vector string_data(length); + result = Dart_StringToUTF16(dart_string, string_data.data(), &length); + if (CheckDartException(result, exception)) + return nullptr; + + jstring java_string = env->NewString(string_data.data(), length); + CheckJniException(env, exception); + return java_string; +} + +jobject DartJni::class_loader() { + return g_jvm_data->class_loader.obj(); +} + +jclass DartJni::class_clazz() { + return g_jvm_data->class_clazz.obj(); +} + +Dart_Handle DartJni::jni_object_type() { + Dart_Handle object_type = + Dart_HandleFromPersistent(IsolateData()->jni_object_type); + DCHECK(!Dart_IsError(object_type)); + return object_type; +} + +Dart_Handle DartJni::jni_float_type() { + Dart_Handle float_type = + Dart_HandleFromPersistent(IsolateData()->jni_float_type); + DCHECK(!Dart_IsError(float_type)); + return float_type; +} + +void JniMethodArgs::Convert(JNIEnv* env, + const std::vector& dart_args, + Dart_Handle* exception) { + jvalues_.reserve(dart_args.size()); + + for (Dart_Handle dart_arg : dart_args) { + jvalue value = DartToJavaValue(env, dart_arg, exception); + if (*exception) + return; + jvalues_.push_back(value); + } +} + +jvalue JniMethodArgs::DartToJavaValue(JNIEnv* env, + Dart_Handle dart_value, + Dart_Handle* exception) { + jvalue java_value = jvalue(); + + if (Dart_IsBoolean(dart_value)) { + java_value.z = DartConverter::FromDart(dart_value); + return java_value; + } + + if (Dart_IsInteger(dart_value)) { + java_value.j = DartConverter::FromDart(dart_value); + return java_value; + } + + if (Dart_IsDouble(dart_value)) { + java_value.d = DartConverter::FromDart(dart_value); + return java_value; + } + + if (Dart_IsString(dart_value)) { + java_value.l = DartJni::DartToJavaString(env, dart_value, exception); + return java_value; + } + + if (Dart_IsNull(dart_value)) { + java_value.l = nullptr; + return java_value; + } + + bool is_object; + Dart_Handle result = + Dart_ObjectIsType(dart_value, DartJni::jni_object_type(), &is_object); + if (CheckDartException(result, exception)) + return java_value; + + if (is_object) { + JniObject* jni_object = DartConverter::FromDart(dart_value); + if (jni_object != nullptr) { + java_value.l = jni_object->java_object(); + } else { + *exception = ToDart("Invalid JniObject argument"); + } + return java_value; + } + + bool is_float; + result = Dart_ObjectIsType(dart_value, DartJni::jni_float_type(), &is_float); + if (CheckDartException(result, exception)) + return java_value; + + if (is_float) { + Dart_Handle value_handle = Dart_GetField(dart_value, ToDart("value")); + if (CheckDartException(value_handle, exception)) + return java_value; + + double double_value; + result = Dart_DoubleValue(value_handle, &double_value); + if (CheckDartException(result, exception)) + return java_value; + + java_value.f = static_cast(double_value); + return java_value; + } + + *exception = ToDart("Argument has unsupported data type"); + return java_value; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/jni/dart_jni.gni b/engine/src/flutter/lib/jni/dart_jni.gni new file mode 100644 index 0000000000..1a5b09d947 --- /dev/null +++ b/engine/src/flutter/lib/jni/dart_jni.gni @@ -0,0 +1,11 @@ +# Copyright 2016 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. + +dart_jni_files = [ + "//flutter/lib/jni/jni_helper.dart", + "//flutter/lib/jni/jni_raw.dart", + "//flutter/lib/jni/jni.dart", +] + +dart_jni_path = "//flutter/lib/jni/jni.dart" diff --git a/engine/src/flutter/lib/jni/dart_jni.h b/engine/src/flutter/lib/jni/dart_jni.h new file mode 100644 index 0000000000..0da3a0e340 --- /dev/null +++ b/engine/src/flutter/lib/jni/dart_jni.h @@ -0,0 +1,101 @@ +// Copyright 2016 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 FLUTTER_LIB_JNI_DART_JNI_H_ +#define FLUTTER_LIB_JNI_DART_JNI_H_ + +#include + +#include "base/android/jni_android.h" +#include "base/android/jni_utils.h" +#include "lib/tonic/dart_library_natives.h" +#include "lib/tonic/dart_wrappable.h" + +#define ENTER_JNI() \ + JNIEnv* env = base::android::AttachCurrentThread(); \ + base::android::ScopedJavaLocalFrame java_frame(env); + +namespace blink { + +bool CheckJniException(JNIEnv* env, Dart_Handle* exception); +bool CheckDartException(Dart_Handle result, Dart_Handle* exception); + +// Data cached for each Dart isolate. +struct DartJniIsolateData { + Dart_PersistentHandle jni_object_type; + Dart_PersistentHandle jni_float_type; +}; + +typedef DartJniIsolateData* (*DartJniIsolateDataProvider)(); + +class DartJni { + public: + static void InitForGlobal(DartJniIsolateDataProvider provider); + static void InitForIsolate(); + static bool InitJni(); + static void OnThreadExit(); + + static base::android::ScopedJavaLocalRef GetClass(JNIEnv* env, + const char* name); + + static std::string GetObjectClassName(JNIEnv* env, jobject obj); + + static jstring DartToJavaString(JNIEnv* env, + Dart_Handle dart_string, + Dart_Handle* exception); + + static jobject class_loader(); + static jclass class_clazz(); + static Dart_Handle jni_object_type(); + static Dart_Handle jni_float_type(); +}; + +class JniMethodArgs { + public: + void Convert(JNIEnv* env, + const std::vector& dart_args, + Dart_Handle* exception); + jvalue* jvalues() { return jvalues_.data(); } + + private: + jvalue DartToJavaValue(JNIEnv* env, + Dart_Handle handle, + Dart_Handle* exception); + + std::vector jvalues_; +}; + +} // namespace blink + +namespace tonic { + +template <> +struct DartConverter { + static jfieldID FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception) { + int64_t result = 0; + Dart_Handle handle = Dart_GetNativeIntegerArgument(args, index, &result); + if (Dart_IsError(handle)) + exception = handle; + return reinterpret_cast(result); + } +}; + +template <> +struct DartConverter { + static jmethodID FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception) { + int64_t result = 0; + Dart_Handle handle = Dart_GetNativeIntegerArgument(args, index, &result); + if (Dart_IsError(handle)) + exception = handle; + return reinterpret_cast(result); + } +}; + +} // namespace tonic + +#endif // FLUTTER_LIB_JNI_DART_JNI_H_ diff --git a/engine/src/flutter/lib/jni/jni.dart b/engine/src/flutter/lib/jni/jni.dart new file mode 100644 index 0000000000..8513a67bbe --- /dev/null +++ b/engine/src/flutter/lib/jni/jni.dart @@ -0,0 +1,67 @@ +// Copyright 2016 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. + +/// Invoke Java Native Interface APIs from Dart. +/// +/// To use, import `dart:jni`. +/// +/// Example: +/// +/// JavaClass dateFormatClass = Java.getClass('java.text.SimpleDateFormat'); +/// JavaObject format = dateFormatClass.newInstance('yyyy.MM.dd'); +/// print(format.parse('2016.01.01').getYear()); +/// +/// This library provides a way to access Java classes that are accessible to +/// the Android runtime hosting Flutter (including Android system APIs). +/// +/// The library consists of two parts: a raw module that offers Dart access +/// to low-level JNI functions, and a helper module that uses reflection to +/// build Java object wrappers that act like standard Dart objects. +/// +/// # Raw JNI +/// +/// Call [JniClass.fromName] to load a JNI class given its fully-qualified name. +/// The resulting [JniClass] object provides methods for constructing instances, +/// looking up field and method IDs, getting and setting static fields, and calling +/// static methods. These methods closely match the JNI functions provided by the VM. +/// +/// Getters/setters of object fields and calls to methods that return objects will +/// return instances of [JniObject]. [JniObject] similarly offers wrappers of the +/// JNI functions that get and set object fields and call object methods. +/// +/// Array instances are represented by [JniArray] and its subclasses, which provide +/// a Dart [List] interface backed by an underlying Java array. +/// +/// # Java Object Wrappers +/// +/// Call [Java.getClass] to create a [JavaClass] instance that acts as a higher-level +/// wrapper for a Java class. Using this wrapper, you can call static methods and read +/// and write static fields using standard Dart field and method syntax. The wrapper +/// will use reflection to locate the corresponding Java fields and methods and map Dart +/// operations to JNI calls. +/// +/// Use the [JavaClass.newInstance] method to construct instances of the class. +/// `newInstance` will pass its arguments to the appropriate constructor. +/// +/// Instances of Java objects are represented by [JavaObject], which similarly exposes +/// field and method accessors derived via reflection. +/// +/// Dart boolean, number, and string types as well as [JavaObject] instances can be passed +/// as arguments to wrapped Java methods. The JNI libraries will convert these arguments +/// from Dart types to the matching Java type. +/// +/// Dart does not support function overloading, and as a result the Java method +/// wrappers need to locate the method on the underlying Java class that most closely +/// matches the arguments passed to the wrapper. If there are multiple Java method overloads +/// that could be suitable for a given set of arguments and the wrappers do not choose the +/// desired overload, then you can obtain the [JniObject] wrapped by the [JavaObject] and +/// use the raw JNI library to invoke the method. + +library dart_jni; + +import 'dart:collection'; +import 'dart:nativewrappers'; + +part 'jni_raw.dart'; +part 'jni_helper.dart'; diff --git a/engine/src/flutter/lib/jni/jni_api.cc b/engine/src/flutter/lib/jni/jni_api.cc new file mode 100644 index 0000000000..2d71ecf4c7 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_api.cc @@ -0,0 +1,53 @@ +// Copyright 2016 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 "flutter/lib/jni/jni_api.h" + +#include "flutter/lib/jni/dart_jni.h" + +namespace blink { + +int64_t JniApi::FromReflectedField(const JniObject* field) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfieldID result = env->FromReflectedField(field->java_object()); + if (CheckJniException(env, &exception)) goto fail; + + return reinterpret_cast(result); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniApi::FromReflectedMethod(const JniObject* method) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jmethodID result = env->FromReflectedMethod(method->java_object()); + if (CheckJniException(env, &exception)) goto fail; + + return reinterpret_cast(result); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +ftl::RefPtr JniApi::GetApplicationContext() { + ENTER_JNI(); + return JniObject::Create(env, base::android::GetApplicationContext()); +} + +ftl::RefPtr JniApi::GetClassLoader() { + ENTER_JNI(); + return JniObject::Create(env, DartJni::class_loader()); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/jni/jni_api.h b/engine/src/flutter/lib/jni/jni_api.h new file mode 100644 index 0000000000..bbf2d24b33 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_api.h @@ -0,0 +1,24 @@ +// Copyright 2016 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 FLUTTER_LIB_JNI_JNI_API_H_ +#define FLUTTER_LIB_JNI_JNI_API_H_ + +#include "flutter/lib/jni/jni_class.h" +#include "flutter/lib/jni/jni_object.h" + +namespace blink { + +// Dart wrappers for basic JNI APIs. +class JniApi { + public: + static int64_t FromReflectedField(const JniObject* field); + static int64_t FromReflectedMethod(const JniObject* method); + static ftl::RefPtr GetApplicationContext(); + static ftl::RefPtr GetClassLoader(); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_JNI_JNI_API_H_ diff --git a/engine/src/flutter/lib/jni/jni_array.cc b/engine/src/flutter/lib/jni/jni_array.cc new file mode 100644 index 0000000000..ac1ff0f296 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_array.cc @@ -0,0 +1,579 @@ +// Copyright 2016 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 "flutter/lib/jni/jni_array.h" + +#include "flutter/lib/jni/dart_jni.h" + +namespace blink { + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniArray); + +JniArray::JniArray(JNIEnv* env, jarray array) : JniObject(env, array) {} + +JniArray::~JniArray() {} + +jsize JniArray::GetLength() { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jsize result = env->GetArrayLength(java_array()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +template +JArrayType JniArray::java_array() const { + return static_cast(java_object()); +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniObjectArray); + +JniObjectArray::JniObjectArray(JNIEnv* env, jobjectArray array) + : JniArray(env, array) {} + +JniObjectArray::~JniObjectArray() {} + +ftl::RefPtr JniObjectArray::Create(const JniClass* clazz, + jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jobjectArray array = + env->NewObjectArray(length, clazz->java_class(), nullptr); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +ftl::RefPtr JniObjectArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jobject obj = env->GetObjectArrayElement(java_array(), index); + if (CheckJniException(env, &exception)) + goto fail; + + return JniObject::Create(env, obj); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +void JniObjectArray::SetArrayElement(jsize index, const JniObject* value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetObjectArrayElement(java_array(), index, + value ? value->java_object() : nullptr); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniBooleanArray); + +JniBooleanArray::JniBooleanArray(JNIEnv* env, jbooleanArray array) + : JniArray(env, array) {} + +JniBooleanArray::~JniBooleanArray() {} + +ftl::RefPtr JniBooleanArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jbooleanArray array = env->NewBooleanArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +bool JniBooleanArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jboolean result; + env->GetBooleanArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return result == JNI_TRUE; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniBooleanArray::SetArrayElement(jsize index, bool value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jboolean jni_value = value ? JNI_TRUE : JNI_FALSE; + env->SetBooleanArrayRegion(java_array(), index, 1, + &jni_value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniByteArray); + +JniByteArray::JniByteArray(JNIEnv* env, jbyteArray array) + : JniArray(env, array) {} + +JniByteArray::~JniByteArray() {} + +ftl::RefPtr JniByteArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jbyteArray array = env->NewByteArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +int64_t JniByteArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jbyte result; + env->GetByteArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniByteArray::SetArrayElement(jsize index, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jbyte jni_value = static_cast(value); + env->SetByteArrayRegion(java_array(), index, 1, &jni_value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniCharArray); + +JniCharArray::JniCharArray(JNIEnv* env, jcharArray array) + : JniArray(env, array) {} + +JniCharArray::~JniCharArray() {} + +ftl::RefPtr JniCharArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jcharArray array = env->NewCharArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +int64_t JniCharArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jchar result; + env->GetCharArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniCharArray::SetArrayElement(jsize index, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jchar jni_value = static_cast(value); + env->SetCharArrayRegion(java_array(), index, 1, &jni_value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniShortArray); + +JniShortArray::JniShortArray(JNIEnv* env, jshortArray array) + : JniArray(env, array) {} + +JniShortArray::~JniShortArray() {} + +ftl::RefPtr JniShortArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jshortArray array = env->NewShortArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +int64_t JniShortArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jshort result; + env->GetShortArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniShortArray::SetArrayElement(jsize index, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jshort jni_value = static_cast(value); + env->SetShortArrayRegion(java_array(), index, 1, &jni_value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniIntArray); + +JniIntArray::JniIntArray(JNIEnv* env, jintArray array) : JniArray(env, array) {} + +JniIntArray::~JniIntArray() {} + +ftl::RefPtr JniIntArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jintArray array = env->NewIntArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +int64_t JniIntArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jint result; + env->GetIntArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniIntArray::SetArrayElement(jsize index, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jint jni_value = static_cast(value); + env->SetIntArrayRegion(java_array(), index, 1, &jni_value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniLongArray); + +JniLongArray::JniLongArray(JNIEnv* env, jlongArray array) + : JniArray(env, array) {} + +JniLongArray::~JniLongArray() {} + +ftl::RefPtr JniLongArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jlongArray array = env->NewLongArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +int64_t JniLongArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jlong result; + env->GetLongArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return static_cast(result); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniLongArray::SetArrayElement(jsize index, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jlong jni_value = static_cast(value); + env->SetLongArrayRegion(java_array(), index, 1, &jni_value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniFloatArray); + +JniFloatArray::JniFloatArray(JNIEnv* env, jfloatArray array) + : JniArray(env, array) {} + +JniFloatArray::~JniFloatArray() {} + +ftl::RefPtr JniFloatArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfloatArray array = env->NewFloatArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +double JniFloatArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfloat result; + env->GetFloatArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniFloatArray::SetArrayElement(jsize index, double value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfloat jni_value = static_cast(value); + env->SetFloatArrayRegion(java_array(), index, 1, &jni_value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniDoubleArray); + +JniDoubleArray::JniDoubleArray(JNIEnv* env, jdoubleArray array) + : JniArray(env, array) {} + +JniDoubleArray::~JniDoubleArray() {} + +ftl::RefPtr JniDoubleArray::Create(jsize length) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jdoubleArray array = env->NewDoubleArray(length); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, array); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +double JniDoubleArray::GetArrayElement(jsize index) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jdouble result; + env->GetDoubleArrayRegion(java_array(), index, 1, &result); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +void JniDoubleArray::SetArrayElement(jsize index, double value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetDoubleArrayRegion(java_array(), index, 1, &value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/jni/jni_array.h b/engine/src/flutter/lib/jni/jni_array.h new file mode 100644 index 0000000000..59e32327e6 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_array.h @@ -0,0 +1,177 @@ +// Copyright 2016 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 FLUTTER_LIB_JNI_JNI_ARRAY_H_ +#define FLUTTER_LIB_JNI_JNI_ARRAY_H_ + +#include + +#include "flutter/lib/jni/jni_class.h" +#include "flutter/lib/jni/jni_object.h" + +namespace blink { + +// Wrapper for a JNI array +class JniArray : public JniObject { + DEFINE_WRAPPERTYPEINFO(); + + public: + ~JniArray() override; + + jsize GetLength(); + + protected: + JniArray(JNIEnv* env, jarray array); + template + JArrayType java_array() const; +}; + +class JniObjectArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniObjectArray); + + public: + ~JniObjectArray() override; + + static ftl::RefPtr Create(const JniClass* clazz, + jsize length); + ftl::RefPtr GetArrayElement(jsize index); + void SetArrayElement(jsize index, const JniObject* value); + + private: + JniObjectArray(JNIEnv* env, jobjectArray array); +}; + +class JniBooleanArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniBooleanArray); + + public: + ~JniBooleanArray() override; + + static ftl::RefPtr Create(jsize length); + bool GetArrayElement(jsize index); + void SetArrayElement(jsize index, bool value); + + private: + JniBooleanArray(JNIEnv* env, jbooleanArray array); +}; + +class JniByteArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniByteArray); + + public: + ~JniByteArray() override; + + static ftl::RefPtr Create(jsize length); + int64_t GetArrayElement(jsize index); + void SetArrayElement(jsize index, int64_t value); + + private: + JniByteArray(JNIEnv* env, jbyteArray array); +}; + +class JniCharArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniCharArray); + + public: + ~JniCharArray() override; + + static ftl::RefPtr Create(jsize length); + int64_t GetArrayElement(jsize index); + void SetArrayElement(jsize index, int64_t value); + + private: + JniCharArray(JNIEnv* env, jcharArray array); +}; + +class JniShortArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniShortArray); + + public: + ~JniShortArray() override; + + static ftl::RefPtr Create(jsize length); + int64_t GetArrayElement(jsize index); + void SetArrayElement(jsize index, int64_t value); + + private: + JniShortArray(JNIEnv* env, jshortArray array); +}; + +class JniIntArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniIntArray); + + public: + ~JniIntArray() override; + + static ftl::RefPtr Create(jsize length); + int64_t GetArrayElement(jsize index); + void SetArrayElement(jsize index, int64_t value); + + private: + JniIntArray(JNIEnv* env, jintArray array); +}; + +class JniLongArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniLongArray); + + public: + ~JniLongArray() override; + + static ftl::RefPtr Create(jsize length); + int64_t GetArrayElement(jsize index); + void SetArrayElement(jsize index, int64_t value); + + private: + JniLongArray(JNIEnv* env, jlongArray array); +}; + +class JniFloatArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniFloatArray); + + public: + ~JniFloatArray() override; + + static ftl::RefPtr Create(jsize length); + double GetArrayElement(jsize index); + void SetArrayElement(jsize index, double value); + + private: + JniFloatArray(JNIEnv* env, jfloatArray array); +}; + +class JniDoubleArray : public JniArray { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniDoubleArray); + + public: + ~JniDoubleArray() override; + + static ftl::RefPtr Create(jsize length); + double GetArrayElement(jsize index); + void SetArrayElement(jsize index, double value); + + private: + JniDoubleArray(JNIEnv* env, jdoubleArray array); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_JNI_JNI_ARRAY_H_ diff --git a/engine/src/flutter/lib/jni/jni_class.cc b/engine/src/flutter/lib/jni/jni_class.cc new file mode 100644 index 0000000000..1f3cf22cb8 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_class.cc @@ -0,0 +1,720 @@ +// Copyright 2016 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 "flutter/lib/jni/jni_class.h" + +#include "flutter/lib/jni/dart_jni.h" + +namespace blink { + +using tonic::ToDart; +using base::android::ScopedJavaLocalRef; + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniClass); + +JniClass::JniClass(JNIEnv* env, jclass clazz) : JniObject(env, clazz) {} + +JniClass::~JniClass() {} + +ftl::RefPtr JniClass::FromName(const char* name) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + if (!name) + return nullptr; + + ScopedJavaLocalRef clazz = DartJni::GetClass(env, name); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, clazz.obj()); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +ftl::RefPtr JniClass::FromClassObject(const JniObject* clazz) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + if (!clazz) + return nullptr; + + jobject class_object = clazz->java_object(); + if (!env->IsInstanceOf(class_object, DartJni::class_clazz())) { + exception = ToDart("invalid JNI class object"); + goto fail; + } + + return ftl::MakeRefCounted(env, + static_cast(class_object)); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +intptr_t JniClass::GetFieldId(const char* name, const char* sig) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfieldID id = env->GetFieldID(java_class(), name, sig); + if (CheckJniException(env, &exception)) + goto fail; + + return reinterpret_cast(id); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +intptr_t JniClass::GetStaticFieldId(const char* name, const char* sig) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfieldID id = env->GetStaticFieldID(java_class(), name, sig); + if (CheckJniException(env, &exception)) + goto fail; + + return reinterpret_cast(id); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +intptr_t JniClass::GetMethodId(const char* name, const char* sig) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jmethodID id = env->GetMethodID(java_class(), name, sig); + if (CheckJniException(env, &exception)) + goto fail; + + return reinterpret_cast(id); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +intptr_t JniClass::GetStaticMethodId(const char* name, const char* sig) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jmethodID id = env->GetStaticMethodID(java_class(), name, sig); + if (CheckJniException(env, &exception)) + goto fail; + + return reinterpret_cast(id); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +ftl::RefPtr JniClass::NewObject( + jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jobject obj = env->NewObjectA(java_class(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return JniObject::Create(env, obj); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +bool JniClass::IsAssignable(const JniClass* clazz) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jboolean result = env->IsAssignableFrom(java_class(), clazz->java_class()); + if (CheckJniException(env, &exception)) + goto fail; + + return result == JNI_TRUE; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +ftl::RefPtr JniClass::GetStaticObjectField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jobject obj = env->GetStaticObjectField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return JniObject::Create(env, obj); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +bool JniClass::GetStaticBooleanField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jboolean result = env->GetStaticBooleanField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result == JNI_TRUE; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +int64_t JniClass::GetStaticByteField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jbyte result = env->GetStaticByteField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::GetStaticCharField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jchar result = env->GetStaticCharField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::GetStaticShortField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jshort result = env->GetStaticShortField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::GetStaticIntField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jint result = env->GetStaticIntField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::GetStaticLongField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jlong result = env->GetStaticLongField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniClass::GetStaticFloatField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfloat result = env->GetStaticFloatField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniClass::GetStaticDoubleField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfloat result = env->GetStaticDoubleField(java_class(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +void JniClass::SetStaticObjectField(jfieldID fieldId, const JniObject* value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticObjectField(java_class(), fieldId, + value ? value->java_object() : nullptr); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticBooleanField(jfieldID fieldId, bool value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticBooleanField(java_class(), fieldId, + value ? JNI_TRUE : JNI_FALSE); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticByteField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticByteField(java_class(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticCharField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticCharField(java_class(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticShortField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticShortField(java_class(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticIntField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticIntField(java_class(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticLongField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticLongField(java_class(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticFloatField(jfieldID fieldId, double value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticFloatField(java_class(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniClass::SetStaticDoubleField(jfieldID fieldId, double value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetStaticDoubleField(java_class(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +ftl::RefPtr JniClass::CallStaticObjectMethod( + jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jobject obj = env->CallStaticObjectMethodA(java_class(), methodId, + java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return JniObject::Create(env, obj); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +bool JniClass::CallStaticBooleanMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jboolean result = env->CallStaticBooleanMethodA(java_class(), methodId, + java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result == JNI_TRUE; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +int64_t JniClass::CallStaticByteMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jbyte result = + env->CallStaticByteMethodA(java_class(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::CallStaticCharMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jchar result = + env->CallStaticCharMethodA(java_class(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::CallStaticShortMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jshort result = env->CallStaticShortMethodA(java_class(), methodId, + java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::CallStaticIntMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jint result = + env->CallStaticIntMethodA(java_class(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniClass::CallStaticLongMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jlong result = + env->CallStaticLongMethodA(java_class(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniClass::CallStaticFloatMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jfloat result = env->CallStaticFloatMethodA(java_class(), methodId, + java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniClass::CallStaticDoubleMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jdouble result = env->CallStaticDoubleMethodA(java_class(), methodId, + java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +void JniClass::CallStaticVoidMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + env->CallStaticVoidMethodA(java_class(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/jni/jni_class.h b/engine/src/flutter/lib/jni/jni_class.h new file mode 100644 index 0000000000..696c84bc64 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_class.h @@ -0,0 +1,88 @@ +// Copyright 2016 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 FLUTTER_LIB_JNI_JNI_CLASS_H_ +#define FLUTTER_LIB_JNI_JNI_CLASS_H_ + +#include + +#include "base/android/jni_android.h" +#include "flutter/lib/jni/jni_object.h" +#include "lib/tonic/dart_wrappable.h" + +namespace blink { + +// Wrapper that exposes a JNI jclass to Dart +class JniClass : public JniObject { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniClass); + + public: + ~JniClass() override; + + static ftl::RefPtr FromName(const char* className); + static ftl::RefPtr FromClassObject(const JniObject* clazz); + + jclass java_class() const { return static_cast(object_.obj()); } + + intptr_t GetFieldId(const char* name, const char* sig); + intptr_t GetStaticFieldId(const char* name, const char* sig); + intptr_t GetMethodId(const char* name, const char* sig); + intptr_t GetStaticMethodId(const char* name, const char* sig); + + ftl::RefPtr NewObject(jmethodID methodId, + const std::vector& args); + + bool IsAssignable(const JniClass* clazz); + + ftl::RefPtr GetStaticObjectField(jfieldID fieldId); + bool GetStaticBooleanField(jfieldID fieldId); + int64_t GetStaticByteField(jfieldID fieldId); + int64_t GetStaticCharField(jfieldID fieldId); + int64_t GetStaticShortField(jfieldID fieldId); + int64_t GetStaticIntField(jfieldID fieldId); + int64_t GetStaticLongField(jfieldID fieldId); + double GetStaticFloatField(jfieldID fieldId); + double GetStaticDoubleField(jfieldID fieldId); + + void SetStaticObjectField(jfieldID fieldId, const JniObject* value); + void SetStaticBooleanField(jfieldID fieldId, bool value); + void SetStaticByteField(jfieldID fieldId, int64_t value); + void SetStaticCharField(jfieldID fieldId, int64_t value); + void SetStaticShortField(jfieldID fieldId, int64_t value); + void SetStaticIntField(jfieldID fieldId, int64_t value); + void SetStaticLongField(jfieldID fieldId, int64_t value); + void SetStaticFloatField(jfieldID fieldId, double value); + void SetStaticDoubleField(jfieldID fieldId, double value); + + ftl::RefPtr CallStaticObjectMethod( + jmethodID methodId, + const std::vector& args); + bool CallStaticBooleanMethod(jmethodID methodId, + const std::vector& args); + int64_t CallStaticByteMethod(jmethodID methodId, + const std::vector& args); + int64_t CallStaticCharMethod(jmethodID methodId, + const std::vector& args); + int64_t CallStaticShortMethod(jmethodID methodId, + const std::vector& args); + int64_t CallStaticIntMethod(jmethodID methodId, + const std::vector& args); + int64_t CallStaticLongMethod(jmethodID methodId, + const std::vector& args); + double CallStaticFloatMethod(jmethodID methodId, + const std::vector& args); + double CallStaticDoubleMethod(jmethodID methodId, + const std::vector& args); + void CallStaticVoidMethod(jmethodID methodId, + const std::vector& args); + + private: + JniClass(JNIEnv* env, jclass clazz); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_JNI_JNI_CLASS_H_ diff --git a/engine/src/flutter/lib/jni/jni_helper.dart b/engine/src/flutter/lib/jni/jni_helper.dart new file mode 100644 index 0000000000..3d222ae69c --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_helper.dart @@ -0,0 +1,647 @@ +// Copyright 2016 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. + +part of dart_jni; + +class JavaError extends Error { + JavaError(this._message); + String _message; + String toString() => _message; +} + +// JNI methods used to invoke Java reflection +class _JavaReflect { + JniClass classClazz; + int classForName; + int classGetConstructors; + int classGetFields; + int classGetMethods; + int classGetName; + int constructorGetParameterTypes; + int fieldGetType; + int memberGetModifiers; + int memberGetName; + int methodGetParameterTypes; + int methodGetReturnType; + int objectGetClass; + int objectToString; + JniClass stringClazz; + + int modifierStatic; + + _JavaReflect() { + classClazz = JniClass.fromName('java.lang.Class'); + classForName = classClazz.getStaticMethodId('forName', + '(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;'); + classGetConstructors = classClazz.getMethodId('getConstructors', + '()[Ljava/lang/reflect/Constructor;'); + classGetFields = classClazz.getMethodId('getFields', '()[Ljava/lang/reflect/Field;'); + classGetMethods = classClazz.getMethodId('getMethods', '()[Ljava/lang/reflect/Method;'); + classGetName = classClazz.getMethodId('getName', '()Ljava/lang/String;'); + + JniClass constructorClazz = JniClass.fromName('java.lang.reflect.Constructor'); + constructorGetParameterTypes = constructorClazz.getMethodId( + 'getParameterTypes', '()[Ljava/lang/Class;'); + + JniClass fieldClazz = JniClass.fromName('java.lang.reflect.Field'); + fieldGetType = fieldClazz.getMethodId('getType', '()Ljava/lang/Class;'); + + JniClass memberClazz = JniClass.fromName('java.lang.reflect.Member'); + memberGetModifiers = memberClazz.getMethodId('getModifiers', '()I'); + memberGetName = memberClazz.getMethodId('getName', '()Ljava/lang/String;'); + + JniClass methodClazz = JniClass.fromName('java.lang.reflect.Method'); + methodGetParameterTypes = methodClazz.getMethodId( + 'getParameterTypes', '()[Ljava/lang/Class;'); + methodGetReturnType = methodClazz.getMethodId( + 'getReturnType', '()Ljava/lang/Class;'); + + JniClass modifierClazz = JniClass.fromName('java.lang.reflect.Modifier'); + modifierStatic = modifierClazz.getStaticIntField( + modifierClazz.getStaticFieldId('STATIC', 'I')); + + JniClass objectClazz = JniClass.fromName('java.lang.Object'); + objectGetClass = objectClazz.getMethodId('getClass', '()Ljava/lang/Class;'); + objectToString = objectClazz.getMethodId('toString', '()Ljava/lang/String;'); + + stringClazz = JniClass.fromName('java.lang.String'); + } +} + +final _JavaReflect _reflect = new _JavaReflect(); + +class _JavaType { + final String name; + final JniClass clazz; + final bool isPrimitive; + + _JavaType(this.name, this.clazz) + : isPrimitive = false; + + _JavaType._primitive(this.name) + : clazz = null, + isPrimitive = true; + + String toString() => 'JavaType:$name'; +} + +class _JavaPrimitive { + static final _JavaType jvoid = new _JavaType._primitive('void'); + static final _JavaType jboolean = new _JavaType._primitive('boolean'); + static final _JavaType jbyte = new _JavaType._primitive('byte'); + static final _JavaType jchar = new _JavaType._primitive('char'); + static final _JavaType jshort = new _JavaType._primitive('short'); + static final _JavaType jint = new _JavaType._primitive('int'); + static final _JavaType jlong = new _JavaType._primitive('long'); + static final _JavaType jfloat = new _JavaType._primitive('float'); + static final _JavaType jdouble = new _JavaType._primitive('double'); +} + +final Map _typeCache = { + 'void': _JavaPrimitive.jvoid, + 'boolean': _JavaPrimitive.jboolean, + 'byte': _JavaPrimitive.jbyte, + 'char': _JavaPrimitive.jchar, + 'short': _JavaPrimitive.jshort, + 'int': _JavaPrimitive.jint, + 'long': _JavaPrimitive.jlong, + 'float': _JavaPrimitive.jfloat, + 'double': _JavaPrimitive.jdouble, +}; + +_JavaType _javaTypeForClass(JniClass clazz) { + String className = JniString.unwrap(clazz.callObjectMethod(_reflect.classGetName, [])); + + _JavaType type = _typeCache[className]; + if (type != null) + return type; + + type = new _JavaType(className, clazz); + _typeCache[className] = type; + return type; +} + +class _JavaField { + String name; + int fieldId; + _JavaType type; + int modifiers; + + _JavaField(JniObject field) { + name = JniString.unwrap(field.callObjectMethod(_reflect.memberGetName, [])); + fieldId = JniApi.fromReflectedField(field); + type = _javaTypeForClass( + field.callObjectMethod(_reflect.fieldGetType, [])); + modifiers = field.callIntMethod(_reflect.memberGetModifiers, []); + } + + bool get isStatic => (modifiers & _reflect.modifierStatic) != 0; +} + +abstract class _HasArguments { + String get name; + List<_JavaType> get argTypes; + int get methodId; +} + +class _JavaMethod implements _HasArguments { + String _name; + int _methodId; + _JavaType returnType; + int modifiers; + List<_JavaType> _argTypes; + + _JavaMethod(JniObject method) { + _name = JniString.unwrap(method.callObjectMethod(_reflect.memberGetName, [])); + _methodId = JniApi.fromReflectedMethod(method); + returnType = _javaTypeForClass( + method.callObjectMethod(_reflect.methodGetReturnType, [])); + modifiers = method.callIntMethod(_reflect.memberGetModifiers, []); + + JniObjectArray argClasses = method.callObjectMethod(_reflect.methodGetParameterTypes, []); + _argTypes = new List<_JavaType>(); + for (JniObject argClass in argClasses) { + _argTypes.add(_javaTypeForClass(argClass)); + } + } + + String get name => _name; + List<_JavaType> get argTypes => _argTypes; + int get methodId => _methodId; + + bool get isStatic => (modifiers & _reflect.modifierStatic) != 0; +} + +class _JavaConstructor implements _HasArguments { + String _name; + int _methodId; + List<_JavaType> _argTypes; + + _JavaConstructor(JniObject ctor) { + _name = JniString.unwrap(ctor.callObjectMethod(_reflect.memberGetName, [])); + _methodId = JniApi.fromReflectedMethod(ctor); + + JniObjectArray argClasses = ctor.callObjectMethod( + _reflect.constructorGetParameterTypes, []); + _argTypes = new List<_JavaType>(); + for (JniObject argClass in argClasses) { + _argTypes.add(_javaTypeForClass(argClass)); + } + } + + String get name => _name; + List<_JavaType> get argTypes => _argTypes; + int get methodId => _methodId; +} + +// Determines whether a Dart value can be used as a method argument declared as +// the given Java type. +bool _typeCompatible(dynamic value, _JavaType type) { + if (type.isPrimitive) { + if (type == _JavaPrimitive.jboolean) { + return (value is bool); + } else { + return (value is num || value is bool || value is JniFloat); + } + } + + if (value == null) + return true; + + if (value is JavaObject) + return value.javaClass.jniClass.isAssignable(type.clazz); + + if (value is JniObject) + return value.getObjectClass().isAssignable(type.clazz); + + if (value is String) { + if (type.isPrimitive) + return false; + return _reflect.stringClazz.isAssignable(type.clazz); + } + + return false; +} + +// Given a list of overloaded methods, select one that is the best match for +// the provided arguments. +_HasArguments _findMatchingMethod(List<_HasArguments> overloads, List args) { + List<_HasArguments> matches = new List<_HasArguments>(); + for (_HasArguments overload in overloads) { + if (overload.argTypes.length == args.length) + matches.add(overload); + } + + if (matches.length == 1) + return matches[0]; + + if (matches.isEmpty) + throw new JavaError('Argument mismatch when invoking method ${overloads[0].name}'); + + outer: for (_HasArguments match in matches) { + for (int i = 0; i < args.length; i++) { + if (!_typeCompatible(args[i], match.argTypes[i])) + continue outer; + } + return match; + } + + throw new JavaError('Unable to find matching method for ${overloads[0].name}'); +} + +// Convert an object received from JNI into the corresponding Dart type. +dynamic _javaObjectToDart(JniObject object) { + if (object == null) + return null; + + if (object is JniString) + return object.text; + + if (object is JniClass) + return Java.wrapClassObject(object); + + if (object is JniArray) + return object; + + return new JavaObject(object); +} + +// Convert a Dart object to a type suitable for passing to JNI. +dynamic _dartObjectToJava(dynamic object, _JavaType javaType) { + if (javaType.isPrimitive) { + if (javaType == _JavaPrimitive.jboolean) { + if (object is bool) + return object; + throw new JavaError('Unable to convert Dart object to Java boolean: $object'); + } + if (javaType == _JavaPrimitive.jfloat) { + if (object is JniFloat) + return object; + if (object is num) + return new JniFloat(object); + throw new JavaError('Unable to convert Dart object to Java float: $object'); + } + + if (object is num) + return object; + throw new JavaError('Unable to convert Dart object to Java primitive type: $object'); + } + + if (object == null) + return object; + + if (object is JniObject) + return object; + + if (object is JavaObject) + return object.jniObject; + + if (object is String) + return JniString.create(object); + + throw new JavaError('Unable to convert Dart object to Java: $object'); +} + +List _convertArgumentsToJava(List dartArgs, _HasArguments method) { + List result = new List(); + for (int i = 0; i < dartArgs.length; i++) { + result.add(_dartObjectToJava(dartArgs[i], method.argTypes[i])); + } + return result; +} + +/// A class that provides access to Java objects from within Dart. +class Java { + static final Map _classCache = new Map(); + + /// Returns a [JavaClass] for the given class name. + static JavaClass getClass(String className) { + JavaClass cacheEntry = _classCache[className]; + if (cacheEntry != null) + return cacheEntry; + + // Load and initialize the class + JniClass jniClass = _reflect.classClazz.callStaticObjectMethod( + _reflect.classForName, + [className, true, JniApi.getClassLoader()] + ); + + JavaClass javaClass = new JavaClass._(jniClass); + _classCache[javaClass.className] = javaClass; + return javaClass; + } + + /// Returns a [JavaClass] that wraps a raw JNI class object. + static JavaClass wrapClassObject(dynamic classObject) { + JniClass jniClass; + if (classObject is JniClass) { + jniClass = classObject; + } else if (classObject is JavaObject && classObject.jniObject is JniClass) { + jniClass = classObject.jniObject; + } else { + throw new JavaError('fromClassObject: $classObject is not a Java class'); + } + + String className = JniString.unwrap(jniClass.callObjectMethod(_reflect.classGetName, [])); + JavaClass cacheEntry = _classCache[className]; + if (cacheEntry != null) + return cacheEntry; + + JavaClass javaClass = new JavaClass._(jniClass); + _classCache[javaClass.className] = javaClass; + return javaClass; + } +} + +/// A wrapper for a JNI class that uses reflection to provide access to the +/// class' static fields, methods, and constructors. +class JavaClass { + JniClass _clazz; + String _className; + Map _fields; + Map _staticFields; + Map> _methods; + Map> _staticMethods; + List<_JavaConstructor> _constructors; + + static final Symbol _newInstanceSymbol = new Symbol('newInstance'); + + JavaClass._(JniClass classObject) { + _clazz = classObject; + _className = JniString.unwrap(_clazz.callObjectMethod(_reflect.classGetName, [])); + + _fields = new Map(); + _staticFields = new Map(); + JniObjectArray reflectFields = _clazz.callObjectMethod(_reflect.classGetFields, []); + for (JniObject reflectField in reflectFields) { + _JavaField javaField = new _JavaField(reflectField); + Map fieldMap = + javaField.isStatic ? _staticFields : _fields; + fieldMap[new Symbol(javaField.name)] = javaField; + + // Dart will identify the field setter with a symbol name ending with an equal sign. + fieldMap[new Symbol(javaField.name + '=')] = javaField; + } + + _methods = new Map>(); + _staticMethods = new Map>(); + JniObjectArray reflectMethods = _clazz.callObjectMethod(_reflect.classGetMethods, []); + for (JniObject reflectMethod in reflectMethods) { + _JavaMethod javaMethod = new _JavaMethod(reflectMethod); + Map> methodMap = + javaMethod.isStatic ? _staticMethods : _methods; + Symbol symbol = new Symbol(javaMethod.name); + List<_JavaMethod> overloads = methodMap[symbol]; + if (overloads != null) { + overloads.add(javaMethod); + } else { + methodMap[symbol] = <_JavaMethod>[javaMethod]; + } + } + + _constructors = new List<_JavaConstructor>(); + JniObjectArray reflectCtors = _clazz.callObjectMethod(_reflect.classGetConstructors, []); + for (JniObject ctor in reflectCtors) { + _constructors.add(new _JavaConstructor(ctor)); + } + } + + String toString() => 'JavaClass:$_className'; + + /// The name of the wrapped Java class. + String get className => _className; + + /// A raw [JniClass] representing the java.lang.Class instance for this class + JniClass get jniClass => _clazz; + + /// A [JavaObject] representing the java.lang.Class instance for this class + JavaObject get asJavaObject => new JavaObject(_clazz); + + dynamic noSuchMethod(Invocation invocation) { + if (invocation.isMethod) { + List<_HasArguments> overloads; + bool isConstructor = (invocation.memberName == _newInstanceSymbol); + if (isConstructor) { + overloads = _constructors; + } else { + overloads = _staticMethods[invocation.memberName]; + if (overloads == null) + throw new JavaError('Static method ${invocation.memberName} not found'); + } + + _HasArguments method = _findMatchingMethod(overloads, invocation.positionalArguments); + List args = _convertArgumentsToJava(invocation.positionalArguments, method); + + if (isConstructor) { + return new JavaObject(_clazz.newObject(method.methodId, args)); + } + + _JavaType returnType = (method as _JavaMethod).returnType; + if (returnType == _JavaPrimitive.jvoid) { + return _clazz.callStaticVoidMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jboolean) { + return _clazz.callStaticBooleanMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jbyte) { + return _clazz.callStaticByteMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jchar) { + return _clazz.callStaticCharMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jshort) { + return _clazz.callStaticShortMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jint) { + return _clazz.callStaticIntMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jlong) { + return _clazz.callStaticLongMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jfloat) { + return _clazz.callStaticFloatMethod(method.methodId, args); + } else if (returnType == _JavaPrimitive.jdouble) { + return _clazz.callStaticDoubleMethod(method.methodId, args); + } else { + return _javaObjectToDart( + _clazz.callStaticObjectMethod(method.methodId, args)); + } + } + + if (invocation.isGetter) { + _JavaField field = _staticFields[invocation.memberName]; + if (field == null) + throw new JavaError('Static field ${invocation.memberName} not found'); + + if (field.type == _JavaPrimitive.jboolean) { + return _clazz.getStaticBooleanField(field.fieldId); + } else if (field.type == _JavaPrimitive.jbyte) { + return _clazz.getStaticByteField(field.fieldId); + } else if (field.type == _JavaPrimitive.jchar) { + return _clazz.getStaticCharField(field.fieldId); + } else if (field.type == _JavaPrimitive.jshort) { + return _clazz.getStaticShortField(field.fieldId); + } else if (field.type == _JavaPrimitive.jint) { + return _clazz.getStaticIntField(field.fieldId); + } else if (field.type == _JavaPrimitive.jlong) { + return _clazz.getStaticLongField(field.fieldId); + } else if (field.type == _JavaPrimitive.jfloat) { + return _clazz.getStaticFloatField(field.fieldId); + } else if (field.type == _JavaPrimitive.jdouble) { + return _clazz.getStaticDoubleField(field.fieldId); + } else { + return _javaObjectToDart(_clazz.getStaticObjectField(field.fieldId)); + } + } + + if (invocation.isSetter) { + _JavaField field = _staticFields[invocation.memberName]; + if (field == null) + throw new JavaError('Static field ${invocation.memberName} not found'); + + dynamic value = invocation.positionalArguments[0]; + + if (field.type == _JavaPrimitive.jboolean) { + _clazz.setStaticBooleanField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jbyte) { + _clazz.setStaticByteField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jchar) { + _clazz.setStaticCharField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jshort) { + _clazz.setStaticShortField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jint) { + _clazz.setStaticIntField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jlong) { + _clazz.setStaticLongField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jfloat) { + _clazz.setStaticFloatField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jdouble) { + _clazz.setStaticDoubleField(field.fieldId, value); + } else { + _clazz.setStaticObjectField(field.fieldId, _dartObjectToJava(value, field.type)); + } + + return null; + } + + throw new JavaError('Unable to access ${invocation.memberName}'); + } +} + +/// A wrapper for a JNI object that provides access to the object's fields +/// and methods. +class JavaObject { + JniObject _object; + JavaClass _clazz; + + JavaObject(JniObject object) { + _object = object; + + _clazz = Java.wrapClassObject( + _object.callObjectMethod(_reflect.objectGetClass, [])); + } + + dynamic noSuchMethod(Invocation invocation) { + if (invocation.isMethod) { + List<_JavaMethod> overloads = _clazz._methods[invocation.memberName]; + if (overloads == null) + throw new JavaError('Method ${invocation.memberName} not found'); + + _JavaMethod method = _findMatchingMethod(overloads, invocation.positionalArguments); + List args = _convertArgumentsToJava(invocation.positionalArguments, method); + + if (method.returnType == _JavaPrimitive.jvoid) { + return _object.callVoidMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jboolean) { + return _object.callBooleanMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jbyte) { + return _object.callByteMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jchar) { + return _object.callCharMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jshort) { + return _object.callShortMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jint) { + return _object.callIntMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jlong) { + return _object.callLongMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jfloat) { + return _object.callFloatMethod(method.methodId, args); + } else if (method.returnType == _JavaPrimitive.jdouble) { + return _object.callDoubleMethod(method.methodId, args); + } else { + return _javaObjectToDart( + _object.callObjectMethod(method.methodId, args)); + } + } + + if (invocation.isGetter) { + _JavaField field = _clazz._fields[invocation.memberName]; + if (field == null) + throw new JavaError('Field ${invocation.memberName} not found'); + + if (field.type == _JavaPrimitive.jboolean) { + return _object.getBooleanField(field.fieldId); + } else if (field.type == _JavaPrimitive.jbyte) { + return _object.getByteField(field.fieldId); + } else if (field.type == _JavaPrimitive.jchar) { + return _object.getCharField(field.fieldId); + } else if (field.type == _JavaPrimitive.jshort) { + return _object.getShortField(field.fieldId); + } else if (field.type == _JavaPrimitive.jint) { + return _object.getIntField(field.fieldId); + } else if (field.type == _JavaPrimitive.jlong) { + return _object.getLongField(field.fieldId); + } else if (field.type == _JavaPrimitive.jfloat) { + return _object.getFloatField(field.fieldId); + } else if (field.type == _JavaPrimitive.jdouble) { + return _object.getDoubleField(field.fieldId); + } else { + return _javaObjectToDart(_object.getObjectField(field.fieldId)); + } + } + + if (invocation.isSetter) { + _JavaField field = _clazz._fields[invocation.memberName]; + if (field == null) + throw new JavaError('Field ${invocation.memberName} not found'); + + dynamic value = invocation.positionalArguments[0]; + + if (field.type == _JavaPrimitive.jboolean) { + _object.setBooleanField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jbyte) { + _object.setByteField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jchar) { + _object.setCharField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jshort) { + _object.setShortField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jint) { + _object.setIntField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jlong) { + _object.setLongField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jfloat) { + _object.setFloatField(field.fieldId, value); + } else if (field.type == _JavaPrimitive.jdouble) { + _object.setDoubleField(field.fieldId, value); + } else { + _object.setObjectField(field.fieldId, _dartObjectToJava(value, field.type)); + } + + return null; + } + + throw new JavaError('Unable to access ${invocation.memberName}'); + } + + /// Convert this object to a string using the Java object's `toString` method. + String toString() { + String result = JniString.unwrap(_object.callObjectMethod(_reflect.objectToString, [])); + if (!result.isEmpty) { + return result; + } else { + return 'JavaObject(${_clazz.className})'; + } + } + + /// A [JavaClass] representing this object's class. + JavaClass get javaClass => _clazz; + + /// The raw [JniObject] wrapped by this object. + /// This can be used to perform low-level JNI operations that aren't exposed + /// by [JavaObject], such as access to specific overloaded methods. + JniObject get jniObject => _object; +} diff --git a/engine/src/flutter/lib/jni/jni_object.cc b/engine/src/flutter/lib/jni/jni_object.cc new file mode 100644 index 0000000000..fcce672c7c --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_object.cc @@ -0,0 +1,631 @@ +// Copyright 2016 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 "flutter/lib/jni/jni_object.h" + +#include "base/strings/string_util.h" +#include "flutter/lib/jni/dart_jni.h" +#include "flutter/lib/jni/jni_array.h" +#include "flutter/lib/jni/jni_class.h" +#include "flutter/lib/jni/jni_string.h" + +namespace blink { + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniObject); + +JniObject::JniObject(JNIEnv* env, jobject object) : object_(env, object) {} + +JniObject::~JniObject() {} + +ftl::RefPtr JniObject::Create(JNIEnv* env, jobject object) { + if (object == nullptr) + return nullptr; + + std::string class_name = DartJni::GetObjectClassName(env, object); + + ftl::RefPtr result; + + if (class_name == "java.lang.String") { + result = ftl::MakeRefCounted(env, static_cast(object)); + } else if (class_name == "java.lang.Class") { + result = ftl::MakeRefCounted(env, static_cast(object)); + } else if (base::StartsWith(class_name, "[L", base::CompareCase::SENSITIVE)) { + result = ftl::MakeRefCounted( + env, static_cast(object)); + } else if (class_name == "[Z") { + result = ftl::MakeRefCounted( + env, static_cast(object)); + } else if (class_name == "[B") { + result = + ftl::MakeRefCounted(env, static_cast(object)); + } else if (class_name == "[C") { + result = + ftl::MakeRefCounted(env, static_cast(object)); + } else if (class_name == "[S") { + result = ftl::MakeRefCounted( + env, static_cast(object)); + } else if (class_name == "[I") { + result = + ftl::MakeRefCounted(env, static_cast(object)); + } else if (class_name == "[J") { + result = + ftl::MakeRefCounted(env, static_cast(object)); + } else if (class_name == "[F") { + result = ftl::MakeRefCounted( + env, static_cast(object)); + } else if (class_name == "[D") { + result = ftl::MakeRefCounted( + env, static_cast(object)); + } else { + result = ftl::MakeRefCounted(env, object); + } + + return result; +} + +ftl::RefPtr JniObject::GetObjectClass() { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jclass clazz = env->GetObjectClass(java_object()); + if (CheckJniException(env, &exception)) + goto fail; + + return ftl::MakeRefCounted(env, clazz); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +ftl::RefPtr JniObject::GetObjectField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jobject obj = env->GetObjectField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return JniObject::Create(env, obj); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +bool JniObject::GetBooleanField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jboolean result = env->GetBooleanField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result == JNI_TRUE; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +int64_t JniObject::GetByteField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jbyte result = env->GetByteField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::GetCharField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jchar result = env->GetCharField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::GetShortField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jshort result = env->GetShortField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::GetIntField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jint result = env->GetIntField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::GetLongField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jlong result = env->GetLongField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniObject::GetFloatField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfloat result = env->GetFloatField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniObject::GetDoubleField(jfieldID fieldId) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jfloat result = env->GetDoubleField(java_object(), fieldId); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +void JniObject::SetObjectField(jfieldID fieldId, const JniObject* value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetObjectField(java_object(), fieldId, + value ? value->java_object() : nullptr); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetBooleanField(jfieldID fieldId, bool value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetBooleanField(java_object(), fieldId, value ? JNI_TRUE : JNI_FALSE); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetByteField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetByteField(java_object(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetCharField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetCharField(java_object(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetShortField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetShortField(java_object(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetIntField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetIntField(java_object(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetLongField(jfieldID fieldId, int64_t value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetLongField(java_object(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetFloatField(jfieldID fieldId, double value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetFloatField(java_object(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +void JniObject::SetDoubleField(jfieldID fieldId, double value) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + env->SetDoubleField(java_object(), fieldId, value); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +ftl::RefPtr JniObject::CallObjectMethod( + jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jobject obj = + env->CallObjectMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return JniObject::Create(env, obj); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +bool JniObject::CallBooleanMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jboolean result = + env->CallBooleanMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result == JNI_TRUE; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return false; +} + +int64_t JniObject::CallByteMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jbyte result = + env->CallByteMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::CallCharMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jchar result = + env->CallCharMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::CallShortMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jshort result = + env->CallShortMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::CallIntMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jint result = + env->CallIntMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +int64_t JniObject::CallLongMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jlong result = + env->CallLongMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniObject::CallFloatMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jfloat result = + env->CallFloatMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +double JniObject::CallDoubleMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + jdouble result = + env->CallDoubleMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return 0; +} + +void JniObject::CallVoidMethod(jmethodID methodId, + const std::vector& args) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + JniMethodArgs java_args; + java_args.Convert(env, args, &exception); + if (exception) + goto fail; + + env->CallVoidMethodA(java_object(), methodId, java_args.jvalues()); + if (CheckJniException(env, &exception)) + goto fail; + + return; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/jni/jni_object.h b/engine/src/flutter/lib/jni/jni_object.h new file mode 100644 index 0000000000..11ea100619 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_object.h @@ -0,0 +1,80 @@ +// Copyright 2016 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 FLUTTER_LIB_JNI_JNI_OBJECT_H_ +#define FLUTTER_LIB_JNI_JNI_OBJECT_H_ + +#include + +#include "base/android/jni_android.h" +#include "lib/tonic/dart_wrappable.h" + +namespace blink { + +class JniClass; + +// Wrapper that exposes a JNI jobject to Dart +class JniObject : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(JniObject); + + public: + ~JniObject() override; + + static ftl::RefPtr Create(JNIEnv* env, jobject object); + + jobject java_object() const { return object_.obj(); } + + ftl::RefPtr GetObjectClass(); + + ftl::RefPtr GetObjectField(jfieldID fieldId); + bool GetBooleanField(jfieldID fieldId); + int64_t GetByteField(jfieldID fieldId); + int64_t GetCharField(jfieldID fieldId); + int64_t GetShortField(jfieldID fieldId); + int64_t GetIntField(jfieldID fieldId); + int64_t GetLongField(jfieldID fieldId); + double GetFloatField(jfieldID fieldId); + double GetDoubleField(jfieldID fieldId); + + void SetObjectField(jfieldID fieldId, const JniObject* value); + void SetBooleanField(jfieldID fieldId, bool value); + void SetByteField(jfieldID fieldId, int64_t value); + void SetCharField(jfieldID fieldId, int64_t value); + void SetShortField(jfieldID fieldId, int64_t value); + void SetIntField(jfieldID fieldId, int64_t value); + void SetLongField(jfieldID fieldId, int64_t value); + void SetFloatField(jfieldID fieldId, double value); + void SetDoubleField(jfieldID fieldId, double value); + + ftl::RefPtr CallObjectMethod(jmethodID methodId, + const std::vector& args); + bool CallBooleanMethod(jmethodID methodId, + const std::vector& args); + int64_t CallByteMethod(jmethodID methodId, + const std::vector& args); + int64_t CallCharMethod(jmethodID methodId, + const std::vector& args); + int64_t CallShortMethod(jmethodID methodId, + const std::vector& args); + int64_t CallIntMethod(jmethodID methodId, + const std::vector& args); + int64_t CallLongMethod(jmethodID methodId, + const std::vector& args); + double CallFloatMethod(jmethodID methodId, + const std::vector& args); + double CallDoubleMethod(jmethodID methodId, + const std::vector& args); + void CallVoidMethod(jmethodID methodId, const std::vector& args); + + protected: + JniObject(JNIEnv* env, jobject object); + + base::android::ScopedJavaGlobalRef object_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_JNI_JNI_OBJECT_H_ diff --git a/engine/src/flutter/lib/jni/jni_raw.dart b/engine/src/flutter/lib/jni/jni_raw.dart new file mode 100644 index 0000000000..73ed13b556 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_raw.dart @@ -0,0 +1,326 @@ +// Copyright 2016 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. + +part of dart_jni; + +/// A group of methods which invoke Java Native Interface APIs from Dart. +class JniApi { + /// Return the field ID matching a `java.lang.reflect.Field` object. + static int fromReflectedField(JniObject field) + native 'JniApi_FromReflectedField'; + + /// Return the method ID matching a `java.lang.reflect.Method` object. + static int fromReflectedMethod(JniObject method) + native 'JniApi_FromReflectedMethod'; + + /// The `ApplicationContext` of this Android application. + static JniObject getApplicationContext() + native 'JniApi_GetApplicationContext'; + + /// The application's class loader. + static JniObject getClassLoader() + native 'JniApi_GetClassLoader'; +} + +/// Low-level wrapper for a Java object accessed via JNI. +/// These methods map directly to the corresponding JNI functions. See the JNI +/// documentation for more information. +class JniObject extends NativeFieldWrapperClass2 { + JniClass getObjectClass() + native 'JniObject_GetObjectClass'; + + JniObject getObjectField(int fieldId) + native 'JniObject_GetObjectField'; + bool getBooleanField(int fieldId) + native 'JniObject_GetBooleanField'; + int getByteField(int fieldId) + native 'JniObject_GetByteField'; + int getCharField(int fieldId) + native 'JniObject_GetCharField'; + int getShortField(int fieldId) + native 'JniObject_GetShortField'; + int getIntField(int fieldId) + native 'JniObject_GetIntField'; + int getLongField(int fieldId) + native 'JniObject_GetLongField'; + double getFloatField(int fieldId) + native 'JniObject_GetFloatField'; + double getDoubleField(int fieldId) + native 'JniObject_GetDoubleField'; + + void setObjectField(int fieldId, JniObject value) + native 'JniObject_SetObjectField'; + void setBooleanField(int fieldId, bool value) + native 'JniObject_SetBooleanField'; + void setByteField(int fieldId, int value) + native 'JniObject_SetByteField'; + void setCharField(int fieldId, int value) + native 'JniObject_SetCharField'; + void setShortField(int fieldId, int value) + native 'JniObject_SetShortField'; + void setIntField(int fieldId, int value) + native 'JniObject_SetIntField'; + void setLongField(int fieldId, int value) + native 'JniObject_SetLongField'; + void setFloatField(int fieldId, double value) + native 'JniObject_SetFloatField'; + void setDoubleField(int fieldId, double value) + native 'JniObject_SetDoubleField'; + + JniObject callObjectMethod(int methodId, List args) + native 'JniObject_CallObjectMethod'; + bool callBooleanMethod(int methodId, List args) + native 'JniObject_CallBooleanMethod'; + int callByteMethod(int methodId, List args) + native 'JniObject_CallByteMethod'; + int callCharMethod(int methodId, List args) + native 'JniObject_CallCharMethod'; + int callShortMethod(int methodId, List args) + native 'JniObject_CallShortMethod'; + int callIntMethod(int methodId, List args) + native 'JniObject_CallIntMethod'; + int callLongMethod(int methodId, List args) + native 'JniObject_CallLongMethod'; + double callFloatMethod(int methodId, List args) + native 'JniObject_CallFloatMethod'; + double callDoubleMethod(int methodId, List args) + native 'JniObject_CallDoubleMethod'; + void callVoidMethod(int methodId, List args) + native 'JniObject_CallVoidMethod'; +} + +/// Low-level wrapper for a Java class accessed via JNI. +/// These methods map directly to the corresponding JNI functions. See the JNI +/// documentation for more information. +class JniClass extends JniObject { + /// Loads the Java class with the given fully qualified name. + static JniClass fromName(String name) + native 'JniClass_FromName'; + + /// Returns a wrapper for a `java.lang.Class` object. + static JniClass fromClassObject(JniObject classObject) + native 'JniClass_FromClassObject'; + + /// Returns a field ID for the instance field matching this name and type signature. + /// See the JNI reference for explanation of type signatures. + int getFieldId(String name, String sig) + native 'JniClass_GetFieldId'; + + /// Returns a field ID for a static field. + int getStaticFieldId(String name, String sig) + native 'JniClass_GetStaticFieldId'; + + /// Returns a method ID for an instance method. + int getMethodId(String name, String sig) + native 'JniClass_GetMethodId'; + + /// Returns a method ID for a static method. + int getStaticMethodId(String name, String sig) + native 'JniClass_GetStaticMethodId'; + + /// Constructs an instance of the wrapped Java class.. + /// @param methodId The method ID of the constructor, obtained via getMethodId. + /// @param args A list of argument values passed to the constructor. Each value should + /// be a Dart number, bool, string, or [JniObject] instance. + JniObject newObject(int methodId, List args) + native 'JniClass_NewObject'; + + /// Returns true if objects of the wrapped Java class can be cast to the + /// class described by the argument. + bool isAssignable(JniClass clazz) + native 'JniClass_IsAssignable'; + + JniObject getStaticObjectField(int fieldId) + native 'JniClass_GetStaticObjectField'; + bool getStaticBooleanField(int fieldId) + native 'JniClass_GetStaticBooleanField'; + int getStaticByteField(int fieldId) + native 'JniClass_GetStaticByteField'; + int getStaticCharField(int fieldId) + native 'JniClass_GetStaticCharField'; + int getStaticShortField(int fieldId) + native 'JniClass_GetStaticShortField'; + int getStaticIntField(int fieldId) + native 'JniClass_GetStaticIntField'; + int getStaticLongField(int fieldId) + native 'JniClass_GetStaticLongField'; + double getStaticFloatField(int fieldId) + native 'JniClass_GetStaticFloatField'; + double getStaticDoubleField(int fieldId) + native 'JniClass_GetStaticDoubleField'; + + void setStaticObjectField(int fieldId, JniObject value) + native 'JniClass_SetStaticObjectField'; + void setStaticBooleanField(int fieldId, bool value) + native 'JniClass_SetStaticBooleanField'; + void setStaticByteField(int fieldId, int value) + native 'JniClass_SetStaticByteField'; + void setStaticCharField(int fieldId, int value) + native 'JniClass_SetStaticCharField'; + void setStaticShortField(int fieldId, int value) + native 'JniClass_SetStaticShortField'; + void setStaticIntField(int fieldId, int value) + native 'JniClass_SetStaticIntField'; + void setStaticLongField(int fieldId, int value) + native 'JniClass_SetStaticLongField'; + void setStaticFloatField(int fieldId, double value) + native 'JniClass_SetStaticFloatField'; + void setStaticDoubleField(int fieldId, double value) + native 'JniClass_SetStaticDoubleField'; + + JniObject callStaticObjectMethod(int methodId, List args) + native 'JniClass_CallStaticObjectMethod'; + bool callStaticBooleanMethod(int methodId, List args) + native 'JniClass_CallStaticBooleanMethod'; + int callStaticByteMethod(int methodId, List args) + native 'JniClass_CallStaticByteMethod'; + int callStaticCharMethod(int methodId, List args) + native 'JniClass_CallStaticCharMethod'; + int callStaticShortMethod(int methodId, List args) + native 'JniClass_CallStaticShortMethod'; + int callStaticIntMethod(int methodId, List args) + native 'JniClass_CallStaticIntMethod'; + int callStaticLongMethod(int methodId, List args) + native 'JniClass_CallStaticLongMethod'; + double callStaticFloatMethod(int methodId, List args) + native 'JniClass_CallStaticFloatMethod'; + double callStaticDoubleMethod(int methodId, List args) + native 'JniClass_CallStaticDoubleMethod'; + void callStaticVoidMethod(int methodId, List args) + native 'JniClass_CallStaticVoidMethod'; +} + +/// Wrapper for a Java string. +class JniString extends JniObject { + /// Construct a Java string from a Dart string. + static JniString create(String value) + native 'JniString_Create'; + + /// Retrieve the value of the Java string represented by this object as a Dart string. + String get text native 'JniString_GetText'; + + /// Convert a JniObject representing a Java string to a Dart string. + static String unwrap(JniObject object) => (object as JniString).text; +} + +/// Wrapper for a Java array. +class JniArray extends JniObject { + int get length native 'JniArray_GetLength'; + + void set length(int value) { throw new UnsupportedError("Not supported."); } +} + +/// Wrapper for a Java `Object` array. +class JniObjectArray extends JniArray with ListMixin { + static JniObjectArray create(JniClass clazz, int length) + native 'JniObjectArray_Create'; + + JniObject operator [](int index) + native 'JniObjectArray_GetArrayElement'; + + void operator []=(int index, JniObject value) + native 'JniObjectArray_SetArrayElement'; +} + +/// Wrapper for a Java `boolean` array. +class JniBooleanArray extends JniArray with ListMixin { + static JniBooleanArray create(int length) + native 'JniBooleanArray_Create'; + + bool operator [](int index) + native 'JniBooleanArray_GetArrayElement'; + + void operator []=(int index, bool value) + native 'JniBooleanArray_SetArrayElement'; +} + +/// Wrapper for a Java `byte` array. +class JniByteArray extends JniArray with ListMixin { + static JniByteArray create(int length) + native 'JniByteArray_Create'; + + int operator [](int index) + native 'JniByteArray_GetArrayElement'; + + void operator []=(int index, int value) + native 'JniByteArray_SetArrayElement'; +} + +/// Wrapper for a Java `char` array. +class JniCharArray extends JniArray with ListMixin { + static JniCharArray create(int length) + native 'JniCharArray_Create'; + + int operator [](int index) + native 'JniCharArray_GetArrayElement'; + + void operator []=(int index, int value) + native 'JniCharArray_SetArrayElement'; +} + +/// Wrapper for a Java `short` array. +class JniShortArray extends JniArray with ListMixin { + static JniShortArray create(int length) + native 'JniShortArray_Create'; + + int operator [](int index) + native 'JniShortArray_GetArrayElement'; + + void operator []=(int index, int value) + native 'JniShortArray_SetArrayElement'; +} + +/// Wrapper for a Java `int` array. +class JniIntArray extends JniArray with ListMixin { + static JniIntArray create(int length) + native 'JniIntArray_Create'; + + int operator [](int index) + native 'JniIntArray_GetArrayElement'; + + void operator []=(int index, int value) + native 'JniIntArray_SetArrayElement'; +} + +/// Wrapper for a Java `long` array. +class JniLongArray extends JniArray with ListMixin { + static JniLongArray create(int length) + native 'JniLongArray_Create'; + + int operator [](int index) + native 'JniLongArray_GetArrayElement'; + + void operator []=(int index, int value) + native 'JniLongArray_SetArrayElement'; +} + +/// Wrapper for a Java `float` array. +class JniFloatArray extends JniArray with ListMixin { + static JniFloatArray create(int length) + native 'JniFloatArray_Create'; + + double operator [](int index) + native 'JniFloatArray_GetArrayElement'; + + void operator []=(int index, double value) + native 'JniFloatArray_SetArrayElement'; +} + +/// Wrapper for a Java `double` array. +class JniDoubleArray extends JniArray with ListMixin { + static JniDoubleArray create(int length) + native 'JniDoubleArray_Create'; + + double operator [](int index) + native 'JniDoubleArray_GetArrayElement'; + + void operator []=(int index, double value) + native 'JniDoubleArray_SetArrayElement'; +} + +/// Used to pass arguments of type "float" to Java methods. +class JniFloat { + final double value; + JniFloat(this.value); +} diff --git a/engine/src/flutter/lib/jni/jni_string.cc b/engine/src/flutter/lib/jni/jni_string.cc new file mode 100644 index 0000000000..a12d72dd24 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_string.cc @@ -0,0 +1,61 @@ +// Copyright 2016 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 "flutter/lib/jni/jni_string.h" + +namespace blink { + +IMPLEMENT_WRAPPERTYPEINFO(jni, JniString); + +JniString::JniString(JNIEnv* env, jstring object) : JniObject(env, object) {} + +JniString::~JniString() {} + +jstring JniString::java_string() { + return static_cast(java_object()); +} + +ftl::RefPtr JniString::Create(Dart_Handle dart_string) { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jstring java_string = + DartJni::DartToJavaString(env, dart_string, &exception); + if (exception) + goto fail; + + return ftl::MakeRefCounted(env, java_string); + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return nullptr; +} + +Dart_Handle JniString::GetText() { + Dart_Handle exception = nullptr; + { + ENTER_JNI(); + + jsize length = env->GetStringLength(java_string()); + if (CheckJniException(env, &exception)) + goto fail; + + const jchar* chars = env->GetStringChars(java_string(), NULL); + if (CheckJniException(env, &exception)) + goto fail; + + Dart_Handle result = Dart_NewStringFromUTF16(chars, length); + env->ReleaseStringChars(java_string(), chars); + + return result; + } +fail: + Dart_ThrowException(exception); + FTL_NOTREACHED(); + return Dart_Null(); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/jni/jni_string.h b/engine/src/flutter/lib/jni/jni_string.h new file mode 100644 index 0000000000..9c82985720 --- /dev/null +++ b/engine/src/flutter/lib/jni/jni_string.h @@ -0,0 +1,33 @@ +// Copyright 2016 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 FLUTTER_LIB_JNI_JNI_STRING_H_ +#define FLUTTER_LIB_JNI_JNI_STRING_H_ + +#include "flutter/lib/jni/dart_jni.h" +#include "flutter/lib/jni/jni_object.h" + +namespace blink { + +// Wrapper for a JNI string +class JniString : public JniObject { + DEFINE_WRAPPERTYPEINFO(); + friend class JniObject; + FRIEND_MAKE_REF_COUNTED(JniString); + + public: + ~JniString() override; + + static ftl::RefPtr Create(Dart_Handle dart_string); + Dart_Handle GetText(); + + private: + JniString(JNIEnv* env, jstring string); + + jstring java_string(); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_JNI_JNI_STRING_H_ diff --git a/engine/src/flutter/lib/ui/BUILD.gn b/engine/src/flutter/lib/ui/BUILD.gn new file mode 100644 index 0000000000..d9db1a4c2c --- /dev/null +++ b/engine/src/flutter/lib/ui/BUILD.gn @@ -0,0 +1,55 @@ +# Copyright 2016 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("ui") { + sources = [ + "compositing/scene_builder.cc", + "compositing/scene_builder.h", + "compositing/scene.cc", + "compositing/scene.h", + "painting/canvas.cc", + "painting/canvas.h", + "painting/gradient.cc", + "painting/gradient.h", + "painting/image.cc", + "painting/image_decoding.cc", + "painting/image_decoding.h", + "painting/image_filter.cc", + "painting/image_filter.h", + "painting/image.h", + "painting/image_shader.cc", + "painting/image_shader.h", + "painting/mask_filter.cc", + "painting/mask_filter.h", + "painting/matrix.cc", + "painting/matrix.h", + "painting/paint.cc", + "painting/paint.h", + "painting/path.cc", + "painting/path.h", + "painting/picture_recorder.cc", + "painting/picture_recorder.h", + "painting/picture.cc", + "painting/picture.h", + "painting/resource_context.cc", + "painting/resource_context.h", + "painting/rrect.cc", + "painting/rrect.h", + "painting/shader.cc", + "painting/shader.h", + ] + + deps = [ + "//base", + "//flutter/flow", + "//flutter/tonic", + "//flutter/glue", + "//lib/tonic", + "//flutter/skia", + + # For image_decoding: + "//flutter/sky/engine/platform", + "//flutter/sky/engine/wtf", + ] +} diff --git a/engine/src/flutter/lib/ui/compositing.dart b/engine/src/flutter/lib/ui/compositing.dart new file mode 100644 index 0000000000..535ed7f65d --- /dev/null +++ b/engine/src/flutter/lib/ui/compositing.dart @@ -0,0 +1,230 @@ +// 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. + +part of dart_ui; + +/// An opaque object representing a composited scene. +/// +/// To create a Scene object, use a [SceneBuilder]. +/// +/// Scene objects can be displayed on the screen using the +/// [Window.render] method. +class Scene extends NativeFieldWrapperClass2 { + /// Creates an uninitialized Scene object. + /// + /// Calling the Scene constructor directly will not create a useable + /// object. To create a Scene object, use a [SceneBuilder]. + Scene(); // (this constructor is here just so we can document it) + + /// Releases the resources used by this scene. + /// + /// After calling this function, the scene is cannot be used further. + void dispose() native "Scene_dispose"; +} + +/// Builds a [Scene] containing the given visuals. +/// +/// A [Scene] can then be rendered using [Window.render]. +/// +/// To draw graphical operations onto a [Scene], first create a +/// [Picture] using a [PictureRecorder] and a [Canvas], and then add +/// it to the scene using [addPicture]. +class SceneBuilder extends NativeFieldWrapperClass2 { + /// Creates an empty [SceneBuilder] object. + SceneBuilder() { _constructor(); } + void _constructor() native "SceneBuilder_constructor"; + + /// Pushes a transform operation onto the operation stack. + /// + /// The objects are transformed by the given matrix before rasterization. + /// + /// See [pop] for details about the operation stack. + void pushTransform(Float64List matrix4) { + if (matrix4 == null) + throw new ArgumentError("[matrix4] argument cannot be null"); + if (matrix4.length != 16) + throw new ArgumentError("[matrix4] must have 16 entries."); + _pushTransform(matrix4); + } + void _pushTransform(Float64List matrix4) native "SceneBuilder_pushTransform"; + + /// Pushes a rectangular clip operation onto the operation stack. + /// + /// Rasterization outside the given rectangle is discarded. + /// + /// See [pop] for details about the operation stack. + void pushClipRect(Rect rect) { + _pushClipRect(rect.left, rect.right, rect.top, rect.bottom); + } + void _pushClipRect(double left, + double right, + double top, + double bottom) native "SceneBuilder_pushClipRect"; + + /// Pushes a rounded-rectangular clip operation onto the operation stack. + /// + /// Rasterization outside the given rounded rectangle is discarded. + /// + /// See [pop] for details about the operation stack. + void pushClipRRect(RRect rrect) => _pushClipRRect(rrect._value); + void _pushClipRRect(Float32List rrect) native "SceneBuilder_pushClipRRect"; + + /// Pushes a path clip operation onto the operation stack. + /// + /// Rasterization outside the given path is discarded. + /// + /// See [pop] for details about the operation stack. + void pushClipPath(Path path) native "SceneBuilder_pushClipPath"; + + /// Pushes an opacity operation onto the operation stack. + /// + /// The given alpha value is blended into the alpha value of the objects' + /// rasterization. An alpha value of 0 makes the objects entirely invisible. + /// An alpha value of 255 has no effect (i.e., the objects retain the current + /// opacity). + /// + /// See [pop] for details about the operation stack. + void pushOpacity(int alpha) native "SceneBuilder_pushOpacity"; + + /// Pushes a color filter operation onto the operation stack. + /// + /// The given color is applied to the objects' rasterization using the given + /// transfer mode. + /// + /// See [pop] for details about the operation stack. + void pushColorFilter(Color color, TransferMode transferMode) { + _pushColorFilter(color.value, transferMode.index); + } + void _pushColorFilter(int color, int transferMode) native "SceneBuilder_pushColorFilter"; + + /// Pushes a backdrop filter operation onto the operation stack. + /// + /// The given filter is applied to the current contents of the scene prior to + /// rasterizing the given objects. + /// + /// See [pop] for details about the operation stack. + void pushBackdropFilter(ImageFilter filter) native "SceneBuilder_pushBackdropFilter"; + + /// Pushes a shader mask operation onto the operation stack. + /// + /// The given shader is applied to the object's rasterization in the given + /// rectangle using the given transfer mode. + /// + /// See [pop] for details about the operation stack. + void pushShaderMask(Shader shader, Rect maskRect, TransferMode transferMode) { + _pushShaderMask(shader, + maskRect.left, + maskRect.right, + maskRect.top, + maskRect.bottom, + transferMode.index); + } + void _pushShaderMask(Shader shader, + double maskRectLeft, + double maskRectRight, + double maskRectTop, + double maskRectBottom, + int transferMode) native "SceneBuilder_pushShaderMask"; + + /// Ends the effect of the most recently pushed operation. + /// + /// Internally the scene builder maintains a stack of operations. Each of the + /// operations in the stack applies to each of the objects added to the scene. + /// Calling this function removes the most recently added operation from the + /// stack. + void pop() native "SceneBuilder_pop"; + + /// Adds an object to the scene that displays performance statistics. + /// + /// Useful during development to assess the performance of the application. + /// The enabledOptions controls which statistics are displayed. The bounds + /// controls where the statistics are displayed. + /// + /// enabledOptions is a bit field with the following bits defined: + /// - 0x01: displayRasterizerStatistics - show GPU thread frame time + /// - 0x02: visualizeRasterizerStatistics - graph GPU thread frame times + /// - 0x04: displayEngineStatistics - show UI thread frame time + /// - 0x08: visualizeEngineStatistics - graph UI thread frame times + /// Set enabledOptions to 0x0F to enable all the currently defined features. + /// + /// The "UI thread" is the thread that includes all the execution of + /// the main Dart isolate (the isolate that can call + /// [Window.render]). The UI thread frame time is the total time + /// spent executing the [Window.onBeginFrame] callback. The "GPU + /// thread" is the thread (running on the CPU) that subsequently + /// processes the [Scene] provided by the Dart code to turn it into + /// GPU commands and send it to the GPU. + /// + /// See also the [PerformanceOverlayOption] enum in the rendering library. + /// for more details. + // Values above must match constants in //engine/src/sky/compositor/performance_overlay_layer.h + void addPerformanceOverlay(int enabledOptions, Rect bounds) { + _addPerformanceOverlay(enabledOptions, + bounds.left, + bounds.right, + bounds.top, + bounds.bottom); + } + void _addPerformanceOverlay(int enabledOptions, + double left, + double right, + double top, + double bottom) native "SceneBuilder_addPerformanceOverlay"; + + /// Adds a [Picture] to the scene. + /// + /// The picture is rasterized at the given offset. + void addPicture(Offset offset, Picture picture, { bool isComplexHint: false, bool willChangeHint: false }) { + int hints = 0; + if (isComplexHint) + hints |= 1; + if (willChangeHint) + hints |= 2; + _addPicture(offset.dx, offset.dy, picture, hints); + } + void _addPicture(double dx, double dy, Picture picture, int hints) native "SceneBuilder_addPicture"; + + /// (mojo-only) Adds a scene rendered by another application to the scene for + /// this application. + /// + /// Applications typically obtain scene tokens when embedding other views via + /// the Mojo view manager, but this function is agnostic as to the source of + /// scene token. + void addChildScene(Offset offset, + double devicePixelRatio, + int physicalWidth, + int physicalHeight, + int sceneToken) { + _addChildScene(offset.dx, + offset.dy, + devicePixelRatio, + physicalWidth, + physicalHeight, + sceneToken); + } + void _addChildScene(double dx, + double dy, + double devicePixelRatio, + int physicalWidth, + int physicalHeight, + int sceneToken) native "SceneBuilder_addChildScene"; + + /// Sets a threshold after which additional debugging information should be recorded. + /// + /// Currently this interface is difficult to use by end-developers. If you're + /// interested in using this feature, please contact [flutter-dev](https://groups.google.com/forum/#!forum/flutter-dev). + /// We'll hopefully be able to figure out how to make this feature more useful + /// to you. + void setRasterizerTracingThreshold(int frameInterval) native "SceneBuilder_setRasterizerTracingThreshold"; + + /// Finishes building the scene. + /// + /// Returns a [Scene] containing the objects that have been added to + /// this scene builder. The [Scene] can then be displayed on the + /// screen with [Window.render]. + /// + /// After calling this function, the scene builder object is invalid and + /// cannot be used further. + Scene build() native "SceneBuilder_build"; +} diff --git a/engine/src/flutter/lib/ui/compositing/scene.cc b/engine/src/flutter/lib/ui/compositing/scene.cc new file mode 100644 index 0000000000..ab80b073cc --- /dev/null +++ b/engine/src/flutter/lib/ui/compositing/scene.cc @@ -0,0 +1,45 @@ +// 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 "flutter/lib/ui/compositing/scene.h" + +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" + +namespace blink { + +IMPLEMENT_WRAPPERTYPEINFO(ui, Scene); + +#define FOR_EACH_BINDING(V) V(Scene, dispose) + +DART_BIND_ALL(Scene, FOR_EACH_BINDING) + +ftl::RefPtr Scene::create(std::unique_ptr rootLayer, + uint32_t rasterizerTracingThreshold) { + return ftl::MakeRefCounted(std::move(rootLayer), + rasterizerTracingThreshold); +} + +Scene::Scene(std::unique_ptr rootLayer, + uint32_t rasterizerTracingThreshold) + : m_layerTree(new flow::LayerTree()) { + m_layerTree->set_root_layer(std::move(rootLayer)); + m_layerTree->set_rasterizer_tracing_threshold(rasterizerTracingThreshold); +} + +Scene::~Scene() {} + +void Scene::dispose() { + ClearDartWrapper(); +} + +std::unique_ptr Scene::takeLayerTree() { + return std::move(m_layerTree); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/compositing/scene.h b/engine/src/flutter/lib/ui/compositing/scene.h new file mode 100644 index 0000000000..a9c7eaf9a0 --- /dev/null +++ b/engine/src/flutter/lib/ui/compositing/scene.h @@ -0,0 +1,46 @@ +// 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 FLUTTER_LIB_UI_COMPOSITING_SCENE_H_ +#define FLUTTER_LIB_UI_COMPOSITING_SCENE_H_ + +#include +#include + +#include "flutter/flow/layers/layer_tree.h" +#include "lib/tonic/dart_wrappable.h" +#include "third_party/skia/include/core/SkPicture.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class Scene : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(Scene); + + public: + ~Scene() override; + static ftl::RefPtr create(std::unique_ptr rootLayer, + uint32_t rasterizerTracingThreshold); + + std::unique_ptr takeLayerTree(); + + void dispose(); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit Scene(std::unique_ptr rootLayer, + uint32_t rasterizerTracingThreshold); + + std::unique_ptr m_layerTree; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_COMPOSITING_SCENE_H_ diff --git a/engine/src/flutter/lib/ui/compositing/scene_builder.cc b/engine/src/flutter/lib/ui/compositing/scene_builder.cc new file mode 100644 index 0000000000..2fc6c5b222 --- /dev/null +++ b/engine/src/flutter/lib/ui/compositing/scene_builder.cc @@ -0,0 +1,206 @@ +// 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 "flutter/lib/ui/compositing/scene_builder.h" + +#include "flutter/flow/layers/backdrop_filter_layer.h" +#include "flutter/flow/layers/child_scene_layer.h" +#include "flutter/flow/layers/clip_path_layer.h" +#include "flutter/flow/layers/clip_rect_layer.h" +#include "flutter/flow/layers/clip_rrect_layer.h" +#include "flutter/flow/layers/color_filter_layer.h" +#include "flutter/flow/layers/container_layer.h" +#include "flutter/flow/layers/opacity_layer.h" +#include "flutter/flow/layers/performance_overlay_layer.h" +#include "flutter/flow/layers/picture_layer.h" +#include "flutter/flow/layers/shader_mask_layer.h" +#include "flutter/flow/layers/transform_layer.h" +#include "flutter/lib/ui/painting/matrix.h" +#include "flutter/lib/ui/painting/shader.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "third_party/skia/include/core/SkColorFilter.h" + +namespace blink { + +static void SceneBuilder_constructor(Dart_NativeArguments args) { + DartCallConstructor(&SceneBuilder::create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, SceneBuilder); + +#define FOR_EACH_BINDING(V) \ + V(SceneBuilder, pushTransform) \ + V(SceneBuilder, pushClipRect) \ + V(SceneBuilder, pushClipRRect) \ + V(SceneBuilder, pushClipPath) \ + V(SceneBuilder, pushOpacity) \ + V(SceneBuilder, pushColorFilter) \ + V(SceneBuilder, pushBackdropFilter) \ + V(SceneBuilder, pushShaderMask) \ + V(SceneBuilder, pop) \ + V(SceneBuilder, addPicture) \ + V(SceneBuilder, addChildScene) \ + V(SceneBuilder, addPerformanceOverlay) \ + V(SceneBuilder, setRasterizerTracingThreshold) \ + V(SceneBuilder, build) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void SceneBuilder::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register( + {{"SceneBuilder_constructor", SceneBuilder_constructor, 1, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +SceneBuilder::SceneBuilder() + : m_currentLayer(nullptr), m_currentRasterizerTracingThreshold(0) {} + +SceneBuilder::~SceneBuilder() {} + +void SceneBuilder::pushTransform(const tonic::Float64List& matrix4) { + SkMatrix sk_matrix = ToSkMatrix(matrix4); + std::unique_ptr layer(new flow::TransformLayer()); + layer->set_transform(sk_matrix); + addLayer(std::move(layer)); +} + +void SceneBuilder::pushClipRect(double left, + double right, + double top, + double bottom) { + std::unique_ptr layer(new flow::ClipRectLayer()); + layer->set_clip_rect(SkRect::MakeLTRB(left, top, right, bottom)); + addLayer(std::move(layer)); +} + +void SceneBuilder::pushClipRRect(const RRect& rrect) { + std::unique_ptr layer(new flow::ClipRRectLayer()); + layer->set_clip_rrect(rrect.sk_rrect); + addLayer(std::move(layer)); +} + +void SceneBuilder::pushClipPath(const CanvasPath* path) { + std::unique_ptr layer(new flow::ClipPathLayer()); + layer->set_clip_path(path->path()); + addLayer(std::move(layer)); +} + +void SceneBuilder::pushOpacity(int alpha) { + std::unique_ptr layer(new flow::OpacityLayer()); + layer->set_alpha(alpha); + addLayer(std::move(layer)); +} + +void SceneBuilder::pushColorFilter(int color, int transferMode) { + std::unique_ptr layer(new flow::ColorFilterLayer()); + layer->set_color(static_cast(color)); + layer->set_transfer_mode(static_cast(transferMode)); + addLayer(std::move(layer)); +} + +void SceneBuilder::pushBackdropFilter(ImageFilter* filter) { + std::unique_ptr layer( + new flow::BackdropFilterLayer()); + layer->set_filter(filter->filter()); + addLayer(std::move(layer)); +} + +void SceneBuilder::pushShaderMask(Shader* shader, + double maskRectLeft, + double maskRectRight, + double maskRectTop, + double maskRectBottom, + int transferMode) { + std::unique_ptr layer(new flow::ShaderMaskLayer()); + layer->set_shader(shader->shader()); + layer->set_mask_rect(SkRect::MakeLTRB(maskRectLeft, maskRectTop, + maskRectRight, maskRectBottom)); + layer->set_transfer_mode(static_cast(transferMode)); + addLayer(std::move(layer)); +} + +void SceneBuilder::addLayer(std::unique_ptr layer) { + DCHECK(layer); + if (!m_rootLayer) { + DCHECK(!m_currentLayer); + m_rootLayer = std::move(layer); + m_currentLayer = m_rootLayer.get(); + return; + } + if (!m_currentLayer) + return; + flow::ContainerLayer* newLayer = layer.get(); + m_currentLayer->Add(std::move(layer)); + m_currentLayer = newLayer; +} + +void SceneBuilder::pop() { + if (!m_currentLayer) + return; + m_currentLayer = m_currentLayer->parent(); +} + +void SceneBuilder::addPicture(double dx, + double dy, + Picture* picture, + int hints) { + if (!m_currentLayer) + return; + std::unique_ptr layer(new flow::PictureLayer()); + layer->set_offset(SkPoint::Make(dx, dy)); + layer->set_picture(picture->picture()); + layer->set_is_complex(!!(hints & 1)); + layer->set_will_change(!!(hints & 2)); + m_currentLayer->Add(std::move(layer)); +} + +void SceneBuilder::addChildScene(double dx, + double dy, + double devicePixelRatio, + int physicalWidth, + int physicalHeight, + uint32_t sceneToken) { + if (!m_currentLayer) + return; + std::unique_ptr layer(new flow::ChildSceneLayer()); + layer->set_offset(SkPoint::Make(dx, dy)); + layer->set_device_pixel_ratio(devicePixelRatio); + layer->set_physical_size(SkISize::Make(physicalWidth, physicalHeight)); + mojo::gfx::composition::SceneTokenPtr token = + mojo::gfx::composition::SceneToken::New(); + token->value = sceneToken; + layer->set_scene_token(token.Pass()); + m_currentLayer->Add(std::move(layer)); +} + +void SceneBuilder::addPerformanceOverlay(uint64_t enabledOptions, + double left, + double right, + double top, + double bottom) { + if (!m_currentLayer) + return; + std::unique_ptr layer( + new flow::PerformanceOverlayLayer(enabledOptions)); + layer->set_paint_bounds(SkRect::MakeLTRB(left, top, right, bottom)); + m_currentLayer->Add(std::move(layer)); +} + +void SceneBuilder::setRasterizerTracingThreshold(uint32_t frameInterval) { + m_currentRasterizerTracingThreshold = frameInterval; +} + +ftl::RefPtr SceneBuilder::build() { + m_currentLayer = nullptr; + int32_t threshold = m_currentRasterizerTracingThreshold; + m_currentRasterizerTracingThreshold = 0; + ftl::RefPtr scene = Scene::create(std::move(m_rootLayer), threshold); + ClearDartWrapper(); + return scene; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/compositing/scene_builder.h b/engine/src/flutter/lib/ui/compositing/scene_builder.h new file mode 100644 index 0000000000..f352f8b1ea --- /dev/null +++ b/engine/src/flutter/lib/ui/compositing/scene_builder.h @@ -0,0 +1,82 @@ +// 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 FLUTTER_LIB_UI_COMPOSITING_SCENE_BUILDER_H_ +#define FLUTTER_LIB_UI_COMPOSITING_SCENE_BUILDER_H_ + +#include + +#include + +#include "flutter/flow/layers/container_layer.h" +#include "flutter/lib/ui/compositing/scene.h" +#include "flutter/lib/ui/painting/image_filter.h" +#include "flutter/lib/ui/painting/path.h" +#include "flutter/lib/ui/painting/picture.h" +#include "flutter/lib/ui/painting/rrect.h" +#include "flutter/lib/ui/painting/shader.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/typed_data/float64_list.h" + +namespace blink { + +class SceneBuilder : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(SceneBuilder); + + public: + static ftl::RefPtr create() { + return ftl::MakeRefCounted(); + } + + ~SceneBuilder() override; + + void pushTransform(const tonic::Float64List& matrix4); + void pushClipRect(double left, double right, double top, double bottom); + void pushClipRRect(const RRect& rrect); + void pushClipPath(const CanvasPath* path); + void pushOpacity(int alpha); + void pushColorFilter(int color, int transferMode); + void pushBackdropFilter(ImageFilter* filter); + void pushShaderMask(Shader* shader, + double maskRectLeft, + double maskRectRight, + double maskRectTop, + double maskRectBottom, + int transferMode); + void pop(); + + void addPerformanceOverlay(uint64_t enabledOptions, + double left, + double right, + double top, + double bottom); + void addPicture(double dx, double dy, Picture* picture, int hints); + void addChildScene(double dx, + double dy, + double devicePixelRatio, + int physicalWidth, + int physicalHeight, + uint32_t sceneToken); + + void setRasterizerTracingThreshold(uint32_t frameInterval); + + ftl::RefPtr build(); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit SceneBuilder(); + + void addLayer(std::unique_ptr layer); + + std::unique_ptr m_rootLayer; + flow::ContainerLayer* m_currentLayer; + int32_t m_currentRasterizerTracingThreshold; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_COMPOSITING_SCENE_BUILDER_H_ diff --git a/engine/src/flutter/lib/ui/dart_ui.gni b/engine/src/flutter/lib/ui/dart_ui.gni new file mode 100644 index 0000000000..daf350f5c9 --- /dev/null +++ b/engine/src/flutter/lib/ui/dart_ui.gni @@ -0,0 +1,12 @@ +# Copyright 2016 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. + +dart_ui_files = [ + "//flutter/lib/ui/compositing.dart", + "//flutter/lib/ui/geometry.dart", + "//flutter/lib/ui/painting.dart", + "//flutter/lib/ui/ui.dart", +] + +dart_ui_path = "//flutter/lib/ui/ui.dart" diff --git a/engine/src/flutter/lib/ui/geometry.dart b/engine/src/flutter/lib/ui/geometry.dart new file mode 100644 index 0000000000..f60b982963 --- /dev/null +++ b/engine/src/flutter/lib/ui/geometry.dart @@ -0,0 +1,1362 @@ +// 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. + +part of dart_ui; + +/// Base class for [Size] and [Offset], which are both ways to describe +/// a distance as a two-dimensional axis-aligned vector. +abstract class OffsetBase { + /// Abstract const constructor. This constructor enables subclasses to provide + /// const constructors so that they can be used in const expressions. + /// + /// The first argument sets the horizontal dimension, and the second the + /// vertical dimension. + const OffsetBase(this._dx, this._dy); + + final double _dx; + final double _dy; + + /// Returns true if either dimension is [double.INFINITY], and false if both + /// are finite (or negative infinity, or NaN). + /// + /// This is different than comparing for equality with an instance that has + /// _both_ dimensions set to [double.INFINITY]. + bool get isInfinite => _dx >= double.INFINITY || _dy >= double.INFINITY; + + /// Less-than operator. Compares an [Offset] or [Size] to another [Offset] or + /// [Size], and returns true if both the horizontal and vertical values of the + /// left-hand-side operand are smaller than the horizontal and vertical values + /// of the right-hand-side operand respectively. Returns false otherwise. + /// + /// This is a partial ordering. It is possible for two values to be neither + /// less, nor greater than, nor equal to, another. + bool operator <(OffsetBase other) => _dx < other._dx && _dy < other._dy; + + /// Less-than-or-equal-to operator. Compares an [Offset] or [Size] to another + /// [Offset] or [Size], and returns true if both the horizontal and vertical + /// values of the left-hand-side operand are smaller than or equal to the + /// horizontal and vertical values of the right-hand-side operand + /// respectively. Returns false otherwise. + /// + /// This is a partial ordering. It is possible for two values to be neither + /// less, nor greater than, nor equal to, another. + bool operator <=(OffsetBase other) => _dx <= other._dx && _dy <= other._dy; + + /// Greater-than operator. Compares an [Offset] or [Size] to another [Offset] + /// or [Size], and returns true if both the horizontal and vertical values of + /// the left-hand-side operand are bigger than the horizontal and vertical + /// values of the right-hand-side operand respectively. Returns false + /// otherwise. + /// + /// This is a partial ordering. It is possible for two values to be neither + /// less, nor greater than, nor equal to, another. + bool operator >(OffsetBase other) => _dx > other._dx && _dy > other._dy; + + /// Greater-than-or-equal-to operator. Compares an [Offset] or [Size] to + /// another [Offset] or [Size], and returns true if both the horizontal and + /// vertical values of the left-hand-side operand are bigger than or equal to + /// the horizontal and vertical values of the right-hand-side operand + /// respectively. Returns false otherwise. + /// + /// This is a partial ordering. It is possible for two values to be neither + /// less, nor greater than, nor equal to, another. + bool operator >=(OffsetBase other) => _dx > other._dx && _dy >= other._dy; + + /// Equality operator. Compares an [Offset] or [Size] to another [Offset] or + /// [Size], and returns true if the horizontal and vertical values of the + /// left-hand-side operand are equal to the horizontal and vertical values of + /// the right-hand-side operand respectively. Returns false otherwise. + @override + bool operator ==(dynamic other) { + if (other is! OffsetBase) + return false; + final OffsetBase typedOther = other; + return _dx == typedOther._dx && + _dy == typedOther._dy; + } + + @override + int get hashCode => hashValues(_dx, _dy); +} + +/// An immutable 2D floating-point offset. +/// +/// An Offset represents a vector from an unspecified [Point]. +/// +/// Adding an offset to a [Point] returns the [Point] that is indicated by the +/// vector from that first point. +class Offset extends OffsetBase { + /// Creates an offset. The first argument sets [dx], the horizontal component, + /// and the second sets [dy], the vertical component. + const Offset(double dx, double dy) : super(dx, dy); + + /// The x component of the offset. + double get dx => _dx; + + /// The y component of the offset. + double get dy => _dy; + + /// The magnitude of the offset. + double get distance => math.sqrt(_dx * _dx + _dy * _dy); + + /// The square of the magnitude of the offset. + /// + /// This is cheaper than computing the [distance] itself. + double get distanceSquared => _dx * _dx + _dy * _dy; + + /// An offset with zero magnitude. + static const Offset zero = const Offset(0.0, 0.0); + + /// An offset with infinite x and y components. + static const Offset infinite = const Offset(double.INFINITY, double.INFINITY); + + /// Returns a new offset with the x component scaled by scaleX and the y component scaled by scaleY. + Offset scale(double scaleX, double scaleY) => new Offset(dx * scaleX, dy * scaleY); + + /// Returns a new offset with translateX added to the x component and translateY added to the y component. + Offset translate(double translateX, double translateY) => new Offset(dx + translateX, dy + translateY); + + /// Unary negation operator. Returns an offset with the coordinates negated. + Offset operator -() => new Offset(-dx, -dy); + + /// Binary subtraction operator. Returns an offset whose [dx] value is the + /// left-hand-side operand's [dx] minus the right-hand-side operand's [dx] and + /// whose [dy] value is the left-hand-side operand's [dy] minus the + /// right-hand-side operand's [dy]. + Offset operator -(Offset other) => new Offset(dx - other.dx, dy - other.dy); + + /// Binary addition operator. Returns an offset whose [dx] value is the sum of + /// the [dx] values of the two operands, and whose [dy] value is the sum of + /// the [dy] values of the two operands. + Offset operator +(Offset other) => new Offset(dx + other.dx, dy + other.dy); + + /// Multiplication operator. Returns an offset whose coordinates are the + /// coordinates of the left-hand-side operand (an Offset) multiplied by the + /// scalar right-hand-side operand (a double). + Offset operator *(double operand) => new Offset(dx * operand, dy * operand); + + /// Division operator. Returns an offset whose coordinates are the + /// coordinates of the left-hand-side operand (an Offset) divided by the + /// scalar right-hand-side operand (a double). + Offset operator /(double operand) => new Offset(dx / operand, dy / operand); + + /// Integer (truncating) division operator. Returns an offset whose + /// coordinates are the coordinates of the left-hand-side operand (an Offset) + /// divided by the scalar right-hand-side operand (a double), rounded towards + /// zero. + Offset operator ~/(double operand) => new Offset((dx ~/ operand).toDouble(), (dy ~/ operand).toDouble()); + + /// Modulo (remainder) operator. Returns an offset whose coordinates are the + /// remainder of dividing the coordinates of the left-hand-side operand (an + /// Offset) by the scalar right-hand-side operand (a double). + Offset operator %(double operand) => new Offset(dx % operand, dy % operand); + + /// Rectangle constructor operator. Combines an offset and a [Size] to form a + /// [Rect] whose top-left coordinate is the point given by adding this offset, + /// the left-hand-side operand, to the origin, and whose size is the + /// right-hand-side operand. + /// + /// ```dart + /// Rect myRect = Offset.zero & const Size(100.0, 100.0); + /// // same as: new Rect.fromLTWH(0.0, 0.0, 100.0, 100.0) + /// ``` + /// + /// See also: [Point.&] + Rect operator &(Size other) => new Rect.fromLTWH(dx, dy, other.width, other.height); + + /// Returns the point at (0, 0) plus this offset. + Point toPoint() => new Point(dx, dy); + + /// Linearly interpolate between two offsets. + /// + /// If either offset is null, this function interpolates from [Offset.zero]. + static Offset lerp(Offset a, Offset b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return b * t; + if (b == null) + return a * (1.0 - t); + return new Offset(lerpDouble(a.dx, b.dx, t), lerpDouble(a.dy, b.dy, t)); + } + + /// Compares two Offsets for equality. + @override + bool operator ==(dynamic other) => other is Offset && super == other; + + @override + String toString() => "Offset(${dx?.toStringAsFixed(1)}, ${dy?.toStringAsFixed(1)})"; +} + +/// Holds a 2D floating-point size. +/// +/// You can think of this as a vector from Point(0,0) to Point(size.width, +/// size.height). +class Size extends OffsetBase { + /// Creates a Size with the given width and height. + const Size(double width, double height) : super(width, height); + + /// Creates an instance of Size that has the same values as another. + // Used by the rendering library's _DebugSize hack. + Size.copy(Size source) : super(source.width, source.height); + + /// Creates a square Size whose width and height are the given dimension. + const Size.square(double dimension) : super(dimension, dimension); + + /// Creates a Size with the given width and an infinite height. + const Size.fromWidth(double width) : super(width, double.INFINITY); + + /// Creates a Size with the given height and an infinite width. + const Size.fromHeight(double height) : super(double.INFINITY, height); + + /// Creates a square Size whose width and height are twice the given dimension. + /// + /// This is a square that contains a circle with the given radius. + const Size.fromRadius(double radius) : super(radius * 2.0, radius * 2.0); + + /// The horizontal extent of this size. + double get width => _dx; + + /// The vertical extent of this size. + double get height => _dy; + + /// An empty size, one with a zero width and a zero height. + static const Size zero = const Size(0.0, 0.0); + + /// A size whose width and height are infinite. + /// + /// See also [isInfinite], which checks whether either dimension is infinite. + static const Size infinite = const Size(double.INFINITY, double.INFINITY); + + /// Binary subtraction operator for Size. + /// + /// Subtracting a Size from a Size returns the [Offset] that describes how + /// much bigger the left-hand-side operand is than the right-hand-side + /// operand. Adding that resulting Offset to the Size that was the + /// right-hand-side operand would return a Size equal to the Size that was the + /// left-hand-side operand. (i.e. if `sizeA - sizeB -> offsetA`, then `offsetA + /// + sizeB -> sizeA`) + /// + /// Subtracting an [Offset] from a Size returns the Size that is smaller than + /// the Size operand by the difference given by the Offset operand. In other + /// words, the returned Size has a [width] consisting of the [width] of the + /// left-hand-side operand minus the [Offset.dx] dimension of the + /// right-hand-side operand, and a [height] consisting of the [height] of the + /// left-hand-side operand minus the [Offset.dy] dimension of the + /// right-hand-side operand. + dynamic operator -(OffsetBase other) { + if (other is Size) + return new Offset(width - other.width, height - other.height); + if (other is Offset) + return new Size(width - other.dx, height - other.dy); + throw new ArgumentError(other); + } + + /// Binary addition operator for adding an Offset to a Size. Returns a Size + /// whose [width] is the sum of the [width] of the left-hand-side operand, a + /// Size, and the [Offset.dx] dimension of the right-hand-side operand, an + /// [Offset], and whose [height] is the sum of the [height] of the + /// left-hand-side operand and the [Offset.dy] dimension of the + /// right-hand-side operand. + Size operator +(Offset other) => new Size(width + other.dx, height + other.dy); + + /// Multiplication operator. Returns a size whose dimensions are the + /// dimensions of the left-hand-side operand (a Size) multiplied by the + /// scalar right-hand-side operand (a double). + Size operator *(double operand) => new Size(width * operand, height * operand); + + /// Division operator. Returns a size whose dimensions are the dimensions of + /// the left-hand-side operand (a Size) divided by the scalar right-hand-side + /// operand (a double). + Size operator /(double operand) => new Size(width / operand, height / operand); + + /// Integer (truncating) division operator. Returns a size whose dimensions + /// are the dimensions of the left-hand-side operand (a Size) divided by the + /// scalar right-hand-side operand (a double), rounded towards zero. + Size operator ~/(double operand) => new Size((width ~/ operand).toDouble(), (height ~/ operand).toDouble()); + + /// Modulo (remainder) operator. Returns a size whose dimensions are the + /// remainder of dividing the left-hand-side operand (a Size) by the scalar + /// right-hand-side operand (a double). + Size operator %(double operand) => new Size(width % operand, height % operand); + + /// Whether this size encloses a non-zero area. + /// + /// Negative areas are considered empty. + bool get isEmpty => width <= 0.0 || height <= 0.0; + + /// The lesser of the [width] and the [height]. + double get shortestSide { + double w = width.abs(); + double h = height.abs(); + return w < h ? w : h; + } + + // Convenience methods that do the equivalent of calling the similarly named + // methods on a Rect constructed from the given origin and this size. + + /// The point at the intersection of the top and left edges of the rectangle + /// described by the given point (which is interpreted as the top-left corner) + /// and this size. + /// + /// See also [Rect.topLeft]. + Point topLeft(Point origin) => origin; + + /// The point at the center of the top edge of the rectangle described by the + /// given point (which is interpreted as the top-left corner) and this size. + /// + /// See also [Rect.topCenter]. + Point topCenter(Point origin) => new Point(origin.x + width / 2.0, origin.y); + + /// The point at the intersection of the top and right edges of the rectangle + /// described by the given point (which is interpreted as the top-left corner) + /// and this size. + /// + /// See also [Rect.topRight]. + Point topRight(Point origin) => new Point(origin.x + width, origin.y); + + /// The point at the center of the left edge of the rectangle described by the + /// given point (which is interpreted as the top-left corner) and this size. + /// + /// See also [Rect.centerLeft]. + Point centerLeft(Point origin) => new Point(origin.x, origin.y + height / 2.0); + + /// The point halfway between the left and right and the top and bottom edges + /// of the rectangle described by the given point (which is interpreted as the + /// top-left corner) and this size. + /// + /// See also [Rect.center]. + Point center(Point origin) => new Point(origin.x + width / 2.0, origin.y + height / 2.0); + + /// The point at the center of the right edge of the rectangle described by the + /// given point (which is interpreted as the top-left corner) and this size. + /// + /// See also [Rect.centerLeft]. + Point centerRight(Point origin) => new Point(origin.x + width, origin.y + height / 2.0); + + /// The point at the intersection of the bottom and left edges of the + /// rectangle described by the given point (which is interpreted as the + /// top-left corner) and this size. + /// + /// See also [Rect.bottomLeft]. + Point bottomLeft(Point origin) => new Point(origin.x, origin.y + height); + + /// The point at the center of the bottom edge of the rectangle described by + /// the given point (which is interpreted as the top-left corner) and this + /// size. + /// + /// See also [Rect.bottomLeft]. + Point bottomCenter(Point origin) => new Point(origin.x + width / 2.0, origin.y + height); + + /// The point at the intersection of the bottom and right edges of the + /// rectangle described by the given point (which is interpreted as the + /// top-left corner) and this size. + /// + /// See also [Rect.bottomRight]. + Point bottomRight(Point origin) => new Point(origin.x + width, origin.y + height); + + /// Linearly interpolate between two sizes + /// + /// If either size is null, this function interpolates from [Offset.zero]. + static Size lerp(Size a, Size b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return b * t; + if (b == null) + return a * (1.0 - t); + return new Size(lerpDouble(a.width, b.width, t), lerpDouble(a.height, b.height, t)); + } + + /// Compares two Sizes for equality. + @override + bool operator ==(dynamic other) => other is Size && super == other; + + @override + String toString() => "Size(${width?.toStringAsFixed(1)}, ${height?.toStringAsFixed(1)})"; +} + +/// An immutable 2D floating-point x,y coordinate pair. +/// +/// A Point represents a specific position in Cartesian space. +/// +/// Subtracting a point from another returns the [Offset] that represents the +/// vector between the two points. +class Point { + /// Creates a point. The first argument sets [x], the horizontal component, + /// and the second sets [y], the vertical component. + const Point(this.x, this.y); + + /// The horizontal component of the point. + final double x; + + /// The vertical component of the point. + final double y; + + /// The point at the origin, (0, 0). + static const Point origin = const Point(0.0, 0.0); + + /// Unary negation operator. Returns a point with the coordinates negated. + Point operator -() => new Point(-x, -y); + + /// Binary subtraction operator. Returns an [Offset] representing the + /// direction and distance from the other point (the right-hand-side operand) + /// to this point (the left-hand-side operand). + Offset operator -(Point other) => new Offset(x - other.x, y - other.y); + + /// Binary addition operator. Returns a point that is this point (the + /// left-hand-side operand) plus a vector [Offset] (the right-hand-side + /// operand). + Point operator +(Offset other) => new Point(x + other.dx, y + other.dy); + + /// Rectangle constructor operator. Combines a point and a [Size] to form a + /// [Rect] whose top-left coordinate is this point, the left-hand-side + /// operand, and whose size is the right-hand-side operand. + /// + /// ```dart + /// Rect myRect = Point.origin & const Size(100.0, 100.0); + /// // same as: new Rect.fromLTWH(0.0, 0.0, 100.0, 100.0) + /// ``` + /// + /// See also: [Offset.&] + Rect operator &(Size other) => new Rect.fromLTWH(x, y, other.width, other.height); + + /// Multiplication operator. Returns a point whose coordinates are the + /// coordinates of the left-hand-side operand (a Point) multiplied by the + /// scalar right-hand-side operand (a double). + Point operator *(double operand) => new Point(x * operand, y * operand); + + /// Division operator. Returns a point whose coordinates are the + /// coordinates of the left-hand-side operand (a point) divided by the + /// scalar right-hand-side operand (a double). + Point operator /(double operand) => new Point(x / operand, y / operand); + + /// Integer (truncating) division operator. Returns a point whose + /// coordinates are the coordinates of the left-hand-side operand (a point) + /// divided by the scalar right-hand-side operand (a double), rounded towards + /// zero. + Point operator ~/(double operand) => new Point((x ~/ operand).toDouble(), (y ~/ operand).toDouble()); + + /// Modulo (remainder) operator. Returns a point whose coordinates are the + /// remainder of the coordinates of the left-hand-side operand (a point) + /// divided by the scalar right-hand-side operand (a double). + Point operator %(double operand) => new Point(x % operand, y % operand); + + /// Converts this point to an [Offset] with the same coordinates. + // does the equivalent of "return this - Point.origin" + Offset toOffset() => new Offset(x, y); + + /// Linearly interpolate between two points. + /// + /// If either point is null, this function interpolates from [Point.origin]. + static Point lerp(Point a, Point b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return b * t; + if (b == null) + return a * (1.0 - t); + return new Point(lerpDouble(a.x, b.x, t), lerpDouble(a.y, b.y, t)); + } + + @override + bool operator ==(dynamic other) { + if (other is! Point) + return false; + final Point typedOther = other; + return x == typedOther.x && + y == typedOther.y; + } + + @override + int get hashCode => hashValues(x, y); + + @override + String toString() => "Point(${x?.toStringAsFixed(1)}, ${y?.toStringAsFixed(1)})"; +} + +/// An immutable 2D, axis-aligned, floating-point rectangle whose coordinates +/// are relative to an origin point. +class Rect { + Rect._(); + + /// Construct a rectangle from its left, top, right, and bottom edges. + Rect.fromLTRB(double left, double top, double right, double bottom) { + _value + ..[0] = left + ..[1] = top + ..[2] = right + ..[3] = bottom; + } + + /// Construct a rectangle from its left and top edges, its width, and its height. + /// + /// To construct a [Rect] from a [Point] or [Offset] and a [Size], you can use + /// the rectangle constructor operator `&`. See [Point.&] and [Offset.&]. + Rect.fromLTWH(double left, double top, double width, double height) { + _value + ..[0] = left + ..[1] = top + ..[2] = left + width + ..[3] = top + height; + } + + /// Construct a rectangle that bounds the given circle. + Rect.fromCircle({ Point center, double radius }) { + _value + ..[0] = center.x - radius + ..[1] = center.y - radius + ..[2] = center.x + radius + ..[3] = center.y + radius; + } + + /// Construct the smallest rectangle that encloses the given points. + Rect.fromPoints(Point a, Point b) { + _value + ..[0] = math.min(a.x, b.x) + ..[1] = math.min(a.y, b.y) + ..[2] = math.max(a.x, b.x) + ..[3] = math.max(a.y, b.y); + } + + static const int _kDataSize = 4; + final Float32List _value = new Float32List(_kDataSize); + + /// The offset of the left edge of this rectangle from the x axis. + double get left => _value[0]; + + /// The offset of the top edge of this rectangle from the y axis. + double get top => _value[1]; + + /// The offset of the right edge of this rectangle from the x axis. + double get right => _value[2]; + + /// The offset of the bottom edge of this rectangle from the y axis. + double get bottom => _value[3]; + + /// A rectangle with left, top, right, and bottom edges all at zero. + static final Rect zero = new Rect._(); + + /// Returns a new rectangle translated by the given offset. + Rect shift(Offset offset) { + return new Rect.fromLTRB(left + offset.dx, top + offset.dy, right + offset.dx, bottom + offset.dy); + } + + /// Returns a new rectangle with edges moved outwards by the given delta. + Rect inflate(double delta) { + return new Rect.fromLTRB(left - delta, top - delta, right + delta, bottom + delta); + } + + /// Returns a new rectangle with edges moved inwards by the given delta. + Rect deflate(double delta) => inflate(-delta); + + /// Returns a new rectangle that is the intersection of the given + /// rectangle and this rectangle. The two rectangles must overlap + /// for this to be meaningful. If the two rectangles do not overlap, + /// then the resulting Rect will have a negative width or height. + Rect intersect(Rect other) { + return new Rect.fromLTRB( + math.max(left, other.left), + math.max(top, other.top), + math.min(right, other.right), + math.min(bottom, other.bottom) + ); + } + + /// The distance between the left and right edges of this rectangle. + double get width => right - left; + + /// The distance between the top and bottom edges of this rectangle. + double get height => bottom - top; + + /// The distance between upper-left corner and the lower-right corner of this rectangle. + Size get size => new Size(width, height); + + /// Whether this rectangle encloses a non-zero area. + /// Negative areas are considered empty. + bool get isEmpty => left >= right || top >= bottom; + + /// The lesser of the magnitudes of the width and the height of this + /// rectangle. + double get shortestSide { + double w = width.abs(); + double h = height.abs(); + return w < h ? w : h; + } + + + /// The point at the intersection of the top and left edges of this rectangle. + /// + /// See also [Size.topLeft]. + Point get topLeft => new Point(left, top); + + /// The point at the center of the top edge of this rectangle. + /// + /// See also [Size.topCenter]. + Point get topCenter => new Point(left + width / 2.0, top); + + /// The point at the intersection of the top and right edges of this rectangle. + /// + /// See also [Size.topRight]. + Point get topRight => new Point(right, top); + + /// The point at the center of the left edge of this rectangle. + /// + /// See also [Size.centerLeft]. + Point get centerLeft => new Point(left, top + height / 2.0); + + /// The point halfway between the left and right and the top and bottom edges of this rectangle. + /// + /// See also [Size.center]. + Point get center => new Point(left + width / 2.0, top + height / 2.0); + + /// The point at the center of the right edge of this rectangle. + /// + /// See also [Size.centerLeft]. + Point get centerRight => new Point(right, top + height / 2.0); + + /// The point at the intersection of the bottom and left edges of this rectangle. + /// + /// See also [Size.bottomLeft]. + Point get bottomLeft => new Point(left, bottom); + + /// The point at the center of the bottom edge of this rectangle. + /// + /// See also [Size.bottomLeft]. + Point get bottomCenter => new Point(left + width / 2.0, bottom); + + /// The point at the intersection of the bottom and right edges of this rectangle. + /// + /// See also [Size.bottomRight]. + Point get bottomRight => new Point(right, bottom); + + + /// Whether the given point lies between the left and right and the top and bottom edges of this rectangle. + /// + /// Rectangles include their top and left edges but exclude their bottom and right edges. + bool contains(Point point) { + return point.x >= left && point.x < right && point.y >= top && point.y < bottom; + } + + /// Linearly interpolate between two rectangles. + /// + /// If either rect is null, [Rect.zero] is used as a substitute. + static Rect lerp(Rect a, Rect b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return new Rect.fromLTRB(b.left * t, b.top * t, b.right * t, b.bottom * t); + if (b == null) { + double k = 1.0 - t; + return new Rect.fromLTRB(a.left * k, a.top * k, a.right * k, a.bottom * k); + } + return new Rect.fromLTRB( + lerpDouble(a.left, b.left, t), + lerpDouble(a.top, b.top, t), + lerpDouble(a.right, b.right, t), + lerpDouble(a.bottom, b.bottom, t) + ); + } + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! Rect) + return false; + final Rect typedOther = other; + for (int i = 0; i < _kDataSize; i += 1) { + if (_value[i] != typedOther._value[i]) + return false; + } + return true; + } + + @override + int get hashCode => hashList(_value); + + @override + String toString() => "Rect.fromLTRB(${left.toStringAsFixed(1)}, ${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ${bottom.toStringAsFixed(1)})"; +} + +/// A radius for either circular or elliptical shapes. +class Radius { + /// Constructs a circular radius. [x] and [y] will have the same radius value. + const Radius.circular(double radius) : this.elliptical(radius, radius); + + /// Constructs an elliptical radius with the given radii. + const Radius.elliptical(this.x, this.y); + + /// A radius with [x] and [y] values set to zero. + /// + /// You can use [Radius.zero] with [RRect] to have right-angle corners. + static const Radius zero = const Radius.circular(0.0); + + /// The radius value on the horizontal axis. + final double x; + + /// The radius value on the vertical axis. + final double y; + + /// Linearly interpolate between two radii. + /// + /// If either is null, this function substitutes [Radius.zero] instead. + static Radius lerp(Radius a, Radius b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return new Radius.elliptical(b.x * t, b.y * t); + if (b == null) { + double k = 1.0 - t; + return new Radius.elliptical(a.x * k, a.y * k); + } + return new Radius.elliptical( + lerpDouble(a.x, b.x, t), + lerpDouble(a.y, b.y, t) + ); + } + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! Radius) + return false; + final Radius typedOther = other; + return typedOther.x == x && typedOther.y == y; + } + + @override + int get hashCode => hashValues(x, y); + + @override + String toString() { + return x == y ? 'Radius.circular(${x.toStringAsFixed(1)})' : + 'Radius.elliptical(${x.toStringAsFixed(1)}, ' + '${y.toStringAsFixed(1)})'; + } +} + +/// A rounded rectangle with the custom radii for all four corners. +class RRect { + RRect._(); + + /// Construct a rounded rectangle from its left, top, right, and bottom edges, + /// and the same radii along its horizontal axis and its vertical axis. + RRect.fromLTRBXY(double left, double top, double right, double bottom, + double radiusX, double radiusY) { + _value + ..[0] = left + ..[1] = top + ..[2] = right + ..[3] = bottom + ..[4] = radiusX + ..[5] = radiusY + ..[6] = radiusX + ..[7] = radiusY + ..[8] = radiusX + ..[9] = radiusY + ..[10] = radiusX + ..[11] = radiusY; + } + + /// Construct a rounded rectangle from its left, top, right, and bottom edges, + /// and the same radius in each corner. + RRect.fromLTRBR(double left, double top, double right, double bottom, + Radius radius) { + _value + ..[0] = left + ..[1] = top + ..[2] = right + ..[3] = bottom + ..[4] = radius.x + ..[5] = radius.y + ..[6] = radius.x + ..[7] = radius.y + ..[8] = radius.x + ..[9] = radius.y + ..[10] = radius.x + ..[11] = radius.y; + } + + /// Construct a rounded rectangle from its bounding box and the same radii + /// along its horizontal axis and its vertical axis. + RRect.fromRectXY(Rect rect, double radiusX, double radiusY) { + _value + ..[0] = rect.left + ..[1] = rect.top + ..[2] = rect.right + ..[3] = rect.bottom + ..[4] = radiusX + ..[5] = radiusY + ..[6] = radiusX + ..[7] = radiusY + ..[8] = radiusX + ..[9] = radiusY + ..[10] = radiusX + ..[11] = radiusY; + } + + /// Construct a rounded rectangle from its bounding box and a radius that is + /// the same in each corner. + RRect.fromRectAndRadius(Rect rect, Radius radius) { + _value + ..[0] = rect.left + ..[1] = rect.top + ..[2] = rect.right + ..[3] = rect.bottom + ..[4] = radius.x + ..[5] = radius.y + ..[6] = radius.x + ..[7] = radius.y + ..[8] = radius.x + ..[9] = radius.y + ..[10] = radius.x + ..[11] = radius.y; + } + + /// Construct a rounded rectangle from its left, top, right, and bottom edges, + /// and topLeft, topRight, bottomRight, and bottomLeft radii. + /// + /// The corner radii default to [Radius.zero], i.e. right-angled corners. + RRect.fromLTRBAndCorners( + double left, + double top, + double right, + double bottom, + { + Radius topLeft: Radius.zero, + Radius topRight: Radius.zero, + Radius bottomRight: Radius.zero, + Radius bottomLeft: Radius.zero + } + ) { + _value + ..[0] = left + ..[1] = top + ..[2] = right + ..[3] = bottom + ..[4] = topLeft.x + ..[5] = topLeft.y + ..[6] = topRight.x + ..[7] = topRight.y + ..[8] = bottomRight.x + ..[9] = bottomRight.y + ..[10] = bottomLeft.x + ..[11] = bottomLeft.y; + } + + /// Construct a rounded rectangle from its bounding box and and topLeft, + /// topRight, bottomRight, and bottomLeft radii. + /// + /// The corner radii default to [Radius.zero], i.e. right-angled corners + RRect.fromRectAndCorners( + Rect rect, + { + Radius topLeft: Radius.zero, + Radius topRight: Radius.zero, + Radius bottomRight: Radius.zero, + Radius bottomLeft: Radius.zero + } + ) { + _value + ..[0] = rect.left + ..[1] = rect.top + ..[2] = rect.right + ..[3] = rect.bottom + ..[4] = topLeft.x + ..[5] = topLeft.y + ..[6] = topRight.x + ..[7] = topRight.y + ..[8] = bottomRight.x + ..[9] = bottomRight.y + ..[10] = bottomLeft.x + ..[11] = bottomLeft.y; + } + + RRect._fromList(List list) { + for (int i = 0; i < _kDataSize; i += 1) + _value[i] = list[i]; + } + + static const int _kDataSize = 12; + final Float32List _value = new Float32List(_kDataSize); + RRect _scaled; // same RRect with scaled radii per side + + /// The offset of the left edge of this rectangle from the x axis. + double get left => _value[0]; + + /// The offset of the top edge of this rectangle from the y axis. + double get top => _value[1]; + + /// The offset of the right edge of this rectangle from the x axis. + double get right => _value[2]; + + /// The offset of the bottom edge of this rectangle from the y axis. + double get bottom => _value[3]; + + /// The top-left horizontal radius. + double get tlRadiusX => _value[4]; + + /// The top-left vertical radius. + double get tlRadiusY => _value[5]; + + /// The top-left [Radius]. + Radius get tlRadius => new Radius.elliptical(_value[4], _value[5]); + + /// The top-right horizontal radius. + double get trRadiusX => _value[6]; + + /// The top-right vertical radius. + double get trRadiusY => _value[7]; + + /// The top-right [Radius]. + Radius get trRadius => new Radius.elliptical(_value[6], _value[7]); + + /// The bottom-right horizontal radius. + double get brRadiusX => _value[8]; + + /// The bottom-right vertical radius. + double get brRadiusY => _value[9]; + + /// The bottom-right [Radius]. + Radius get brRadius => new Radius.elliptical(_value[8], _value[9]); + + /// The bottom-left horizontal radius. + double get blRadiusX => _value[10]; + + /// The bottom-left vertical radius. + double get blRadiusY => _value[11]; + + /// The bottom-left [Radius]. + Radius get blRadius => new Radius.elliptical(_value[10], _value[11]); + + /// A rounded rectangle with all the values set to zero. + static final RRect zero = new RRect._(); + + /// Returns a new RRect translated by the given offset. + RRect shift(Offset offset) { + return new RRect.fromLTRBAndCorners( + _value[0] + offset.dx, + _value[1] + offset.dy, + _value[2] + offset.dx, + _value[3] + offset.dy, + topLeft: new Radius.elliptical( + _value[4], + _value[5] + ), + topRight: new Radius.elliptical( + _value[6], + _value[7] + ), + bottomRight: new Radius.elliptical( + _value[8], + _value[9] + ), + bottomLeft: new Radius.elliptical( + _value[10], + _value[11] + ) + ); + } + + /// Returns a new RRect with edges and radii moved outwards by the given + /// delta. + RRect inflate(double delta) { + return new RRect.fromLTRBAndCorners( + _value[0] - delta, + _value[1] - delta, + _value[2] + delta, + _value[3] + delta, + topLeft: new Radius.elliptical( + _value[4] + delta, + _value[5] + delta + ), + topRight: new Radius.elliptical( + _value[6] + delta, + _value[7] + delta + ), + bottomRight: new Radius.elliptical( + _value[8] + delta, + _value[9] + delta + ), + bottomLeft: new Radius.elliptical( + _value[10] + delta, + _value[11] + delta + ) + ); + } + + /// Returns a new RRect with edges and radii moved inwards by the given delta. + RRect deflate(double delta) => inflate(-delta); + + /// The distance between the left and right edges of this rectangle. + double get width => right - left; + + /// The distance between the top and bottom edges of this rectangle. + double get height => bottom - top; + + /// The bounding box of this rounded rectangle (the rectangle with no rounded corners). + Rect get outerRect => new Rect.fromLTRB(left, top, right, bottom); + + /// The non-rounded rectangle that is constrained by the smaller of the two + /// diagonals, with each diagonal traveling through the middle of the curve + /// corners. The middle of a corner is the intersection of the curve with its + /// respective quadrant bisector. + Rect get safeInnerRect { + const double kInsetFactor = 0.29289321881; // 1-cos(pi/4) + + final double leftRadius = math.max(blRadiusX, tlRadiusX); + final double topRadius = math.max(tlRadiusY, trRadiusY); + final double rightRadius = math.max(trRadiusX, brRadiusX); + final double bottomRadius = math.max(brRadiusY, blRadiusY); + + return new Rect.fromLTRB( + left + leftRadius * kInsetFactor, + top + topRadius * kInsetFactor, + right - rightRadius * kInsetFactor, + bottom - bottomRadius * kInsetFactor + ); + } + + /// The rectangle that would be formed using the axis-aligned intersection of + /// the sides of the rectangle, i.e., the rectangle formed from the + /// inner-most centers of the ellipses that form the corners. This is the + /// intersection of the [wideMiddleRect] and the [tallMiddleRect]. If any of + /// the intersections are void, the resulting [Rect] will have negative width + /// or height. + Rect get middleRect { + final double leftRadius = math.max(blRadiusX, tlRadiusX); + final double topRadius = math.max(tlRadiusY, trRadiusY); + final double rightRadius = math.max(trRadiusX, brRadiusX); + final double bottomRadius = math.max(brRadiusY, blRadiusY); + return new Rect.fromLTRB( + left + leftRadius, + top + topRadius, + right - rightRadius, + bottom - bottomRadius + ); + } + + /// The biggest rectangle that is entirely inside the rounded rectangle and + /// has the full width of the rounded rectangle. If the rounded rectangle does + /// not have an axis-aligned intersection of its left and right side, the + /// resulting [Rect] will have negative width or height. + Rect get wideMiddleRect { + final double topRadius = math.max(tlRadiusY, trRadiusY); + final double bottomRadius = math.max(brRadiusY, blRadiusY); + return new Rect.fromLTRB( + left, + top + topRadius, + right, + bottom - bottomRadius + ); + } + + /// The biggest rectangle that is entirely inside the rounded rectangle and + /// has the full height of the rounded rectangle. If the rounded rectangle + /// does not have an axis-aligned intersection of its top and bottom side, the + /// resulting [Rect] will have negative width or height. + Rect get tallMiddleRect { + final double leftRadius = math.max(blRadiusX, tlRadiusX); + final double rightRadius = math.max(trRadiusX, brRadiusX); + return new Rect.fromLTRB( + left + leftRadius, + top, + right - rightRadius, + bottom + ); + } + + /// Whether this rounded rectangle encloses a non-zero area. + /// Negative areas are considered empty. + bool get isEmpty => left >= right || top >= bottom; + + /// Whether this rounded rectangle has a side with no straight section. + bool get isStadium { + return ( + tlRadius == trRadius && trRadius == brRadius && brRadius == blRadius && + (width <= 2.0 * tlRadiusX || height <= 2.0 * tlRadiusY) + ); + } + + /// Whether this rounded rectangle has no side with a straight section. + bool get isEllipse { + return ( + tlRadius == trRadius && trRadius == brRadius && brRadius == blRadius && + width <= 2.0 * tlRadiusX && height <= 2.0 * tlRadiusY + ); + } + + /// Whether this rounded rectangle would draw as a circle. + bool get isCircle => width == height && isEllipse; + + /// The lesser of the magnitudes of the width and the height of this rounded + /// rectangle. + double get shortestSide { + double w = width.abs(); + double h = height.abs(); + return w < h ? w : h; + } + + /// The point halfway between the left and right and the top and bottom edges + /// of this rectangle. + Point get center => new Point(left + width / 2.0, top + height / 2.0); + + // Returns the minimum between min and scale to which radius1 and radius2 + // should be scaled with in order not to exceed the limit. + double _getMin(double min, double radius1, double radius2, limit) { + double sum = radius1 + radius2; + if (sum > limit && sum != 0.0) + return math.min(min, limit / sum); + return min; + } + + // Scales all radii so that on each side their sum will not pass the size of + // the width/height. + // + // Inspired from: + // https://github.com/google/skia/blob/master/src/core/SkRRect.cpp#L164 + void _scaleRadii() { + if (_scaled == null) { + double scale = 1.0; + final List scaled = new List.from(_value); + + scale = _getMin(scale, scaled[11], scaled[5], height); + scale = _getMin(scale, scaled[4], scaled[6], width); + scale = _getMin(scale, scaled[7], scaled[9], height); + scale = _getMin(scale, scaled[8], scaled[10], width); + + if (scale < 1.0) { + for (int i = 4; i < _kDataSize; i += 1) + scaled[i] *= scale; + } + + _scaled = new RRect._fromList(scaled); + } + } + + /// Whether the given point lies inside the rounded rectangle. This method + /// works by normalizing the sizes of the radii in case they overflow the + /// sizes of the side. + bool contains(Point point) { + if (point.x < left || point.x >= right || point.y < top || point.y >= bottom) + return false; // outside bounding box + + _scaleRadii(); + + double x; + double y; + double radiusX; + double radiusY; + // check whether point is in one of the rounded corner areas + // x, y -> translate to ellipse center + if (point.x < left + _scaled.tlRadiusX && + point.y < top + _scaled.tlRadiusY) { + x = point.x - left - _scaled.tlRadiusX; + y = point.y - top - _scaled.tlRadiusY; + radiusX = _scaled.tlRadiusX; + radiusY = _scaled.tlRadiusY; + } else if (point.x > right - _scaled.trRadiusX && + point.y < top + _scaled.trRadiusY) { + x = point.x - right + _scaled.trRadiusX; + y = point.y - top - _scaled.trRadiusY; + radiusX = _scaled.trRadiusX; + radiusY = _scaled.trRadiusY; + } else if (point.x > right - _scaled.brRadiusX && + point.y > bottom - _scaled.brRadiusY) { + x = point.x - right + _scaled.brRadiusX; + y = point.y - bottom + _scaled.brRadiusY; + radiusX = _scaled.brRadiusX; + radiusY = _scaled.brRadiusY; + } else if (point.x < left + _scaled.blRadiusX && + point.y > bottom - _scaled.blRadiusY) { + x = point.x - left - _scaled.blRadiusX; + y = point.y - bottom + _scaled.blRadiusY; + radiusX = _scaled.blRadiusX; + radiusY = _scaled.blRadiusY; + } else { + return true; // inside and not within the rounded corner area + } + + x = x / radiusX; + y = y / radiusY; + // check if the point is outside the unit circle + if (x * x + y * y > 1.0) + return false; + return true; + } + + /// Linearly interpolate between two rounded rectangles. + /// + /// If either is null, this function substitutes [RRect.zero] instead. + static RRect lerp(RRect a, RRect b, double t) { + if (a == null && b == null) + return null; + if (a == null) { + return new RRect._fromList([ + b.left * t, + b.top * t, + b.right * t, + b.bottom * t, + b.tlRadiusX * t, + b.tlRadiusY * t, + b.trRadiusX * t, + b.trRadiusY * t, + b.brRadiusX * t, + b.brRadiusY * t, + b.blRadiusX * t, + b.blRadiusY * t + ]); + } + if (b == null) { + double k = 1.0 - t; + return new RRect._fromList([ + a.left * k, + a.top * k, + a.right * k, + a.bottom * k, + a.tlRadiusX * k, + a.tlRadiusY * k, + a.trRadiusX * k, + a.trRadiusY * k, + a.brRadiusX * k, + a.brRadiusY * k, + a.blRadiusX * k, + a.blRadiusY * k + ]); + } + return new RRect._fromList([ + lerpDouble(a.left, b.left, t), + lerpDouble(a.top, b.top, t), + lerpDouble(a.right, b.right, t), + lerpDouble(a.bottom, b.bottom, t), + lerpDouble(a.tlRadiusX, b.tlRadiusX, t), + lerpDouble(a.tlRadiusY, b.tlRadiusY, t), + lerpDouble(a.trRadiusX, b.trRadiusX, t), + lerpDouble(a.trRadiusY, b.trRadiusY, t), + lerpDouble(a.brRadiusX, b.brRadiusX, t), + lerpDouble(a.brRadiusY, b.brRadiusY, t), + lerpDouble(a.blRadiusX, b.blRadiusX, t), + lerpDouble(a.blRadiusY, b.blRadiusY, t) + ]); + } + + @override + bool operator ==(dynamic other) { + if (identical(this, other)) + return true; + if (other is! RRect) + return false; + final RRect typedOther = other; + for (int i = 0; i < _kDataSize; i += 1) { + if (_value[i] != typedOther._value[i]) + return false; + } + return true; + } + + @override + int get hashCode => hashList(_value); + + @override + String toString() { + return 'RRect.fromLTRBAndCorners(${left.toStringAsFixed(1)}, ' + '${top.toStringAsFixed(1)}, ${right.toStringAsFixed(1)}, ' + '${bottom.toStringAsFixed(1)}, ' + 'topLeft: $tlRadius, topRight: $trRadius, ' + 'bottomRight: $brRadius, bottomLeft: $blRadius)'; + } +} + +/// A transform consisting of a translation, a rotation, and a uniform scale. +/// +/// Used by [Canvas.drawAtlas]. This is a more efficient way to represent these +/// simple transformations than a full matrix. +// Modeled after Skia's SkRSXform. +class RSTransform { + /// Creates an RSTransform. + /// + /// An [RSTransform] expresses the combination of a translation, a rotation + /// around a particular point, and a scale factor. + /// + /// The first argument, `scos`, is the cosine of the rotation, multiplied by + /// the scale factor. + /// + /// The second argument, `ssin`, is the sine of the rotation, multiplied by + /// that same scale factor. + /// + /// The third argument is the x coordinate of the translation, minus the + /// `scos` argument multiplied by the x-coordinate of the rotation point, plus + /// the `ssin` argument multiplied by the y-coordinate of the rotation point. + /// + /// The fourth argument is the y coordinate of the translation, minus the `ssin` + /// argument multiplied by the x-coordinate of the rotation point, minus the + /// `scos` argument multiplied by the y-coordinate of the rotation point. + /// + /// The [new RSTransform.fromComponents] method may be a simpler way to + /// construct these values. However, if there is a way to factor out the + /// computations of the sine and cosine of the rotation so that they can be + /// reused over multiple calls to this constructor, it may be more efficient + /// to directly use this constructor instead. + RSTransform(double scos, double ssin, double tx, double ty) { + _value + ..[0] = scos + ..[1] = ssin + ..[2] = tx + ..[3] = ty; + } + + /// Creates an RSTransform from its individual components. + /// + /// The `rotation` parameter gives the rotation in radians. + /// + /// The `scale` parameter describes the uniform scale factor. + /// + /// The `anchorX` and `anchorY` parameters give the coordinate of the point + /// around which to rotate. + /// + /// The `translateX` and `translateY` parameters give the coordinate of the + /// offset by which to translate. + /// + /// This constructor computes the arguments of the [new RSTransform] + /// constructor and then defers to that constructor to actually create the + /// object. If many [RSTransform] objects are being created and there is a way + /// to factor out the computations of the sine and cosine of the rotation + /// (which are computed each time this constructor is called) and reuse them + /// over multiple [RSTransform] objects, it may be more efficient to directly + /// use the more direct [new RSTransform] constructor instead. + factory RSTransform.fromComponents({ + double rotation, + double scale, + double anchorX, + double anchorY, + double translateX, + double translateY + }) { + final double scos = math.cos(rotation) * scale; + final double ssin = math.sin(rotation) * scale; + final double tx = translateX + -scos * anchorX + ssin * anchorY; + final double ty = translateY + -ssin * anchorX - scos * anchorY; + return new RSTransform(scos, ssin, tx, ty); + } + + final Float32List _value = new Float32List(4); + + /// The cosine of the rotation multiplied by the scale factor. + double get scos => _value[0]; + + /// The sine of the rotation multiplied by that same scale factor. + double get ssin => _value[1]; + + /// The x coordinate of the translation, minus [scos] multiplied by the + /// x-coordinate of the rotation point, plus [ssin] multiplied by the + /// y-coordinate of the rotation point. + double get tx => _value[2]; + + /// The y coordinate of the translation, minus [ssin] multiplied by the + /// x-coordinate of the rotation point, minus [scos] multiplied by the + /// y-coordinate of the rotation point. + double get ty => _value[3]; +} diff --git a/engine/src/flutter/lib/ui/painting.dart b/engine/src/flutter/lib/ui/painting.dart new file mode 100644 index 0000000000..6c93143051 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting.dart @@ -0,0 +1,1542 @@ +// 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. + +part of dart_ui; + +Color _scaleAlpha(Color a, double factor) { + return a.withAlpha((a.alpha * factor).round()); +} + +/// An immutable 32 bit color value in ARGB +class Color { + /// Construct a color from the lower 32 bits of an int. + /// + /// Bits 24-31 are the alpha value. + /// Bits 16-23 are the red value. + /// Bits 8-15 are the green value. + /// Bits 0-7 are the blue value. + const Color(int value) : value = value & 0xFFFFFFFF; + + /// Construct a color from the lower 8 bits of four integers. + const Color.fromARGB(int a, int r, int g, int b) : + value = ((((a & 0xff) << 24) | + ((r & 0xff) << 16) | + ((g & 0xff) << 8) | + ((b & 0xff) << 0)) & 0xFFFFFFFF); + + /// A 32 bit value representing this color. + /// + /// Bits 24-31 are the alpha value. + /// Bits 16-23 are the red value. + /// Bits 8-15 are the green value. + /// Bits 0-7 are the blue value. + final int value; + + /// The alpha channel of this color in an 8 bit value. + int get alpha => (0xff000000 & value) >> 24; + + /// The alpha channel of this color as a double. + double get opacity => alpha / 0xFF; + + /// The red channel of this color in an 8 bit value. + int get red => (0x00ff0000 & value) >> 16; + + /// The green channel of this color in an 8 bit value. + int get green => (0x0000ff00 & value) >> 8; + + /// The blue channel of this color in an 8 bit value. + int get blue => (0x000000ff & value) >> 0; + + /// Returns a new color that matches this color with the alpha channel + /// replaced with a (which ranges from 0 to 255). + Color withAlpha(int a) { + return new Color.fromARGB(a, red, green, blue); + } + + /// Returns a new color that matches this color with the alpha channel + /// replaced with the given opacity (which ranges from 0.0 to 1.0). + Color withOpacity(double opacity) { + assert(opacity >= 0.0 && opacity <= 1.0); + return withAlpha((255.0 * opacity).round()); + } + + /// Returns a new color that matches this color with the red channel replaced + /// with r. + Color withRed(int r) { + return new Color.fromARGB(alpha, r, green, blue); + } + + /// Returns a new color that matches this color with the green channel + /// replaced with g. + Color withGreen(int g) { + return new Color.fromARGB(alpha, red, g, blue); + } + + /// Returns a new color that matches this color with the blue channel replaced + /// with b. + Color withBlue(int b) { + return new Color.fromARGB(alpha, red, green, b); + } + + /// Linearly interpolate between two colors + /// + /// If either color is null, this function linearly interpolates from a + /// transparent instance of the other color. + static Color lerp(Color a, Color b, double t) { + if (a == null && b == null) + return null; + if (a == null) + return _scaleAlpha(b, t); + if (b == null) + return _scaleAlpha(a, 1.0 - t); + return new Color.fromARGB( + lerpDouble(a.alpha, b.alpha, t).toInt(), + lerpDouble(a.red, b.red, t).toInt(), + lerpDouble(a.green, b.green, t).toInt(), + lerpDouble(a.blue, b.blue, t).toInt() + ); + } + + @override + bool operator ==(dynamic other) { + if (other is! Color) + return false; + final Color typedOther = other; + return value == typedOther.value; + } + + @override + int get hashCode => value.hashCode; + + @override + String toString() => "Color(0x${value.toRadixString(16).padLeft(8, '0')})"; +} + +/// Algorithms to use when painting on the canvas. +/// +/// When drawing a shape or image onto a canvas, different algorithms +/// can be used to blend the pixels. The image below shows the effects +/// of these modes. +/// +/// [![Open Skia fiddle to view image.](https://flutter.io/images/transfer_mode.png)](https://fiddle.skia.org/c/864acd0659c7a866ea7296a3184b8bdd) +/// +/// See [Paint.transferMode]. +enum TransferMode { + // This list comes from Skia's SkXfermode.h and the values (order) should be + // kept in sync. + // See: https://skia.org/user/api/skpaint#SkXfermode + + clear, + src, + dst, + srcOver, + dstOver, + srcIn, + dstIn, + srcOut, + dstOut, + srcATop, + dstATop, + xor, + plus, + modulate, + + // Following blend modes are defined in the CSS Compositing standard. + + screen, // The last coeff mode. + + overlay, + darken, + lighten, + colorDodge, + colorBurn, + hardLight, + softLight, + difference, + exclusion, + multiply, // The last separable mode. + + hue, + saturation, + color, + luminosity, +} + +/// Quality levels for image filters. +/// +/// See [Paint.filterQuality]. +enum FilterQuality { + // This list comes from Skia's SkFilterQuality.h and the values (order) should + // be kept in sync. + + /// Fastest possible filtering, albeit also the lowest quality. + /// + /// Typically this implies nearest-neighbour filtering. + none, + + /// Better quality than [none], faster than [medium]. + /// + /// Typically this implies bilinear interpolation. + low, + + /// Better quality than [low], faster than [high]. + /// + /// Typically this implies a combination of bilinear interpolation and + /// pyramidal parametric prefiltering (mipmaps). + medium, + + /// Best possible quality filtering, albeit also the slowest. + /// + /// Typically this implies bicubic interpolation or better. + high, +} + +/// Styles to use for line endings. +/// +/// See [Paint.strokeCap]. +enum StrokeCap { + /// Begin and end contours with a flat edge and no extension. + butt, + + /// Begin and end contours with a semi-circle extension. + round, + + /// Begin and end contours with a half square extension. This is + /// similar to extending each contour by half the stroke width (as + /// given by [Paint.strokeWidth]). + square, +} + +/// Strategies for painting shapes and paths on a canvas. +/// +/// See [Paint.style]. +enum PaintingStyle { + // This list comes from Skia's SkPaint.h and the values (order) should be kept + // in sync. + + /// Apply the [Paint] to the inside of the shape. For example, when + /// applied to the [Paint.drawCircle] call, this results in a disc + /// of the given size being painted. + fill, + + /// Apply the [Paint] to the edge of the shape. For example, when + /// applied to the [Paint.drawCircle] call, this results is a hoop + /// of the given size being painted. The line drawn on the edge will + /// be the width given by the [Paint.strokeWidth] property. + stroke, + + /// Apply the [Paint] to the inside of the shape and the edge of the + /// shape at the same time. The resulting drawing is similar to what + /// would be achieved by inflating the shape by half the stroke + /// width (as given by [Paint.strokeWidth]), and then using [fill]. + strokeAndFill, +} + +// If we actually run on big endian machines, we'll need to do something smarter +// here. We don't use [Endianness.HOST_ENDIAN] because it's not a compile-time +// constant and can't propagate into the set/get calls. +const Endianness _kFakeHostEndian = Endianness.LITTLE_ENDIAN; + +/// A description of the style to use when drawing on a [Canvas]. +/// +/// Most APIs on [Canvas] take a [Paint] object to describe the style +/// to use for that operation. +class Paint { + // Paint objects are encoded in two buffers: + // + // * _data is binary data in four-byte fields, each of which is either a + // uint32_t or a float. The default value for each field is encoded as + // zero to make initialization trivial. Most values already have a default + // value of zero, but some, such a color, have a non-zero default value. + // To encode or decode these values, XOR the value with the default value. + // + // * _objects is a list of unencodable objects, typically wrappers for native + // objects. The objects are simply stored in the list without any additional + // encoding. + // + // The binary format must match the deserialization code in paint.cc. + + final ByteData _data = new ByteData(_kDataByteCount); + static const int _kIsAntiAliasIndex = 0; + static const int _kColorIndex = 1; + static const int _kTransferModeIndex = 2; + static const int _kStyleIndex = 3; + static const int _kStrokeWidthIndex = 4; + static const int _kStrokeCapIndex = 5; + static const int _kFilterQualityIndex = 6; + static const int _kColorFilterIndex = 7; + static const int _kColorFilterColorIndex = 8; + static const int _kColorFilterTransferModeIndex = 9; + + static const int _kIsAntiAliasOffset = _kIsAntiAliasIndex << 2; + static const int _kColorOffset = _kColorIndex << 2; + static const int _kTransferModeOffset = _kTransferModeIndex << 2; + static const int _kStyleOffset = _kStyleIndex << 2; + static const int _kStrokeWidthOffset = _kStrokeWidthIndex << 2; + static const int _kStrokeCapOffset = _kStrokeCapIndex << 2; + static const int _kFilterQualityOffset = _kFilterQualityIndex << 2; + static const int _kColorFilterOffset = _kColorFilterIndex << 2; + static const int _kColorFilterColorOffset = _kColorFilterColorIndex << 2; + static const int _kColorFilterTransferModeOffset = _kColorFilterTransferModeIndex << 2; + // If you add more fields, remember to update _kDataByteCount. + static const int _kDataByteCount = 40; + + // Binary format must match the deserialization code in paint.cc. + List _objects; + static const int _kMaskFilterIndex = 0; + static const int _kShaderIndex = 1; + static const int _kObjectCount = 2; // Must be one larger than the largest index + + /// Whether to apply anti-aliasing to lines and images drawn on the + /// canvas. + /// + /// Defaults to true. + bool get isAntiAlias { + return _data.getInt32(_kIsAntiAliasOffset, _kFakeHostEndian) == 0; + } + set isAntiAlias(bool value) { + // We encode true as zero and false as one because the default value, which + // we always encode as zero, is true. + final int encoded = value ? 0 : 1; + _data.setInt32(_kIsAntiAliasOffset, encoded, _kFakeHostEndian); + } + + static const int _kColorDefault = 0xFF000000; + + /// The color to use when stroking or filling a shape. + /// + /// Defaults to opaque black. + /// + /// See also: + /// + /// * [style], which controls whether to stroke or fill (or both). + /// * [colorFilter], which overrides [color]. + /// * [shader], which overrides [color] with more elaborate effects. + /// + /// This color is not used when compositing. To colorize a layer, use + /// [colorFilter]. + Color get color { + final int encoded = _data.getInt32(_kColorOffset, _kFakeHostEndian); + return new Color(encoded ^ _kColorDefault); + } + set color(Color value) { + assert(value != null); + final int encoded = value.value ^ _kColorDefault; + _data.setInt32(_kColorOffset, encoded, _kFakeHostEndian); + } + + static final int _kTransferModeDefault = TransferMode.srcOver.index; + + /// A transfer mode to apply when a shape is drawn or a layer is composited. + /// + /// The source colors are from the shape being drawn (e.g. from + /// [Canvas.drawPath]) or layer being composited (the graphics that were drawn + /// between the [Canvas.saveLayer] and [Canvas.restore] calls), after applying + /// the [colorFilter], if any. + /// + /// The destination colors are from the background onto which the shape or + /// layer is being composited. + /// + /// Defaults to [TransferMode.srcOver]. + TransferMode get transferMode { + final int encoded = _data.getInt32(_kTransferModeOffset, _kFakeHostEndian); + return TransferMode.values[encoded ^ _kTransferModeDefault]; + } + set transferMode(TransferMode value) { + assert(value != null); + final int encoded = value.index ^ _kTransferModeDefault; + _data.setInt32(_kTransferModeOffset, encoded, _kFakeHostEndian); + } + + /// Whether to paint inside shapes, the edges of shapes, or both. + /// + /// Defaults to [PaintingStyle.fill]. + PaintingStyle get style { + return PaintingStyle.values[_data.getInt32(_kStyleOffset, _kFakeHostEndian)]; + } + set style(PaintingStyle value) { + assert(value != null); + final int encoded = value.index; + _data.setInt32(_kStyleOffset, encoded, _kFakeHostEndian); + } + + /// How wide to make edges drawn when [style] is set to + /// [PaintingStyle.stroke] or [PaintingStyle.strokeAndFill]. The + /// width is given in logical pixels measured in the direction + /// orthogonal to the direction of the path. + /// + /// Defaults to 0.0, which correspond to a hairline width. + double get strokeWidth { + return _data.getFloat32(_kStrokeWidthOffset, _kFakeHostEndian); + } + set strokeWidth(double value) { + assert(value != null); + final double encoded = value; + _data.setFloat32(_kStrokeWidthOffset, encoded, _kFakeHostEndian); + } + + /// The kind of finish to place on the end of lines drawn when + /// [style] is set to [PaintingStyle.stroke] or + /// [PaintingStyle.strokeAndFill]. + /// + /// Defaults to [StrokeCap.butt], i.e. no caps. + StrokeCap get strokeCap { + return StrokeCap.values[_data.getInt32(_kStrokeCapOffset, _kFakeHostEndian)]; + } + set strokeCap(StrokeCap value) { + assert(value != null); + final int encoded = value.index; + _data.setInt32(_kStrokeCapOffset, encoded, _kFakeHostEndian); + } + + /// A mask filter (for example, a blur) to apply to a shape after it has been + /// drawn but before it has been composited into the image. + /// + /// See [MaskFilter] for details. + MaskFilter get maskFilter { + if (_objects == null) + return null; + return _objects[_kMaskFilterIndex]; + } + set maskFilter(MaskFilter value) { + _objects ??= new List(_kObjectCount); + _objects[_kMaskFilterIndex] = value; + } + + /// Controls the performance vs quality trade-off to use when applying + /// filters, such as [maskFilter], or when drawing images, as with + /// [Canvas.drawImageRect] or [Canvas.drawImageNine]. + /// + /// Defaults to [FilterQuality.none]. + // TODO(ianh): verify that the image drawing methods actually respect this + FilterQuality get filterQuality { + return FilterQuality.values[_data.getInt32(_kFilterQualityOffset, _kFakeHostEndian)]; + } + set filterQuality(FilterQuality value) { + assert(value != null); + final int encoded = value.index; + _data.setInt32(_kFilterQualityOffset, encoded, _kFakeHostEndian); + } + + /// The shader to use when stroking or filling a shape. + /// + /// When this is null, the [color] is used instead. + /// + /// See also: + /// + /// * [Gradient], a shader that paints a color gradient. + /// * [ImageShader], a shader that tiles an [Image]. + /// * [colorFilter], which overrides [shader]. + /// * [color], which is used if [shader] and [colorFilter] are null. + Shader get shader { + if (_objects == null) + return null; + return _objects[_kShaderIndex]; + } + set shader(Shader value) { + _objects ??= new List(_kObjectCount); + _objects[_kShaderIndex] = value; + } + + /// A color filter to apply when a shape is drawn or when a layer is + /// composited. + /// + /// See [ColorFilter] for details. + /// + /// When a shape is being drawn, [colorFilter] overrides [color] and [shader]. + ColorFilter get colorFilter { + final bool isNull = _data.getInt32(_kColorFilterOffset, _kFakeHostEndian) == 0; + if (isNull) + return null; + return new ColorFilter.mode( + new Color(_data.getInt32(_kColorFilterColorOffset, _kFakeHostEndian)), + TransferMode.values[_data.getInt32(_kColorFilterTransferModeOffset, _kFakeHostEndian)] + ); + } + set colorFilter(ColorFilter value) { + if (value == null) { + _data.setInt32(_kColorFilterOffset, 0, _kFakeHostEndian); + _data.setInt32(_kColorFilterColorOffset, 0, _kFakeHostEndian); + _data.setInt32(_kColorFilterTransferModeOffset, 0, _kFakeHostEndian); + } else { + assert(value._color != null); + assert(value._transferMode != null); + _data.setInt32(_kColorFilterOffset, 1, _kFakeHostEndian); + _data.setInt32(_kColorFilterColorOffset, value._color.value, _kFakeHostEndian); + _data.setInt32(_kColorFilterTransferModeOffset, value._transferMode.index, _kFakeHostEndian); + } + } + + @override + String toString() { + StringBuffer result = new StringBuffer(); + String semicolon = ''; + result.write('Paint('); + if (style == PaintingStyle.stroke || style == PaintingStyle.strokeAndFill) { + result.write('$style'); + if (strokeWidth != 0.0) + result.write(' $strokeWidth'); + else + result.write(' hairline'); + if (strokeCap != StrokeCap.butt) + result.write(' $strokeCap'); + semicolon = '; '; + } + if (isAntiAlias != true) { + result.write('${semicolon}antialias off'); + semicolon = '; '; + } + if (color != const Color(0xFF000000)) { + if (color != null) + result.write('$semicolon$color'); + else + result.write('${semicolon}no color'); + semicolon = '; '; + } + if (transferMode != TransferMode.srcOver) { + result.write('$semicolon$transferMode'); + semicolon = '; '; + } + if (colorFilter != null) { + result.write('${semicolon}colorFilter: $colorFilter'); + semicolon = '; '; + } + if (maskFilter != null) { + result.write('${semicolon}maskFilter: $maskFilter'); + semicolon = '; '; + } + if (filterQuality != FilterQuality.none) { + result.write('${semicolon}filterQuality: $filterQuality'); + semicolon = '; '; + } + if (shader != null) + result.write('${semicolon}shader: $shader'); + result.write(')'); + return result.toString(); + } +} + +/// Opaque handle to raw decoded image data (pixels). +/// +/// To obtain an Image object, use the [decodeImageFromDataPipe] or +/// [decodeImageFromList] functions. +/// +/// To draw an Image, use one of the methods on the [Canvas] class, such as +/// [drawImage]. +abstract class Image extends NativeFieldWrapperClass2 { + /// The number of image pixels along the image's horizontal axis. + int get width native "Image_width"; + + /// The number of image pixels along the image's vertical axis. + int get height native "Image_height"; + + /// Release the resources used by this object. The object is no longer usable + /// after this method is called. + void dispose() native "Image_dispose"; + + @override + String toString() => '[$width\u00D7$height]'; +} + +/// Callback signature for [decodeImageFromDataPipe] and [decodeImageFromList]. +typedef void ImageDecoderCallback(Image result); + +/// Convert an image file from a mojo pipe into an [Image] object. +void decodeImageFromDataPipe(int handle, ImageDecoderCallback callback) + native "decodeImageFromDataPipe"; + +/// Convert an image file from a byte array into an [Image] object. +void decodeImageFromList(Uint8List list, ImageDecoderCallback callback) + native "decodeImageFromList"; + +/// Determines how the interior of a [Path] is calculated. +enum PathFillType { + /// The interior is defined by a non-zero sum of signed edge crossings. + winding, + + /// The interior is defined by an odd number of edge crossings. + evenOdd, + + /// The interior is defined as the exterior region calculated by [winding]. + inverseWinding, + + /// The interior is defined as the exterior region calculated by [evenOdd]. + inverseEvenOdd, +} + +/// A complex, one-dimensional subset of a plane. +/// +/// A path consists of a number of subpaths, and a _current point_. +/// +/// Subpaths consist of segments of various types, such as lines, +/// arcs, or beziers. Subpaths can be open or closed, and can +/// self-intersect. +/// +/// Closed subpaths enclose a (possibly discontiguous) region of the +/// plane based on whether a line from a given point on the plane to a +/// point at infinity intersects the path an even (non-enclosed) or an +/// odd (enclosed) number of times. +/// +/// The _current point_ is initially at the origin. After each +/// operation adding a segment to a subpath, the current point is +/// updated to the end of that segment. +/// +/// Paths can be drawn on canvases using [Canvas.drawPath], and can +/// used to create clip regions using [Canvas.clipPath]. +class Path extends NativeFieldWrapperClass2 { + /// Create a new empty [Path] object. + Path() { _constructor(); } + void _constructor() native "Path_constructor"; + + /// Determines how the interior of this path is calculated. + PathFillType get fillType => PathFillType.values[_getFillType()]; + set fillType (PathFillType value) => _setFillType(value.index); + + int _getFillType() native "Path_getFillType"; + void _setFillType(int fillType) native "Path_setFillType"; + + /// Starts a new subpath at the given coordinate. + void moveTo(double x, double y) native "Path_moveTo"; + + /// Starts a new subpath at the given offset from the current point. + void relativeMoveTo(double dx, double dy) native "Path_relativeMoveTo"; + + /// Adds a straight line segment from the current point to the given + /// point. + void lineTo(double x, double y) native "Path_lineTo"; + + /// Adds a straight line segment from the current point to the point + /// at the given offset from the current point. + void relativeLineTo(double dx, double dy) native "Path_relativeLineTo"; + + /// Adds a quadratic bezier segment that curves from the current + /// point to the given point (x2,y2), using the control point + /// (x1,y1). + void quadraticBezierTo(double x1, double y1, double x2, double y2) native "Path_quadraticBezierTo"; + + /// Adds a quadratic bezier segment that curves from the current + /// point to the point at the offset (x2,y2) from the current point, + /// using the control point at the offset (x1,y1) from the current + /// point. + void relativeQuadraticBezierTo(double x1, double y1, double x2, double y2) native "Path_relativeQuadraticBezierTo"; + + /// Adds a cubic bezier segment that curves from the current point + /// to the given point (x3,y3), using the control points (x1,y1) and + /// (x2,y2). + void cubicTo(double x1, double y1, double x2, double y2, double x3, double y3) native "Path_cubicTo"; + + /// Adds a cubcic bezier segment that curves from the current point + /// to the point at the offset (x3,y3) from the current point, using + /// the control points at the offsets (x1,y1) and (x2,y2) from the + /// current point. + void relativeCubicTo(double x1, double y1, double x2, double y2, double x3, double y3) native "Path_relativeCubicTo"; + + /// Adds a bezier segment that curves from the current point to the + /// given point (x2,y2), using the control points (x1,y1) and the + /// weight w. If the weight is greater than 1, then the curve is a + /// hyperbola; if the weight equals 1, it's a parabola; and if it is + /// less than 1, it is an ellipse. + void conicTo(double x1, double y1, double x2, double y2, double w) native "Path_conicTo"; + + /// Adds a bezier segment that curves from the current point to the + /// point at the offset (x2,y2) from the current point, using the + /// control point at the offset (x1,y1) from the current point and + /// the weight w. If the weight is greater than 1, then the curve is + /// a hyperbola; if the weight equals 1, it's a parabola; and if it + /// is less than 1, it is an ellipse. + void relativeConicTo(double x1, double y1, double x2, double y2, double w) native "Path_relativeConicTo"; + + /// If the [forceMoveTo] argument is false, adds a straight line + /// segment and an arc segment. + /// + /// If the [forceMoveTo] argument is true, starts a new subpath + /// consisting of an arc segment. + /// + /// In either case, the arc segment consists of the arc that follows + /// the edge of the oval bounded by the given rectangle, from + /// startAngle radians around the oval up to startAngle + sweepAngle + /// radians around the oval, with zero radians being the point on + /// the right hand side of the oval that crosses the horizontal line + /// that intersects the center of the rectangle and with positive + /// angles going clockwise around the oval. + /// + /// The line segment added if [forceMoveTo] is false starts at the + /// current point and ends at the start of the arc. + void arcTo(Rect rect, double startAngle, double sweepAngle, bool forceMoveTo) { + _arcTo(rect.left, rect.top, rect.right, rect.bottom, startAngle, sweepAngle, forceMoveTo); + } + void _arcTo(double left, double top, double right, double bottom, + double startAngle, double sweepAngle, bool forceMoveTo) native "Path_arcTo"; + + /// Adds a new subpath that consists of four lines that outline the + /// given rectangle. + void addRect(Rect rect) { + _addRect(rect.left, rect.top, rect.right, rect.bottom); + } + void _addRect(double left, double top, double right, double bottom) native "Path_addRect"; + + /// Adds a new subpath that consists of a curve that forms the + /// ellipse that fills the given rectangle. + void addOval(Rect oval) { + _addOval(oval.left, oval.top, oval.right, oval.bottom); + } + void _addOval(double left, double top, double right, double bottom) native "Path_addOval"; + + /// Adds a new subpath with one arc segment that consists of the arc + /// that follows the edge of the oval bounded by the given + /// rectangle, from startAngle radians around the oval up to + /// startAngle + sweepAngle radians around the oval, with zero + /// radians being the point on the right hand side of the oval that + /// crosses the horizontal line that intersects the center of the + /// rectangle and with positive angles going clockwise around the + /// oval. + void addArc(Rect oval, double startAngle, double sweepAngle) { + _addArc(oval.left, oval.top, oval.right, oval.bottom, startAngle, sweepAngle); + } + void _addArc(double left, double top, double right, double bottom, + double startAngle, double sweepAngle) native "Path_addArc"; + + /// Adds a new subpath with a sequence of line segments that connect the given + /// points. If `close` is true, a final line segment will be added that + /// connects the last point to the first point. + void addPolygon(List points, bool close) { + _addPolygon(_encodePointList(points), close); + } + void _addPolygon(Float32List points, bool close) native "Path_addPolygon"; + + /// Adds a new subpath that consists of the straight lines and + /// curves needed to form the rounded rectangle described by the + /// argument. + void addRRect(RRect rrect) => _addRRect(rrect._value); + void _addRRect(Float32List rrect) native "Path_addRRect"; + + /// Adds a new subpath that consists of the given path offset by the given + /// offset. + void addPath(Path path, Offset offset) => _addPath(path, offset.dx, offset.dy); + void _addPath(Path path, double dx, double dy) native "Path_addPath"; + + /// Adds the given path to this path by extending the current segment of this + /// path with the the first segment of the given path. + void extendWithPath(Path path, Offset offset) => _extendWithPath(path, offset.dx, offset.dy); + void _extendWithPath(Path path, double dx, double dy) native "Path_extendWithPath"; + + /// Closes the last subpath, as if a straight line had been drawn + /// from the current point to the first point of the subpath. + void close() native "Path_close"; + + /// Clears the [Path] object of all subpaths, returning it to the + /// same state it had when it was created. The _current point_ is + /// reset to the origin. + void reset() native "Path_reset"; + + /// Tests to see if the point is within the path. (That is, whether + /// the point would be in the visible portion of the path if the + /// path was used with [Canvas.clipPath].) + /// + /// Returns true if the point is in the path, and false otherwise. + bool contains(Point position) => _contains(position.x, position.y); + bool _contains(double x, double y) native "Path_contains"; + + /// Returns a copy of the path with all the segments of every + /// subpath translated by the given offset. + Path shift(Offset offset) => _shift(offset.dx, offset.dy); + Path _shift(double dx, double dy) native "Path_shift"; + + /// Returns a copy of the path with all the segments of every + /// subpath transformed by the given matrix. + Path transform(Float64List matrix4) { + if (matrix4.length != 16) + throw new ArgumentError("[matrix4] must have 16 entries."); + return _transform(matrix4); + } + Path _transform(Float64List matrix4) native "Path_transform"; +} + +/// Styles to use for blurs in [MaskFilter] objects. +enum BlurStyle { + // These mirror SkBlurStyle and must be kept in sync. + + /// Fuzzy inside and outside. This is useful for painting shadows that are + /// offset from the shape that ostensibly is casting the shadow. + normal, + + /// Solid inside, fuzzy outside. This corresponds to drawing the shape, and + /// additionally drawing the blur. This can make objects appear brighter, + /// maybe even as if they were fluorescent. + solid, + + /// Nothing inside, fuzzy outside. This is useful for painting shadows for + /// partially transparent shapes, when they are painted separately but without + /// an offset, so that the shadow doesn't paint below the shape. + outer, + + /// Fuzzy inside, nothing outside. This can make shapes appear to be lit from + /// within. + inner, +} + +/// A mask filter to apply to shapes as they are painted. A mask filter is a +/// function that takes a bitmap of color pixels, and returns another bitmap of +/// color pixels. +/// +/// Instances of this class are used with [Paint.maskFilter] on [Paint] objects. +class MaskFilter extends NativeFieldWrapperClass2 { + /// Creates a mask filter that takes the shape being drawn and blurs it. + /// + /// This is commonly used to approximate shadows. + /// + /// The `style` argument controls the kind of effect to draw; see [BlurStyle]. + /// + /// The `sigma` argument controls the size of the effect. It is the standard + /// deviation of the Gaussian blur to apply. The value must be greater than + /// zero. The sigma corresponds to very roughly half the radius of the effect + /// in pixels. + /// + /// If the `ignoreTransform` argument is set, then the current transform is + /// ignored when computing the blur. This makes the operation cheaper, but + /// lowers the quality of the effect. In particular, it means that the sigma + /// will be relative to the device pixel coordinate space, rather than the + /// logical pixel coordinate space, which means the blur will look different + /// on different devices. + /// + /// If the `highQuality` argument is set, then the quality of the blur may be + /// slightly improved, at the cost of making the operation even more + /// expensive. + /// + /// Even in the best conditions and with the lowest quality settings, a blur + /// is an expensive operation and blurs should therefore be used sparingly. + MaskFilter.blur(BlurStyle style, double sigma, { + bool ignoreTransform: false, + bool highQuality: false + }) { + _constructor(style.index, sigma, _makeBlurFlags(ignoreTransform, highQuality)); + } + void _constructor(int style, double sigma, int flags) native "MaskFilter_constructor"; + + // Convert constructor parameters to the SkBlurMaskFilter::BlurFlags type. + static int _makeBlurFlags(bool ignoreTransform, bool highQuality) { + int flags = 0; + if (ignoreTransform) + flags |= 0x01; + if (highQuality) + flags |= 0x02; + return flags; + } +} + +/// A description of a color filter to apply when drawing a shape or compositing +/// a layer with a particular [Paint]. A color filter is a function that takes +/// two colors, and outputs one color. When applied during compositing, it is +/// independently applied to each pixel of the layer being drawn before the +/// entire layer is merged with the destination. +/// +/// Instances of this class are used with [Paint.colorFilter] on [Paint] +/// objects. +class ColorFilter { + /// Creates a color filter that applies the transfer mode given as the second + /// argument. The source color is the one given as the first argument, and the + /// destination color is the one from the layer being composited. + /// + /// The output of this filter is then composited into the background according + /// to the [Paint.transferMode], using the output of this filter as the source + /// and the background as the destination. + ColorFilter.mode(Color color, TransferMode transferMode) + : _color = color, _transferMode = transferMode; + + final Color _color; + final TransferMode _transferMode; + + @override + bool operator ==(dynamic other) { + if (other is! ColorFilter) + return false; + final ColorFilter typedOther = other; + return _color == typedOther._color && + _transferMode == typedOther._transferMode; + } + + @override + int get hashCode => hashValues(_color, _transferMode); + + @override + String toString() => "ColorFilter($_color, $TransferMode)"; +} + +/// A filter operation to apply to a raster image. +/// +/// See [SceneBuilder.pushBackdropFilter]. +class ImageFilter extends NativeFieldWrapperClass2 { + void _constructor() native "ImageFilter_constructor"; + + /// A source filter containing an image. + // ImageFilter.image({ Image image }) { + // _constructor(); + // _initImage(image); + // } + // void _initImage(Image image) native "ImageFilter_initImage"; + + /// A source filter containing a picture. + // ImageFilter.picture({ Picture picture }) { + // _constructor(); + // _initPicture(picture); + // } + // void _initPicture(Picture picture) native "ImageFilter_initPicture"; + + /// Creates an image filter that applies a Gaussian blur. + ImageFilter.blur({ double sigmaX: 0.0, double sigmaY: 0.0 }) { + _constructor(); + _initBlur(sigmaX, sigmaY); + } + void _initBlur(double sigmaX, double sigmaY) native "ImageFilter_initBlur"; +} + +/// Base class for objects such as [Gradient] and [ImageShader] which +/// correspond to shaders as used by [Paint.shader]. +abstract class Shader extends NativeFieldWrapperClass2 { } + +/// Defines what happens at the edge of the gradient. +enum TileMode { + /// Edge is clamped to the final color. + clamp, + + /// Edge is repeated from first color to last. + repeated, + + /// Edge is mirrored from last color to first. + mirror, +} + +Int32List _encodeColorList(List colors) { + final int colorCount = colors.length; + final Int32List result = new Int32List(colorCount); + for (int i = 0; i < colorCount; ++i) + result[i] = colors[i].value; + return result; +} + +Float32List _encodePointList(List points) { + final int pointCount = points.length; + final Float32List result = new Float32List(pointCount * 2); + for (int i = 0; i < pointCount; ++i) { + final int xIndex = i * 2; + final int yIndex = xIndex + 1; + final Point point = points[i]; + result[xIndex] = point.x; + result[yIndex] = point.y; + } + return result; +} + +/// A shader (as used by [Paint.shader]) that renders a color gradient. +/// +/// There are two useful types of gradients, created by [new Gradient.linear] +/// and [new Griadent.radial]. +class Gradient extends Shader { + /// Creates a Gradient object that is not initialized. + /// + /// Use the [Gradient.linear] or [Gradient.radial] constructors to + /// obtain a usable [Gradient] object. + Gradient(); + void _constructor() native "Gradient_constructor"; + + /// Creates a linear gradient from `endPoint[0]` to `endPoint[1]`. If + /// `colorStops` is provided, `colorStops[i]` is a number from 0 to 1 that + /// specifies where `color[i]` begins in the gradient. If `colorStops` is not + /// provided, then two stops at 0.0 and 1.0 are implied. The behavior before + /// and after the radius is described by the `tileMode` argument. + // TODO(mpcomplete): Consider passing a list of (color, colorStop) pairs + // instead. + Gradient.linear(List endPoints, + List colors, + [List colorStops = null, + TileMode tileMode = TileMode.clamp]) { + if (endPoints == null || endPoints.length != 2) + throw new ArgumentError("Expected exactly 2 [endPoints]."); + _validateColorStops(colors, colorStops); + final Float32List endPointsBuffer = _encodePointList(endPoints); + final Int32List colorsBuffer = _encodeColorList(colors); + final Float32List colorStopsBuffer = colorStops == null ? null : new Float32List.fromList(colorStops); + _constructor(); + _initLinear(endPointsBuffer, colorsBuffer, colorStopsBuffer, tileMode.index); + } + void _initLinear(Float32List endPoints, Int32List colors, Float32List colorStops, int tileMode) native "Gradient_initLinear"; + + /// Creates a radial gradient centered at `center` that ends at `radius` + /// distance from the center. If `colorStops` is provided, `colorStops[i]` is + /// a number from 0 to 1 that specifies where `color[i]` begins in the + /// gradient. If `colorStops` is not provided, then two stops at 0.0 and 1.0 + /// are implied. The behavior before and after the radius is described by the + /// `tileMode` argument. + Gradient.radial(Point center, + double radius, + List colors, + [List colorStops = null, + TileMode tileMode = TileMode.clamp]) { + _validateColorStops(colors, colorStops); + final Int32List colorsBuffer = _encodeColorList(colors); + final Float32List colorStopsBuffer = colorStops == null ? null : new Float32List.fromList(colorStops); + _constructor(); + _initRadial(center.x, center.y, radius, colorsBuffer, colorStopsBuffer, tileMode.index); + } + void _initRadial(double centerX, double centerY, double radius, Int32List colors, Float32List colorStops, int tileMode) native "Gradient_initRadial"; + + static void _validateColorStops(List colors, List colorStops) { + if (colorStops != null && colors.length != colorStops.length) + throw new ArgumentError("[colors] and [colorStops] parameters must be equal length."); + } +} + +/// A shader (as used by [Paint.shader]) that tiles an image. +class ImageShader extends Shader { + /// Creates an image-tiling shader. The first argument specifies the image to + /// tile. The second and third arguments specify the [TileMode] for the x + /// direction and y direction respectively. The fourth argument gives the + /// matrix to apply to the effect. All the arguments are required and must not + /// be null. + ImageShader(Image image, TileMode tmx, TileMode tmy, Float64List matrix4) { + if (image == null) + throw new ArgumentError("[image] argument cannot be null"); + if (tmx == null) + throw new ArgumentError("[tmx] argument cannot be null"); + if (tmy == null) + throw new ArgumentError("[tmy] argument cannot be null"); + if (matrix4 == null) + throw new ArgumentError("[matrix4] argument cannot be null"); + if (matrix4.length != 16) + throw new ArgumentError("[matrix4] must have 16 entries."); + _constructor(); + _initWithImage(image, tmx.index, tmy.index, matrix4); + } + void _constructor() native "ImageShader_constructor"; + void _initWithImage(Image image, int tmx, int tmy, Float64List matrix4) native "ImageShader_initWithImage"; +} + +/// Defines how a list of points is interpreted when drawing a set of triangles. +/// +/// Used by [Canvas.drawVertices]. +enum VertexMode { + /// Draw each sequence of three points as the vertices of a triangle. + triangles, + + /// Draw each sliding window of three points as the vertices of a triangle. + triangleStrip, + + /// Draw the first point and each sliding window of two points as the vertices of a triangle. + triangleFan, +} + +/// Defines how a list of points is interpreted when drawing a set of points. +/// +/// Used by [Canvas.drawPoints]. +enum PointMode { + /// Draw each point separately. + /// + /// If the [Paint.strokeCap] is [StrokeCat.round], then each point is drawn + /// as a circle with the diameter of the [Paint.strokeWidth], filled as + /// described by the [Paint] (ignoring [Paint.style]). + /// + /// Otherwise, each point is drawn as an axis-aligned square with sides of + /// length [Paint.strokeWidth], filled as described by the [Paint] (ignoring + /// [Paint.style]). + points, + + /// Draw each sequence of two points as a line segment. + /// + /// If the number of points is odd, then the last point is ignored. + /// + /// The lines are stroked as described by the [Paint] (ignoring + /// [Paint.style]). + lines, + + /// Draw the entire sequence of point as one line. + /// + /// The lines are stroked as described by the [Paint] (ignoring + /// [Paint.style]). + polygon, +} + +/// An interface for recording graphical operations. +/// +/// [Canvas] objects are used in creating [Picture] objects, which can +/// themselves be used with a [SceneBuilder] to build a [Scene]. In +/// normal usage, however, this is all handled by the framework. +/// +/// A canvas has a current transformation matrix which is applied to all +/// operations. Initially, the transformation matrix is the identity transform. +/// It can be modified using the [translate], [scale], [rotate], [skew], +/// [transform], and [setMatrix] methods. +/// +/// A canvas also has a current clip region which is applied to all operations. +/// Initially, the clip region is infinite. It can be modified using the +/// [clipRect], [clipRRect], and [clipPath] methods. +/// +/// The current transform and clip can be saved and restored using the stack +/// managed by the [save], [saveLayer], and [restore] methods. +class Canvas extends NativeFieldWrapperClass2 { + /// Creates a canvas for recording graphical operations into the + /// given picture recorder. + /// + /// Graphical operations that affect pixels entirely outside the given + /// cullRect might be discarded by the implementation. However, the + /// implementation might draw outside these bounds if, for example, a command + /// draws partially inside and outside the cullRect. To ensure that pixels + /// outside a given region are discarded, consider using a [clipRect]. + /// + /// To end the recording, call [PictureRecorder.endRecording] on the + /// given recorder. + Canvas(PictureRecorder recorder, Rect cullRect) { + if (recorder == null) + throw new ArgumentError('The given PictureRecorder was null.'); + if (recorder.isRecording) + throw new ArgumentError('The given PictureRecorder is already associated with another Canvas.'); + // TODO(ianh): throw if recorder is defunct (https://github.com/flutter/flutter/issues/2531) + _constructor(recorder, cullRect.left, cullRect.top, cullRect.right, cullRect.bottom); + } + void _constructor(PictureRecorder recorder, + double left, + double top, + double right, + double bottom) native "Canvas_constructor"; + + /// Saves a copy of the current transform and clip on the save stack. + /// + /// Call [restore] to pop the save stack. + void save() native "Canvas_save"; + + /// Saves a copy of the current transform and clip on the save stack, and then + /// creates a new group which subsequent calls will become a part of. When the + /// save stack is later popped, the group will be flattened into a layer and + /// have the given `paint`'s [Paint.colorFilter] and [Paint.transferMode] + /// applied. + /// + /// This lets you create composite effects, for example making a group of + /// drawing commands semi-transparent. Without using [saveLayer], each part of + /// the group would be painted individually, so where they overlap would be + /// darker than where they do not. By using [saveLayer] to group them + /// together, they can be drawn with an opaque color at first, and then the + /// entire group can be made transparent using the [saveLayer]'s paint. + /// + /// Call [restore] to pop the save stack and apply the paint to the group. + void saveLayer(Rect bounds, Paint paint) { + if (bounds == null) { + _saveLayerWithoutBounds(paint._objects, paint._data); + } else { + _saveLayer(bounds.left, bounds.top, bounds.right, bounds.bottom, + paint._objects, paint._data); + } + } + void _saveLayerWithoutBounds(List paintObjects, ByteData paintData) + native "Canvas_saveLayerWithoutBounds"; + // TODO(jackson): Paint should be optional, but making it optional causes crash + void _saveLayer(double left, + double top, + double right, + double bottom, + List paintObjects, + ByteData paintData) native "Canvas_saveLayer"; + + /// Pops the current save stack, if there is anything to pop. + /// Otherwise, does nothing. + /// + /// Use [save] and [saveLayer] to push state onto the stack. + /// + /// If the state was pushed with with [saveLayer], then this call will also + /// cause the new layer to be composited into the previous layer. + void restore() native "Canvas_restore"; + + /// Returns the number of items on the save stack, including the + /// initial state. This means it returns 1 for a clean canvas, and + /// that each call to [save] and [saveLayer] increments it, and that + /// each matching call to [restore] decrements it. + /// + /// This number cannot go below 1. + int getSaveCount() native "Canvas_getSaveCount"; + + /// Add a translation to the current transform, shifting the coordinate space + /// horizontally by the first argument and vertically by the second argument. + void translate(double dx, double dy) native "Canvas_translate"; + + /// Add an axis-aligned scale to the current transform, scaling by the first + /// argument in the horizontal direction and the second in the vertical + /// direction. + void scale(double sx, double sy) native "Canvas_scale"; + + /// Add a rotation to the current transform. The argument is in radians clockwise. + void rotate(double radians) native "Canvas_rotate"; + + /// Add an axis-aligned skew to the current transform, with the first argument + /// being the horizontal skew in radians clockwise around the origin, and the + /// second argument being the vertical skew in radians clockwise around the + /// origin. + void skew(double sx, double sy) native "Canvas_skew"; + + /// Multiply the current transform by the specified 4⨉4 transformation matrix + /// specified as a list of values in column-major order. + void transform(Float64List matrix4) { + if (matrix4.length != 16) + throw new ArgumentError("[matrix4] must have 16 entries."); + _transform(matrix4); + } + void _transform(Float64List matrix4) native "Canvas_transform"; + + /// Replaces the current transform with the specified 4⨉4 transformation + /// matrix specified as a list of values in column-major order. + void setMatrix(Float64List matrix4) { + if (matrix4.length != 16) + throw new ArgumentError("[matrix4] must have 16 entries."); + _setMatrix(matrix4); + } + void _setMatrix(Float64List matrix4) native "Canvas_setMatrix"; + + /// Reduces the clip region to the intersection of the current clip and the + /// given rectangle. + void clipRect(Rect rect) { + _clipRect(rect.left, rect.top, rect.right, rect.bottom); + } + void _clipRect(double left, + double top, + double right, + double bottom) native "Canvas_clipRect"; + + /// Reduces the clip region to the intersection of the current clip and the + /// given rounded rectangle. + void clipRRect(RRect rrect) => _clipRRect(rrect._value); + void _clipRRect(Float32List rrect) native "Canvas_clipRRect"; + + /// Reduces the clip region to the intersection of the current clip and the + /// given [Path]. + void clipPath(Path path) native "Canvas_clipPath"; + + /// Paints the given [Color] onto the canvas, applying the given + /// [TransferMode], with the given color being the source and the background + /// being the destination. + void drawColor(Color color, TransferMode transferMode) { + _drawColor(color.value, transferMode.index); + } + void _drawColor(int color, int transferMode) native "Canvas_drawColor"; + + /// Draws a line between the given [Point]s using the given paint. The line is + /// stroked, the value of the [Paint.style] is ignored for this call. + void drawLine(Point p1, Point p2, Paint paint) { + _drawLine(p1.x, p1.y, p2.x, p2.y, paint._objects, paint._data); + } + void _drawLine(double x1, + double y1, + double x2, + double y2, + List paintObjects, + ByteData paintData) native "Canvas_drawLine"; + + /// Fills the canvas with the given [Paint]. + /// + /// To fill the canvas with a solid color and transfer mode, consider + /// [drawColor] instead. + void drawPaint(Paint paint) => _drawPaint(paint._objects, paint._data); + void _drawPaint(List paintObjects, ByteData paintData) native "Canvas_drawPaint"; + + /// Draws a rectangle with the given [Paint]. Whether the rectangle is filled + /// or stroked (or both) is controlled by [Paint.style]. + void drawRect(Rect rect, Paint paint) { + _drawRect(rect.left, rect.top, rect.right, rect.bottom, + paint._objects, paint._data); + } + void _drawRect(double left, + double top, + double right, + double bottom, + List paintObjects, + ByteData paintData) native "Canvas_drawRect"; + + /// Draws a rounded rectangle with the given [Paint]. Whether the rectangle is + /// filled or stroked (or both) is controlled by [Paint.style]. + void drawRRect(RRect rrect, Paint paint) { + _drawRRect(rrect._value, paint._objects, paint._data); + } + void _drawRRect(Float32List rrect, + List paintObjects, + ByteData paintData) native "Canvas_drawRRect"; + + /// Draws a shape consisting of the difference between two rounded rectangles + /// with the given [Paint]. Whether this shape is filled or stroked (or both) + /// is controlled by [Paint.style]. + /// + /// This shape is almost but not quite entirely unlike an annulus. + void drawDRRect(RRect outer, RRect inner, Paint paint) { + _drawDRRect(outer._value, inner._value, paint._objects, paint._data); + } + void _drawDRRect(Float32List outer, + Float32List inner, + List paintObjects, + ByteData paintData) native "Canvas_drawDRRect"; + + /// Draws an axis-aligned oval that fills the given axis-aligned rectangle + /// with the given [Paint]. Whether the oval is filled or stroked (or both) is + /// controlled by [Paint.style]. + void drawOval(Rect rect, Paint paint) { + _drawOval(rect.left, rect.top, rect.right, rect.bottom, + paint._objects, paint._data); + } + void _drawOval(double left, + double top, + double right, + double bottom, + List paintObjects, + ByteData paintData) native "Canvas_drawOval"; + + /// Draws a circle centered at the point given by the first two arguments and + /// that has the radius given by the third argument, with the [Paint] given in + /// the fourth argument. Whether the circle is filled or stroked (or both) is + /// controlled by [Paint.style]. + void drawCircle(Point c, double radius, Paint paint) { + _drawCircle(c.x, c.y, radius, paint._objects, paint._data); + } + void _drawCircle(double x, + double y, + double radius, + List paintObjects, + ByteData paintData) native "Canvas_drawCircle"; + + /// Draws the given [Path] with the given [Paint]. Whether this shape is + /// filled or stroked (or both) is controlled by [Paint.style]. If the path is + /// filled, then subpaths within it are implicitly closed (see [Path.close]). + void drawPath(Path path, Paint paint) { + _drawPath(path, paint._objects, paint._data); + } + void _drawPath(Path path, + List paintObjects, + ByteData paintData) native "Canvas_drawPath"; + + /// Draws the given [Image] into the canvas with its top-left corner at the + /// given [Point]. The image is composited into the canvas using the given [Paint]. + void drawImage(Image image, Point p, Paint paint) { + _drawImage(image, p.x, p.y, paint._objects, paint._data); + } + void _drawImage(Image image, + double x, + double y, + List paintObjects, + ByteData paintData) native "Canvas_drawImage"; + + /// Draws the subset of the given image described by the `src` argument into + /// the canvas in the axis-aligned rectangle given by the `dst` argument. + /// + /// This might sample from outside the `src` rect by up to half the width of + /// an applied filter. + void drawImageRect(Image image, Rect src, Rect dst, Paint paint) { + _drawImageRect(image, + src.left, + src.top, + src.right, + src.bottom, + dst.left, + dst.top, + dst.right, + dst.bottom, + paint._objects, + paint._data); + } + void _drawImageRect(Image image, + double srcLeft, + double srcTop, + double srcRight, + double srcBottom, + double dstLeft, + double dstTop, + double dstRight, + double dstBottom, + List paintObjects, + ByteData paintData) native "Canvas_drawImageRect"; + + /// Draws the given [Image] into the canvas using the given [Paint]. + /// + /// The image is drawn in nine portions described by splitting the image by + /// drawing two horizontal lines and two vertical lines, where the `center` + /// argument describes the rectangle formed by the four points where these + /// four lines intersect each other. (This forms a 3-by-3 grid of regions, + /// the center region being described by the `center` argument.) + /// + /// The four regions in the corners are drawn, without scaling, in the four + /// corners of the destination rectangle described by `dst`. The remaining + /// five regions are drawn by stretching them to fit such that they exactly + /// cover the destination rectangle while maintaining their relative + /// positions. + void drawImageNine(Image image, Rect center, Rect dst, Paint paint) { + _drawImageNine(image, + center.left, + center.top, + center.right, + center.bottom, + dst.left, + dst.top, + dst.right, + dst.bottom, + paint._objects, + paint._data); + } + void _drawImageNine(Image image, + double centerLeft, + double centerTop, + double centerRight, + double centerBottom, + double dstLeft, + double dstTop, + double dstRight, + double dstBottom, + List paintObjects, + ByteData paintData) native "Canvas_drawImageNine"; + + /// Draw the given picture onto the canvas. To create a picture, see + /// [PictureRecorder]. + void drawPicture(Picture picture) native "Canvas_drawPicture"; + + /// Draws the text in the given paragraph into this canvas at the given offset. + /// + /// Valid only after [Paragraph.layout] has been called on the paragraph. + void drawParagraph(Paragraph paragraph, Offset offset) { + paragraph._paint(this, offset.dx, offset.dy); + } + + /// Draws a sequence of points according to the given [PointMode]. + void drawPoints(PointMode pointMode, List points, Paint paint) { + _drawPoints(paint._objects, paint._data, pointMode.index, _encodePointList(points)); + } + void _drawPoints(List paintObjects, + ByteData paintData, + int pointMode, + Float32List points) native "Canvas_drawPoints"; + + void drawVertices(VertexMode vertexMode, + List vertices, + List textureCoordinates, + List colors, + TransferMode transferMode, + List indicies, + Paint paint) { + final int vertexCount = vertices.length; + + if (textureCoordinates.isNotEmpty && textureCoordinates.length != vertexCount) + throw new ArgumentError("[vertices] and [textureCoordinates] lengths must match"); + if (colors.isNotEmpty && colors.length != vertexCount) + throw new ArgumentError("[vertices] and [colors] lengths must match"); + + final Float32List vertexBuffer = _encodePointList(vertices); + final Float32List textureCoordinateBuffer = textureCoordinates.isEmpty ? null : _encodePointList(textureCoordinates); + final Int32List colorBuffer = colors.isEmpty ? null : _encodeColorList(colors); + final Int32List indexBuffer = new Int32List.fromList(indicies); + + _drawVertices( + paint._objects, paint._data, vertexMode.index, vertexBuffer, + textureCoordinateBuffer, colorBuffer, transferMode.index, indexBuffer + ); + } + void _drawVertices(List paintObjects, + ByteData paintData, + int vertexMode, + Float32List vertices, + Float32List textureCoordinates, + Int32List colors, + int transferMode, + Int32List indicies) native "Canvas_drawVertices"; + + // TODO(eseidel): Paint should be optional, but optional doesn't work. + void drawAtlas(Image atlas, + List transforms, + List rects, + List colors, + TransferMode transferMode, + Rect cullRect, + Paint paint) { + final int rectCount = rects.length; + + if (transforms.length != rectCount) + throw new ArgumentError("[transforms] and [rects] lengths must match"); + if (colors.isNotEmpty && colors.length != rectCount) + throw new ArgumentError("if supplied, [colors] length must match that of [transforms] and [rects]"); + + final Float32List rstTransformBuffer = new Float32List(rectCount * 4); + final Float32List rectBuffer = new Float32List(rectCount * 4); + + for (int i = 0; i < rectCount; ++i) { + final int index0 = i * 4; + final int index1 = index0 + 1; + final int index2 = index0 + 2; + final int index3 = index0 + 3; + final RSTransform rstTransform = transforms[i]; + final Rect rect = rects[i]; + rstTransformBuffer[index0] = rstTransform.scos; + rstTransformBuffer[index1] = rstTransform.ssin; + rstTransformBuffer[index2] = rstTransform.tx; + rstTransformBuffer[index3] = rstTransform.ty; + rectBuffer[index0] = rect.left; + rectBuffer[index1] = rect.top; + rectBuffer[index2] = rect.right; + rectBuffer[index3] = rect.bottom; + } + + final Int32List colorBuffer = colors.isEmpty ? null : _encodeColorList(colors); + final Float32List cullRectBuffer = cullRect?._value; + + _drawAtlas( + paint._objects, paint._data, atlas, rstTransformBuffer, rectBuffer, + colorBuffer, transferMode.index, cullRectBuffer + ); + } + void _drawAtlas(List paintObjects, + ByteData paintData, + Image atlas, + Float32List rstTransforms, + Float32List rects, + Int32List colors, + int transferMode, + Float32List cullRect) native "Canvas_drawAtlas"; +} + +/// An object representing a sequence of recorded graphical operations. +/// +/// To create a [Picture], use a [PictureRecorder]. +/// +/// A [Picture] can be placed in a [Scene] using a [SceneBuilder], via +/// the [SceneBuilder.addPicture] method. A [Picture] can also be +/// drawn into a [Canvas], using the [Canvas.drawPicture] method. +abstract class Picture extends NativeFieldWrapperClass2 { + /// Creates an uninitialized Picture object. + /// + /// Calling the Picture constructor directly will not create a useable + /// object. To create a Picture object, use a [PictureRecorder]. + Picture(); // (this constructor is here just so we can document it) + + /// Release the resources used by this object. The object is no longer usable + /// after this method is called. + void dispose() native "Picture_dispose"; +} + +/// Records a [Picture] containing a sequence of graphical operations. +/// +/// To begin recording, construct a [Canvas] to record the commands. +/// To end recording, use the [PictureRecorder.endRecording] method. +class PictureRecorder extends NativeFieldWrapperClass2 { + /// Creates a new idle PictureRecorder. To associate it with a + /// [Canvas] and begin recording, pass this [PictureRecorder] to the + /// [Canvas] constructor. + PictureRecorder() { _constructor(); } + void _constructor() native "PictureRecorder_constructor"; + + /// Whether this object is currently recording commands. + /// + /// Specifically, this returns true if a [Canvas] object has been + /// created to record commands and recording has not yet ended via a + /// call to [endRecording], and false if either this + /// [PictureRecorder] has not yet been associated with a [Canvas], + /// or the [endRecording] method has already been called. + bool get isRecording native "PictureRecorder_isRecording"; + + /// Finishes recording graphical operations. + /// + /// Returns a picture containing the graphical operations that have been + /// recorded thus far. After calling this function, both the picture recorder + /// and the canvas objects are invalid and cannot be used further. + /// + /// Returns null if the PictureRecorder is not associated with a canvas. + Picture endRecording() native "PictureRecorder_endRecording"; +} diff --git a/engine/src/flutter/lib/ui/painting/canvas.cc b/engine/src/flutter/lib/ui/painting/canvas.cc new file mode 100644 index 0000000000..ecbcffc2a0 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/canvas.cc @@ -0,0 +1,398 @@ +// 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 "flutter/lib/ui/painting/canvas.h" + +#include + +#include "flutter/lib/ui/painting/image.h" +#include "flutter/lib/ui/painting/matrix.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/skia/include/core/SkCanvas.h" + +namespace blink { + +static void Canvas_constructor(Dart_NativeArguments args) { + DartCallConstructor(&Canvas::Create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, Canvas); + +#define FOR_EACH_BINDING(V) \ + V(Canvas, save) \ + V(Canvas, saveLayerWithoutBounds) \ + V(Canvas, saveLayer) \ + V(Canvas, restore) \ + V(Canvas, getSaveCount) \ + V(Canvas, translate) \ + V(Canvas, scale) \ + V(Canvas, rotate) \ + V(Canvas, skew) \ + V(Canvas, transform) \ + V(Canvas, setMatrix) \ + V(Canvas, clipRect) \ + V(Canvas, clipRRect) \ + V(Canvas, clipPath) \ + V(Canvas, drawColor) \ + V(Canvas, drawLine) \ + V(Canvas, drawPaint) \ + V(Canvas, drawRect) \ + V(Canvas, drawRRect) \ + V(Canvas, drawDRRect) \ + V(Canvas, drawOval) \ + V(Canvas, drawCircle) \ + V(Canvas, drawPath) \ + V(Canvas, drawImage) \ + V(Canvas, drawImageRect) \ + V(Canvas, drawImageNine) \ + V(Canvas, drawPicture) \ + V(Canvas, drawPoints) \ + V(Canvas, drawVertices) \ + V(Canvas, drawAtlas) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void Canvas::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({{"Canvas_constructor", Canvas_constructor, 6, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +ftl::RefPtr Canvas::Create(PictureRecorder* recorder, + double left, + double top, + double right, + double bottom) { + FTL_DCHECK(recorder); + FTL_DCHECK(!recorder->isRecording()); + ftl::RefPtr canvas = ftl::MakeRefCounted( + recorder->BeginRecording(SkRect::MakeLTRB(left, top, right, bottom))); + recorder->set_canvas(canvas); + return canvas; +} + +Canvas::Canvas(SkCanvas* canvas) : canvas_(canvas) {} + +Canvas::~Canvas() {} + +void Canvas::save() { + if (!canvas_) + return; + canvas_->save(); +} + +void Canvas::saveLayerWithoutBounds(const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->saveLayer(nullptr, paint.paint()); +} + +void Canvas::saveLayer(double left, + double top, + double right, + double bottom, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + SkRect bounds = SkRect::MakeLTRB(left, top, right, bottom); + canvas_->saveLayer(&bounds, paint.paint()); +} + +void Canvas::restore() { + if (!canvas_) + return; + canvas_->restore(); +} + +int Canvas::getSaveCount() { + if (!canvas_) + return 0; + return canvas_->getSaveCount(); +} + +void Canvas::translate(double dx, double dy) { + if (!canvas_) + return; + canvas_->translate(dx, dy); +} + +void Canvas::scale(double sx, double sy) { + if (!canvas_) + return; + canvas_->scale(sx, sy); +} + +void Canvas::rotate(double radians) { + if (!canvas_) + return; + canvas_->rotate(radians * 180.0 / M_PI); +} + +void Canvas::skew(double sx, double sy) { + if (!canvas_) + return; + canvas_->skew(sx, sy); +} + +void Canvas::transform(const tonic::Float64List& matrix4) { + if (!canvas_) + return; + canvas_->concat(ToSkMatrix(matrix4)); +} + +void Canvas::setMatrix(const tonic::Float64List& matrix4) { + if (!canvas_) + return; + canvas_->setMatrix(ToSkMatrix(matrix4)); +} + +void Canvas::clipRect(double left, double top, double right, double bottom) { + if (!canvas_) + return; + canvas_->clipRect(SkRect::MakeLTRB(left, top, right, bottom)); +} + +void Canvas::clipRRect(const RRect& rrect) { + if (!canvas_) + return; + canvas_->clipRRect(rrect.sk_rrect, SkRegion::kIntersect_Op); +} + +void Canvas::clipPath(const CanvasPath* path) { + if (!canvas_) + return; + canvas_->clipPath(path->path(), SkRegion::kIntersect_Op); +} + +void Canvas::drawColor(SkColor color, SkXfermode::Mode transfer_mode) { + if (!canvas_) + return; + canvas_->drawColor(color, transfer_mode); +} + +void Canvas::drawLine(double x1, + double y1, + double x2, + double y2, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->drawLine(x1, y1, x2, y2, *paint.paint()); +} + +void Canvas::drawPaint(const Paint& paint, const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->drawPaint(*paint.paint()); +} + +void Canvas::drawRect(double left, + double top, + double right, + double bottom, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->drawRect(SkRect::MakeLTRB(left, top, right, bottom), *paint.paint()); +} + +void Canvas::drawRRect(const RRect& rrect, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->drawRRect(rrect.sk_rrect, *paint.paint()); +} + +void Canvas::drawDRRect(const RRect& outer, + const RRect& inner, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->drawDRRect(outer.sk_rrect, inner.sk_rrect, *paint.paint()); +} + +void Canvas::drawOval(double left, + double top, + double right, + double bottom, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->drawOval(SkRect::MakeLTRB(left, top, right, bottom), *paint.paint()); +} + +void Canvas::drawCircle(double x, + double y, + double radius, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + canvas_->drawCircle(x, y, radius, *paint.paint()); +} + +void Canvas::drawPath(const CanvasPath* path, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + FTL_DCHECK(path); + canvas_->drawPath(path->path(), *paint.paint()); +} + +void Canvas::drawImage(const CanvasImage* image, + double x, + double y, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + FTL_DCHECK(image); + canvas_->drawImage(image->image(), x, y, paint.paint()); +} + +void Canvas::drawImageRect(const CanvasImage* image, + double src_left, + double src_top, + double src_right, + double src_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + FTL_DCHECK(image); + SkRect src = SkRect::MakeLTRB(src_left, src_top, src_right, src_bottom); + SkRect dst = SkRect::MakeLTRB(dst_left, dst_top, dst_right, dst_bottom); + canvas_->drawImageRect(image->image(), src, dst, paint.paint(), + SkCanvas::kFast_SrcRectConstraint); +} + +void Canvas::drawImageNine(const CanvasImage* image, + double center_left, + double center_top, + double center_right, + double center_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data) { + if (!canvas_) + return; + FTL_DCHECK(image); + SkRect center = + SkRect::MakeLTRB(center_left, center_top, center_right, center_bottom); + SkIRect icenter; + center.round(&icenter); + SkRect dst = SkRect::MakeLTRB(dst_left, dst_top, dst_right, dst_bottom); + canvas_->drawImageNine(image->image(), icenter, dst, paint.paint()); +} + +void Canvas::drawPicture(Picture* picture) { + if (!canvas_) + return; + FTL_DCHECK(picture); + canvas_->drawPicture(picture->picture().get()); +} + +void Canvas::drawPoints(const Paint& paint, + const PaintData& paint_data, + SkCanvas::PointMode point_mode, + const tonic::Float32List& points) { + if (!canvas_) + return; + + static_assert(sizeof(SkPoint) == sizeof(float) * 2, + "SkPoint doesn't use floats."); + + canvas_->drawPoints(point_mode, + points.num_elements() / 2, // SkPoints have two floats. + reinterpret_cast(points.data()), + *paint.paint()); +} + +void Canvas::drawVertices(const Paint& paint, + const PaintData& paint_data, + SkCanvas::VertexMode vertex_mode, + const tonic::Float32List& vertices, + const tonic::Float32List& texture_coordinates, + const tonic::Int32List& colors, + SkXfermode::Mode transfer_mode, + const tonic::Int32List& indices) { + if (!canvas_) + return; + + sk_sp transfer_mode_ptr = SkXfermode::Make(transfer_mode); + + std::vector indices16; + indices16.reserve(indices.num_elements()); + for (int i = 0; i < indices.num_elements(); ++i) + indices16.push_back(indices.data()[i]); + + static_assert(sizeof(SkPoint) == sizeof(float) * 2, + "SkPoint doesn't use floats."); + static_assert(sizeof(SkColor) == sizeof(int32_t), + "SkColor doesn't use int32_t."); + + canvas_->drawVertices( + vertex_mode, + vertices.num_elements() / 2, // SkPoints have two floats. + reinterpret_cast(vertices.data()), + reinterpret_cast(texture_coordinates.data()), + reinterpret_cast(colors.data()), transfer_mode_ptr.get(), + indices16.empty() ? nullptr : indices16.data(), indices16.size(), + *paint.paint()); +} + +void Canvas::drawAtlas(const Paint& paint, + const PaintData& paint_data, + CanvasImage* atlas, + const tonic::Float32List& transforms, + const tonic::Float32List& rects, + const tonic::Int32List& colors, + SkXfermode::Mode transfer_mode, + const tonic::Float32List& cull_rect) { + if (!canvas_) + return; + + sk_sp skImage = atlas->image(); + + static_assert(sizeof(SkRSXform) == sizeof(float) * 4, + "SkRSXform doesn't use floats."); + static_assert(sizeof(SkRect) == sizeof(float) * 4, + "SkRect doesn't use floats."); + + canvas_->drawAtlas( + skImage.get(), reinterpret_cast(transforms.data()), + reinterpret_cast(rects.data()), + reinterpret_cast(colors.data()), + rects.num_elements() / 4, // SkRect have four floats. + transfer_mode, reinterpret_cast(cull_rect.data()), + paint.paint()); +} + +void Canvas::Clear() { + canvas_ = nullptr; +} + +bool Canvas::IsRecording() const { + return !!canvas_; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/canvas.h b/engine/src/flutter/lib/ui/painting/canvas.h new file mode 100644 index 0000000000..95b22f11fd --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/canvas.h @@ -0,0 +1,180 @@ +// 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 FLUTTER_LIB_UI_PAINTING_CANVAS_H_ +#define FLUTTER_LIB_UI_PAINTING_CANVAS_H_ + +#include "flutter/lib/ui/painting/paint.h" +#include "flutter/lib/ui/painting/path.h" +#include "flutter/lib/ui/painting/picture.h" +#include "flutter/lib/ui/painting/picture_recorder.h" +#include "flutter/lib/ui/painting/rrect.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/typed_data/float32_list.h" +#include "lib/tonic/typed_data/float64_list.h" +#include "lib/tonic/typed_data/int32_list.h" +#include "third_party/skia/include/core/SkCanvas.h" + +namespace tonic { +class DartLibraryNatives; + +template <> +struct DartConverter + : public DartConverterInteger {}; + +template <> +struct DartConverter + : public DartConverterInteger {}; + +} // namespace tonic + +namespace blink { +class CanvasImage; + +class Canvas : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(Canvas); + + public: + static ftl::RefPtr Create(PictureRecorder* recorder, + double left, + double top, + double right, + double bottom); + + ~Canvas() override; + + void save(); + void saveLayerWithoutBounds(const Paint& paint, const PaintData& paint_data); + void saveLayer(double left, + double top, + double right, + double bottom, + const Paint& paint, + const PaintData& paint_data); + void restore(); + int getSaveCount(); + + void translate(double dx, double dy); + void scale(double sx, double sy); + void rotate(double radians); + void skew(double sx, double sy); + void transform(const tonic::Float64List& matrix4); + void setMatrix(const tonic::Float64List& matrix4); + + void clipRect(double left, double top, double right, double bottom); + void clipRRect(const RRect& rrect); + void clipPath(const CanvasPath* path); + + void drawColor(SkColor color, SkXfermode::Mode transfer_mode); + void drawLine(double x1, + double y1, + double x2, + double y2, + const Paint& paint, + const PaintData& paint_data); + void drawPaint(const Paint& paint, const PaintData& paint_data); + void drawRect(double left, + double top, + double right, + double bottom, + const Paint& paint, + const PaintData& paint_data); + void drawRRect(const RRect& rrect, + const Paint& paint, + const PaintData& paint_data); + void drawDRRect(const RRect& outer, + const RRect& inner, + const Paint& paint, + const PaintData& paint_data); + void drawOval(double left, + double top, + double right, + double bottom, + const Paint& paint, + const PaintData& paint_data); + void drawCircle(double x, + double y, + double radius, + const Paint& paint, + const PaintData& paint_data); + void drawPath(const CanvasPath* path, + const Paint& paint, + const PaintData& paint_data); + void drawImage(const CanvasImage* image, + double x, + double y, + const Paint& paint, + const PaintData& paint_data); + void drawImageRect(const CanvasImage* image, + double src_left, + double src_top, + double src_right, + double src_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data); + void drawImageNine(const CanvasImage* image, + double center_left, + double center_top, + double center_right, + double center_bottom, + double dst_left, + double dst_top, + double dst_right, + double dst_bottom, + const Paint& paint, + const PaintData& paint_data); + void drawPicture(Picture* picture); + + // The paint argument is first for the following functions because Paint + // unwraps a number of C++ objects. Once we create a view unto a + // Float32List, we cannot re-enter the VM to unwrap objects. That means we + // either need to process the paint argument first. + + void drawPoints(const Paint& paint, + const PaintData& paint_data, + SkCanvas::PointMode point_mode, + const tonic::Float32List& points); + + void drawVertices(const Paint& paint, + const PaintData& paint_data, + SkCanvas::VertexMode vertex_mode, + const tonic::Float32List& vertices, + const tonic::Float32List& texture_coordinates, + const tonic::Int32List& colors, + SkXfermode::Mode transfer_mode, + const tonic::Int32List& indices); + + void drawAtlas(const Paint& paint, + const PaintData& paint_data, + CanvasImage* atlas, + const tonic::Float32List& transforms, + const tonic::Float32List& rects, + const tonic::Int32List& colors, + SkXfermode::Mode transfer_mode, + const tonic::Float32List& cull_rect); + + SkCanvas* canvas() const { return canvas_; } + void Clear(); + bool IsRecording() const; + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit Canvas(SkCanvas* canvas); + + // The SkCanvas is supplied by a call to SkPictureRecorder::beginRecording, + // which does not transfer ownership. For this reason, we hold a raw + // pointer and manually set to null in Clear. + SkCanvas* canvas_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_CANVAS_H_ diff --git a/engine/src/flutter/lib/ui/painting/gradient.cc b/engine/src/flutter/lib/ui/painting/gradient.cc new file mode 100644 index 0000000000..46d241984f --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/gradient.cc @@ -0,0 +1,79 @@ +// 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 "flutter/lib/ui/painting/gradient.h" + +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" + +namespace blink { + +typedef CanvasGradient + Gradient; // Because the C++ name doesn't match the Dart name. + +static void Gradient_constructor(Dart_NativeArguments args) { + DartCallConstructor(&CanvasGradient::Create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, Gradient); + +#define FOR_EACH_BINDING(V) \ + V(Gradient, initLinear) \ + V(Gradient, initRadial) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void CanvasGradient::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({{"Gradient_constructor", Gradient_constructor, 1, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +ftl::RefPtr CanvasGradient::Create() { + return ftl::MakeRefCounted(); +} + +void CanvasGradient::initLinear(const tonic::Float32List& end_points, + const tonic::Int32List& colors, + const tonic::Float32List& color_stops, + SkShader::TileMode tile_mode) { + FTL_DCHECK(end_points.num_elements() == 4); + FTL_DCHECK(colors.num_elements() == color_stops.num_elements() || + color_stops.data() == nullptr); + + static_assert(sizeof(SkPoint) == sizeof(float) * 2, + "SkPoint doesn't use floats."); + static_assert(sizeof(SkColor) == sizeof(int32_t), + "SkColor doesn't use int32_t."); + + set_shader(SkGradientShader::MakeLinear( + reinterpret_cast(end_points.data()), + reinterpret_cast(colors.data()), color_stops.data(), + colors.num_elements(), tile_mode)); +} + +void CanvasGradient::initRadial(double center_x, + double center_y, + double radius, + const tonic::Int32List& colors, + const tonic::Float32List& color_stops, + SkShader::TileMode tile_mode) { + FTL_DCHECK(colors.num_elements() * 2 == color_stops.num_elements() || + color_stops.data() == nullptr); + + static_assert(sizeof(SkColor) == sizeof(int32_t), + "SkColor doesn't use int32_t."); + + set_shader(SkGradientShader::MakeRadial( + SkPoint::Make(center_x, center_y), radius, + reinterpret_cast(colors.data()), color_stops.data(), + colors.num_elements(), tile_mode)); +} + +CanvasGradient::CanvasGradient() : Shader(nullptr) {} + +CanvasGradient::~CanvasGradient() {} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/gradient.h b/engine/src/flutter/lib/ui/painting/gradient.h new file mode 100644 index 0000000000..a706f609b2 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/gradient.h @@ -0,0 +1,55 @@ +// 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 FLUTTER_LIB_UI_PAINTING_GRADIENT_H_ +#define FLUTTER_LIB_UI_PAINTING_GRADIENT_H_ + +#include "flutter/lib/ui/painting/shader.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/typed_data/float32_list.h" +#include "lib/tonic/typed_data/int32_list.h" +#include "third_party/skia/include/effects/SkGradientShader.h" + +namespace tonic { +class DartLibraryNatives; + +template <> +struct DartConverter + : public DartConverterInteger {}; + +} // namspace tonic + +namespace blink { + +static_assert(SkShader::kTileModeCount == 3, "Need to update tile mode enum"); + +class CanvasGradient : public Shader { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(CanvasGradient); + + public: + ~CanvasGradient() override; + static ftl::RefPtr Create(); + + void initLinear(const tonic::Float32List& end_points, + const tonic::Int32List& colors, + const tonic::Float32List& color_stops, + SkShader::TileMode tile_mode); + + void initRadial(double center_x, + double center_y, + double radius, + const tonic::Int32List& colors, + const tonic::Float32List& color_stops, + SkShader::TileMode tile_mode); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + CanvasGradient(); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_GRADIENT_H_ diff --git a/engine/src/flutter/lib/ui/painting/image.cc b/engine/src/flutter/lib/ui/painting/image.cc new file mode 100644 index 0000000000..9da6310d23 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image.cc @@ -0,0 +1,37 @@ +// Copyright 2013 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 "flutter/lib/ui/painting/image.h" + +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" + +namespace blink { + +typedef CanvasImage Image; + +IMPLEMENT_WRAPPERTYPEINFO(ui, Image); + +#define FOR_EACH_BINDING(V) \ + V(Image, width) \ + V(Image, height) \ + V(Image, dispose) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void CanvasImage::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +CanvasImage::CanvasImage() {} + +CanvasImage::~CanvasImage() {} + +void CanvasImage::dispose() { + ClearDartWrapper(); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/image.h b/engine/src/flutter/lib/ui/painting/image.h new file mode 100644 index 0000000000..4600d18296 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image.h @@ -0,0 +1,45 @@ +// Copyright 2013 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 FLUTTER_LIB_UI_PAINTING_IMAGE_H_ +#define FLUTTER_LIB_UI_PAINTING_IMAGE_H_ + +#include "lib/tonic/dart_wrappable.h" +#include "third_party/skia/include/core/SkImage.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class CanvasImage final : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(CanvasImage); + + public: + ~CanvasImage() override; + static ftl::RefPtr Create() { + return ftl::MakeRefCounted(); + } + + int width() { return image_->width(); } + int height() { return image_->height(); } + void dispose(); + + const sk_sp& image() const { return image_; } + void set_image(sk_sp image) { image_ = std::move(image); } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + CanvasImage(); + + sk_sp image_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_H_ diff --git a/engine/src/flutter/lib/ui/painting/image_decoding.cc b/engine/src/flutter/lib/ui/painting/image_decoding.cc new file mode 100644 index 0000000000..a87bf9f191 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_decoding.cc @@ -0,0 +1,151 @@ +// 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 "flutter/lib/ui/painting/image_decoding.h" + +#include "flutter/flow/texture_image.h" +#include "flutter/lib/ui/painting/image.h" +#include "flutter/lib/ui/painting/resource_context.h" +#include "flutter/glue/drain_data_pipe_job.h" +#include "flutter/glue/movable_wrapper.h" +#include "flutter/glue/trace_event.h" +#include "lib/ftl/tasks/task_runner.h" +#include "lib/tonic/dart_persistent_value.h" +#include "lib/tonic/logging/dart_invoke.h" +#include "lib/tonic/mojo_converter.h" +#include "lib/tonic/typed_data/uint8_list.h" +#include "flutter/sky/engine/public/platform/Platform.h" +#include "flutter/sky/engine/wtf/PassOwnPtr.h" +#include "third_party/skia/include/core/SkImageGenerator.h" + +using tonic::DartInvoke; +using tonic::DartPersistentValue; +using tonic::DartState; +using tonic::ToDart; + +namespace blink { +namespace { + +sk_sp DecodeImage(std::vector buffer) { + TRACE_EVENT0("blink", "DecodeImage"); + + if (buffer.empty()) { + return nullptr; + } + + sk_sp sk_data = SkData::MakeWithoutCopy(buffer.data(), buffer.size()); + + if (sk_data == nullptr) { + return nullptr; + } + + std::unique_ptr generator( + SkImageGenerator::NewFromEncoded(sk_data.get())); + + if (generator == nullptr) { + return nullptr; + } + + GrContext* context = ResourceContext::Get(); + + // First, try to create a texture image from the generator. + if (sk_sp image = flow::TextureImageCreate(context, *generator)) { + return image; + } + + // The, as a fallback, try to create a regular Skia managed image. These + // don't require a context ready. + return flow::BitmapImageCreate(*generator); +} + +void InvokeImageCallback(sk_sp image, + PassOwnPtr callback) { + tonic::DartState* dart_state = callback->dart_state().get(); + if (!dart_state) + return; + tonic::DartState::Scope scope(dart_state); + if (!image) { + DartInvoke(callback->value(), {Dart_Null()}); + } else { + ftl::RefPtr resultImage = CanvasImage::Create(); + resultImage->set_image(std::move(image)); + DartInvoke(callback->value(), {ToDart(resultImage)}); + } +} + +void DecodeImageAndInvokeImageCallback(PassOwnPtr callback, + std::vector buffer) { + sk_sp image = DecodeImage(std::move(buffer)); + Platform::current()->GetUITaskRunner()->PostTask( + [callback, image]() { InvokeImageCallback(image, callback); }); +} + +void DecodeImageFromDataPipe(Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + + auto consumer = glue::WrapMovable( + tonic::DartConverter::FromArguments( + args, 0, exception)); + if (exception) { + Dart_ThrowException(exception); + return; + } + + Dart_Handle callback_handle = Dart_GetNativeArgument(args, 1); + if (!Dart_IsClosure(callback_handle)) { + Dart_ThrowException(ToDart("Callback must be a function")); + return; + } + + PassOwnPtr callback = + adoptPtr(new DartPersistentValue(DartState::Current(), callback_handle)); + + Platform::current()->GetIOTaskRunner()->PostTask( + [callback, consumer]() mutable { + glue::DrainDataPipeJob* job = nullptr; + job = new glue::DrainDataPipeJob( + consumer.Unwrap(), [callback, job](std::vector buffer) { + delete job; + DecodeImageAndInvokeImageCallback(callback, std::move(buffer)); + }); + }); +} + +void DecodeImageFromList(Dart_NativeArguments args) { + Dart_Handle exception = nullptr; + + tonic::Uint8List list = + tonic::DartConverter::FromArguments(args, 0, exception); + if (exception) { + Dart_ThrowException(exception); + return; + } + + Dart_Handle callback_handle = Dart_GetNativeArgument(args, 1); + if (!Dart_IsClosure(callback_handle)) { + Dart_ThrowException(ToDart("Callback must be a function")); + return; + } + PassOwnPtr callback = + adoptPtr(new DartPersistentValue(DartState::Current(), callback_handle)); + + const char* bytes = reinterpret_cast(list.data()); + PassOwnPtr> buffer = + adoptPtr(new std::vector(bytes, bytes + list.num_elements())); + + Platform::current()->GetIOTaskRunner()->PostTask([callback, buffer]() { + DecodeImageAndInvokeImageCallback(callback, std::move(*buffer)); + }); +} + +} // namespace + +void ImageDecoding::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({ + {"decodeImageFromDataPipe", DecodeImageFromDataPipe, 2, true}, + {"decodeImageFromList", DecodeImageFromList, 2, true}, + }); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/image_decoding.h b/engine/src/flutter/lib/ui/painting/image_decoding.h new file mode 100644 index 0000000000..994d40537f --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_decoding.h @@ -0,0 +1,19 @@ +// 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 FLUTTER_LIB_UI_PAINTING_IMAGE_DECODING_H_ +#define FLUTTER_LIB_UI_PAINTING_IMAGE_DECODING_H_ + +#include "lib/tonic/dart_library_natives.h" + +namespace blink { + +class ImageDecoding { + public: + static void RegisterNatives(tonic::DartLibraryNatives* natives); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_DECODING_H_ diff --git a/engine/src/flutter/lib/ui/painting/image_filter.cc b/engine/src/flutter/lib/ui/painting/image_filter.cc new file mode 100644 index 0000000000..04b44932c2 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_filter.cc @@ -0,0 +1,56 @@ +// Copyright 2016 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 "flutter/lib/ui/painting/image_filter.h" + +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "third_party/skia/include/effects/SkBlurImageFilter.h" +#include "third_party/skia/include/effects/SkImageSource.h" +#include "third_party/skia/include/effects/SkPictureImageFilter.h" + +namespace blink { + +static void ImageFilter_constructor(Dart_NativeArguments args) { + DartCallConstructor(&ImageFilter::Create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, ImageFilter); + +#define FOR_EACH_BINDING(V) \ + V(ImageFilter, initImage) \ + V(ImageFilter, initPicture) \ + V(ImageFilter, initBlur) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void ImageFilter::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register( + {{"ImageFilter_constructor", ImageFilter_constructor, 1, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +ftl::RefPtr ImageFilter::Create() { + return ftl::MakeRefCounted(); +} + +ImageFilter::ImageFilter() {} + +ImageFilter::~ImageFilter() {} + +void ImageFilter::initImage(CanvasImage* image) { + filter_ = SkImageSource::Make(image->image()); +} + +void ImageFilter::initPicture(Picture* picture) { + filter_ = SkPictureImageFilter::Make(picture->picture()); +} + +void ImageFilter::initBlur(double sigma_x, double sigma_y) { + filter_ = SkBlurImageFilter::Make(sigma_x, sigma_y, nullptr); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/image_filter.h b/engine/src/flutter/lib/ui/painting/image_filter.h new file mode 100644 index 0000000000..77973787f2 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_filter.h @@ -0,0 +1,40 @@ +// Copyright 2016 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 FLUTTER_LIB_UI_PAINTING_IMAGE_FILTER_H_ +#define FLUTTER_LIB_UI_PAINTING_IMAGE_FILTER_H_ + +#include "flutter/lib/ui/painting/image.h" +#include "flutter/lib/ui/painting/picture.h" +#include "lib/tonic/dart_wrappable.h" +#include "third_party/skia/include/core/SkImageFilter.h" + +namespace blink { + +class ImageFilter : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(ImageFilter); + + public: + ~ImageFilter() override; + static ftl::RefPtr Create(); + + void initImage(CanvasImage* image); + void initPicture(Picture*); + void initBlur(double sigma_x, double sigma_y); + + const sk_sp& filter() { return filter_; } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + ImageFilter(); + + sk_sp filter_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_FILTER_H_ diff --git a/engine/src/flutter/lib/ui/painting/image_shader.cc b/engine/src/flutter/lib/ui/painting/image_shader.cc new file mode 100644 index 0000000000..d850cd9f1f --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_shader.cc @@ -0,0 +1,50 @@ +// 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 "flutter/lib/ui/painting/image_shader.h" + +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" + +namespace blink { + +static void ImageShader_constructor(Dart_NativeArguments args) { + DartCallConstructor(&ImageShader::Create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, ImageShader); + +#define FOR_EACH_BINDING(V) V(ImageShader, initWithImage) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void ImageShader::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register( + {{"ImageShader_constructor", ImageShader_constructor, 1, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +ftl::RefPtr ImageShader::Create() { + return ftl::MakeRefCounted(); +} + +void ImageShader::initWithImage(CanvasImage* image, + SkShader::TileMode tmx, + SkShader::TileMode tmy, + const tonic::Float64List& matrix4) { + FTL_DCHECK(image != NULL); + SkMatrix sk_matrix = ToSkMatrix(matrix4); + SkBitmap bitmap; + image->image()->asLegacyBitmap(&bitmap, SkImage::kRO_LegacyBitmapMode); + + set_shader(SkShader::MakeBitmapShader(bitmap, tmx, tmy, &sk_matrix)); +} + +ImageShader::ImageShader() : Shader(nullptr) {} + +ImageShader::~ImageShader() {} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/image_shader.h b/engine/src/flutter/lib/ui/painting/image_shader.h new file mode 100644 index 0000000000..3a1602f841 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/image_shader.h @@ -0,0 +1,44 @@ +// 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 FLUTTER_LIB_UI_PAINTING_IMAGE_SHADER_H_ +#define FLUTTER_LIB_UI_PAINTING_IMAGE_SHADER_H_ + +#include "flutter/lib/ui/painting/gradient.h" +#include "flutter/lib/ui/painting/image.h" +#include "flutter/lib/ui/painting/matrix.h" +#include "flutter/lib/ui/painting/shader.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/typed_data/float64_list.h" +#include "third_party/skia/include/core/SkMatrix.h" +#include "third_party/skia/include/core/SkShader.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class ImageShader : public Shader { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(ImageShader); + + public: + ~ImageShader() override; + static ftl::RefPtr Create(); + + void initWithImage(CanvasImage* image, + SkShader::TileMode tmx, + SkShader::TileMode tmy, + const tonic::Float64List& matrix4); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + ImageShader(); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_IMAGE_SHADER_H_ diff --git a/engine/src/flutter/lib/ui/painting/mask_filter.cc b/engine/src/flutter/lib/ui/painting/mask_filter.cc new file mode 100644 index 0000000000..d8d0799e99 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/mask_filter.cc @@ -0,0 +1,39 @@ +// 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 "flutter/lib/ui/painting/mask_filter.h" + +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" +#include "third_party/skia/include/effects/SkBlurMaskFilter.h" + +namespace blink { + +static void MaskFilter_constructor(Dart_NativeArguments args) { + DartCallConstructor(&MaskFilter::Create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, MaskFilter); + +void MaskFilter::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({ + {"MaskFilter_constructor", MaskFilter_constructor, 4, true}, + }); +} + +ftl::RefPtr MaskFilter::Create(unsigned style, + double sigma, + unsigned flags) { + return ftl::MakeRefCounted( + SkBlurMaskFilter::Make(static_cast(style), sigma, flags)); +} + +MaskFilter::MaskFilter(sk_sp filter) + : filter_(std::move(filter)) {} + +MaskFilter::~MaskFilter() {} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/mask_filter.h b/engine/src/flutter/lib/ui/painting/mask_filter.h new file mode 100644 index 0000000000..47846b27d2 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/mask_filter.h @@ -0,0 +1,42 @@ +// 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 FLUTTER_LIB_UI_PAINTING_MASK_FILTER_H_ +#define FLUTTER_LIB_UI_PAINTING_MASK_FILTER_H_ + +#include "lib/tonic/dart_wrappable.h" +#include "third_party/skia/include/core/SkMaskFilter.h" + +class SkMaskFilter; + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class MaskFilter : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(MaskFilter); + + public: + ~MaskFilter() override; + static ftl::RefPtr Create(unsigned style, + double sigma, + unsigned flags); + + const sk_sp& filter() { return filter_; } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + MaskFilter(sk_sp filter); + + sk_sp filter_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_MASK_FILTER_H_ diff --git a/engine/src/flutter/lib/ui/painting/matrix.cc b/engine/src/flutter/lib/ui/painting/matrix.cc new file mode 100644 index 0000000000..aeb76816fa --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/matrix.cc @@ -0,0 +1,41 @@ +// 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 "flutter/lib/ui/painting/matrix.h" + +#include "lib/ftl/logging.h" + +namespace blink { + +// Mappings from SkMatrix-index to input-index. +static const int kSkMatrixIndexToMatrix4Index[] = { + // clang-format off + 0, 4, 12, + 1, 5, 13, + 3, 7, 15, + // clang-format on +}; + +SkMatrix ToSkMatrix(const tonic::Float64List& matrix4) { + FTL_DCHECK(matrix4.data()); + SkMatrix sk_matrix; + for (int i = 0; i < 9; ++i) { + int matrix4_index = kSkMatrixIndexToMatrix4Index[i]; + if (matrix4_index < matrix4.num_elements()) + sk_matrix[i] = matrix4[matrix4_index]; + else + sk_matrix[i] = 0.0; + } + return sk_matrix; +} + +tonic::Float64List ToMatrix4(const SkMatrix& sk_matrix) { + tonic::Float64List matrix4(Dart_NewTypedData(Dart_TypedData_kFloat64, 16)); + for (int i = 0; i < 9; ++i) + matrix4[kSkMatrixIndexToMatrix4Index[i]] = sk_matrix[i]; + matrix4[10] = 1.0; // Identity along the z axis. + return matrix4; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/matrix.h b/engine/src/flutter/lib/ui/painting/matrix.h new file mode 100644 index 0000000000..af59739209 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/matrix.h @@ -0,0 +1,18 @@ +// 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 FLUTTER_LIB_UI_PAINTING_MATRIX_H_ +#define FLUTTER_LIB_UI_PAINTING_MATRIX_H_ + +#include "lib/tonic/typed_data/float64_list.h" +#include "third_party/skia/include/core/SkMatrix.h" + +namespace blink { + +SkMatrix ToSkMatrix(const tonic::Float64List& matrix4); +tonic::Float64List ToMatrix4(const SkMatrix& sk_matrix); + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_MATRIX_H_ diff --git a/engine/src/flutter/lib/ui/painting/paint.cc b/engine/src/flutter/lib/ui/painting/paint.cc new file mode 100644 index 0000000000..3af2e6b36e --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/paint.cc @@ -0,0 +1,124 @@ +// 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 "flutter/lib/ui/painting/paint.h" + +#include "flutter/lib/ui/painting/mask_filter.h" +#include "flutter/lib/ui/painting/shader.h" +#include "lib/ftl/logging.h" +#include "lib/tonic/typed_data/dart_byte_data.h" +#include "third_party/skia/include/core/SkColorFilter.h" +#include "third_party/skia/include/core/SkMaskFilter.h" +#include "third_party/skia/include/core/SkShader.h" +#include "third_party/skia/include/core/SkString.h" + +using namespace blink; + +namespace tonic { + +constexpr int kIsAntiAliasIndex = 0; +constexpr int kColorIndex = 1; +constexpr int kTransferModeIndex = 2; +constexpr int kStyleIndex = 3; +constexpr int kStrokeWidthIndex = 4; +constexpr int kStrokeCapIndex = 5; +constexpr int kFilterQualityIndex = 6; +constexpr int kColorFilterIndex = 7; +constexpr int kColorFilterColorIndex = 8; +constexpr int kColorFilterTransferModeIndex = 9; +constexpr size_t kDataByteCount = 40; + +constexpr int kMaskFilterIndex = 0; +constexpr int kShaderIndex = 1; +constexpr int kObjectCount = 2; // Must be one larger than the largest index + +Paint DartConverter::FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception) { + Dart_Handle paint_objects = Dart_GetNativeArgument(args, index); + FTL_DCHECK(!LogIfError(paint_objects)); + + Dart_Handle paint_data = Dart_GetNativeArgument(args, index + 1); + FTL_DCHECK(!LogIfError(paint_data)); + + Paint result; + SkPaint& paint = result.paint_; + + if (!Dart_IsNull(paint_objects)) { + FTL_DCHECK(Dart_IsList(paint_objects)); + intptr_t length = 0; + Dart_ListLength(paint_objects, &length); + + FTL_CHECK(length == kObjectCount); + Dart_Handle values[kObjectCount]; + if (Dart_IsError(Dart_ListGetRange(paint_objects, 0, kObjectCount, values))) + return result; + + Dart_Handle mask_filter = values[kMaskFilterIndex]; + if (!Dart_IsNull(mask_filter)) { + MaskFilter* decoded = DartConverter::FromDart(mask_filter); + paint.setMaskFilter(decoded->filter()); + } + + Dart_Handle shader = values[kShaderIndex]; + if (!Dart_IsNull(shader)) { + Shader* decoded = DartConverter::FromDart(shader); + paint.setShader(decoded->shader()); + } + } + + tonic::DartByteData byte_data(paint_data); + FTL_CHECK(byte_data.length_in_bytes() == kDataByteCount); + + const uint32_t* uint_data = static_cast(byte_data.data()); + const float* float_data = static_cast(byte_data.data()); + + paint.setAntiAlias(uint_data[kIsAntiAliasIndex] == 0); + + uint32_t encoded_color = uint_data[kColorIndex]; + if (encoded_color) { + SkColor color = encoded_color ^ 0xFF000000; + paint.setColor(color); + } + + uint32_t encoded_transfer_mode = uint_data[kTransferModeIndex]; + if (encoded_transfer_mode) { + uint32_t transfer_mode = encoded_transfer_mode ^ SkXfermode::kSrcOver_Mode; + paint.setXfermodeMode(static_cast(transfer_mode)); + } + + uint32_t style = uint_data[kStyleIndex]; + if (style) + paint.setStyle(static_cast(style)); + + float stroke_width = float_data[kStrokeWidthIndex]; + if (stroke_width != 0.0) + paint.setStrokeWidth(stroke_width); + + uint32_t stroke_cap = uint_data[kStrokeCapIndex]; + if (stroke_cap) + paint.setStrokeCap(static_cast(stroke_cap)); + + uint32_t filter_quality = uint_data[kFilterQualityIndex]; + if (filter_quality) + paint.setFilterQuality(static_cast(filter_quality)); + + if (uint_data[kColorFilterIndex]) { + SkColor color = uint_data[kColorFilterColorIndex]; + SkXfermode::Mode transfer_mode = + static_cast(uint_data[kColorFilterTransferModeIndex]); + paint.setColorFilter(SkColorFilter::MakeModeFilter(color, transfer_mode)); + } + + result.is_null_ = false; + return result; +} + +PaintData DartConverter::FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception) { + return PaintData(); +} + +} // namespace tonic diff --git a/engine/src/flutter/lib/ui/painting/paint.h b/engine/src/flutter/lib/ui/painting/paint.h new file mode 100644 index 0000000000..eeac5a7bf7 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/paint.h @@ -0,0 +1,54 @@ +// 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 FLUTTER_LIB_UI_PAINTING_PAINT_H_ +#define FLUTTER_LIB_UI_PAINTING_PAINT_H_ + +#include "lib/tonic/converter/dart_converter.h" +#include "third_party/skia/include/core/SkPaint.h" + +namespace blink { + +class Paint { + public: + const SkPaint* paint() const { return is_null_ ? nullptr : &paint_; } + + private: + friend struct tonic::DartConverter; + + SkPaint paint_; + bool is_null_; +}; + +// The PaintData argument is a placeholder to receive encoded data for Paint +// objects. The data is actually processed by DartConverter, which reads +// both at the given index and at the next index (which it assumes is a byte +// data for a Paint object). +class PaintData {}; + +} // namespace blink + +namespace tonic { + +template <> +struct DartConverter + : public DartConverterInteger {}; + +template <> +struct DartConverter { + static blink::Paint FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception); +}; + +template <> +struct DartConverter { + static blink::PaintData FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception); +}; + +} // namespace tonic + +#endif // FLUTTER_LIB_UI_PAINTING_PAINT_H_ diff --git a/engine/src/flutter/lib/ui/painting/path.cc b/engine/src/flutter/lib/ui/painting/path.cc new file mode 100644 index 0000000000..cf4a990aa6 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/path.cc @@ -0,0 +1,202 @@ +// 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 "flutter/lib/ui/painting/path.h" + +#include + +#include "flutter/lib/ui/painting/matrix.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" + +namespace blink { + +typedef CanvasPath Path; + +static void Path_constructor(Dart_NativeArguments args) { + DartCallConstructor(&CanvasPath::Create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, Path); + +#define FOR_EACH_BINDING(V) \ + V(Path, getFillType) \ + V(Path, setFillType) \ + V(Path, moveTo) \ + V(Path, relativeMoveTo) \ + V(Path, lineTo) \ + V(Path, relativeLineTo) \ + V(Path, quadraticBezierTo) \ + V(Path, relativeQuadraticBezierTo) \ + V(Path, cubicTo) \ + V(Path, relativeCubicTo) \ + V(Path, conicTo) \ + V(Path, relativeConicTo) \ + V(Path, arcTo) \ + V(Path, addRect) \ + V(Path, addOval) \ + V(Path, addArc) \ + V(Path, addPolygon) \ + V(Path, addRRect) \ + V(Path, addPath) \ + V(Path, extendWithPath) \ + V(Path, close) \ + V(Path, reset) \ + V(Path, contains) \ + V(Path, shift) \ + V(Path, transform) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void CanvasPath::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register({{"Path_constructor", Path_constructor, 1, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +CanvasPath::CanvasPath() {} + +CanvasPath::~CanvasPath() {} + +int CanvasPath::getFillType() { + return path_.getFillType(); +} + +void CanvasPath::setFillType(int fill_type) { + path_.setFillType(static_cast(fill_type)); +} + +void CanvasPath::moveTo(float x, float y) { + path_.moveTo(x, y); +} + +void CanvasPath::relativeMoveTo(float x, float y) { + path_.rMoveTo(x, y); +} + +void CanvasPath::lineTo(float x, float y) { + path_.lineTo(x, y); +} + +void CanvasPath::relativeLineTo(float x, float y) { + path_.rLineTo(x, y); +} + +void CanvasPath::quadraticBezierTo(float x1, float y1, float x2, float y2) { + path_.quadTo(x1, y1, x2, y2); +} + +void CanvasPath::relativeQuadraticBezierTo(float x1, + float y1, + float x2, + float y2) { + path_.rQuadTo(x1, y1, x2, y2); +} + +void CanvasPath::cubicTo(float x1, + float y1, + float x2, + float y2, + float x3, + float y3) { + path_.cubicTo(x1, y1, x2, y2, x3, y3); +} + +void CanvasPath::relativeCubicTo(float x1, + float y1, + float x2, + float y2, + float x3, + float y3) { + path_.rCubicTo(x1, y1, x2, y2, x3, y3); +} + +void CanvasPath::conicTo(float x1, float y1, float x2, float y2, float w) { + path_.conicTo(x1, y1, x2, y2, w); +} + +void CanvasPath::relativeConicTo(float x1, + float y1, + float x2, + float y2, + float w) { + path_.rConicTo(x1, y1, x2, y2, w); +} + +void CanvasPath::arcTo(float left, + float top, + float right, + float bottom, + float startAngle, + float sweepAngle, + bool forceMoveTo) { + path_.arcTo(SkRect::MakeLTRB(left, top, right, bottom), + startAngle * 180.0 / M_PI, sweepAngle * 180.0 / M_PI, + forceMoveTo); +} + +void CanvasPath::addRect(float left, float top, float right, float bottom) { + path_.addRect(SkRect::MakeLTRB(left, top, right, bottom)); +} + +void CanvasPath::addOval(float left, float top, float right, float bottom) { + path_.addOval(SkRect::MakeLTRB(left, top, right, bottom)); +} + +void CanvasPath::addArc(float left, + float top, + float right, + float bottom, + float startAngle, + float sweepAngle) { + path_.addArc(SkRect::MakeLTRB(left, top, right, bottom), + startAngle * 180.0 / M_PI, sweepAngle * 180.0 / M_PI); +} + +void CanvasPath::addPolygon(const tonic::Float32List& points, bool close) { + path_.addPoly(reinterpret_cast(points.data()), + points.num_elements() / 2, close); +} + +void CanvasPath::addRRect(const RRect& rrect) { + path_.addRRect(rrect.sk_rrect); +} + +void CanvasPath::addPath(CanvasPath* path, double dx, double dy) { + if (path) + path_.addPath(path->path(), dx, dy, SkPath::kAppend_AddPathMode); +} + +void CanvasPath::extendWithPath(CanvasPath* path, double dx, double dy) { + if (path) + path_.addPath(path->path(), dx, dy, SkPath::kExtend_AddPathMode); +} + +void CanvasPath::close() { + path_.close(); +} + +void CanvasPath::reset() { + path_.reset(); +} + +bool CanvasPath::contains(double x, double y) { + return path_.contains(x, y); +} + +ftl::RefPtr CanvasPath::shift(double dx, double dy) { + ftl::RefPtr path = CanvasPath::Create(); + path_.offset(dx, dy, &path->path_); + return path; +} + +ftl::RefPtr CanvasPath::transform( + const tonic::Float64List& matrix4) { + ftl::RefPtr path = CanvasPath::Create(); + path_.transform(ToSkMatrix(matrix4), &path->path_); + return path; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/path.h b/engine/src/flutter/lib/ui/painting/path.h new file mode 100644 index 0000000000..5472767f9c --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/path.h @@ -0,0 +1,86 @@ +// 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 FLUTTER_LIB_UI_PAINTING_PATH_H_ +#define FLUTTER_LIB_UI_PAINTING_PATH_H_ + +#include "flutter/lib/ui/painting/rrect.h" +#include "lib/tonic/dart_wrappable.h" +#include "lib/tonic/typed_data/float32_list.h" +#include "lib/tonic/typed_data/float64_list.h" +#include "third_party/skia/include/core/SkPath.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { + +class CanvasPath : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(CanvasPath); + + public: + ~CanvasPath() override; + static ftl::RefPtr Create() { + return ftl::MakeRefCounted(); + } + + int getFillType(); + void setFillType(int fill_type); + + void moveTo(float x, float y); + void relativeMoveTo(float x, float y); + void lineTo(float x, float y); + void relativeLineTo(float x, float y); + void quadraticBezierTo(float x1, float y1, float x2, float y2); + void relativeQuadraticBezierTo(float x1, float y1, float x2, float y2); + void cubicTo(float x1, float y1, float x2, float y2, float x3, float y3); + void relativeCubicTo(float x1, + float y1, + float x2, + float y2, + float x3, + float y3); + void conicTo(float x1, float y1, float x2, float y2, float w); + void relativeConicTo(float x1, float y1, float x2, float y2, float w); + void arcTo(float left, + float top, + float right, + float bottom, + float startAngle, + float sweepAngle, + bool forceMoveTo); + void addRect(float left, float top, float right, float bottom); + void addOval(float left, float top, float right, float bottom); + void addArc(float left, + float top, + float right, + float bottom, + float startAngle, + float sweepAngle); + void addPolygon(const tonic::Float32List& points, bool close); + void addRRect(const RRect& rrect); + void addPath(CanvasPath* path, double dx, double dy); + void extendWithPath(CanvasPath* path, double dx, double dy); + void close(); + void reset(); + bool contains(double x, double y); + ftl::RefPtr shift(double dx, double dy); + ftl::RefPtr transform(const tonic::Float64List& matrix4); + + const SkPath& path() const { return path_; } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + CanvasPath(); + + SkPath path_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_PATH_H_ diff --git a/engine/src/flutter/lib/ui/painting/picture.cc b/engine/src/flutter/lib/ui/painting/picture.cc new file mode 100644 index 0000000000..5242a58ad9 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/picture.cc @@ -0,0 +1,33 @@ +// 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 "flutter/lib/ui/painting/picture.h" + +#include "flutter/lib/ui/painting/canvas.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" + +namespace blink { + +IMPLEMENT_WRAPPERTYPEINFO(ui, Picture); + +#define FOR_EACH_BINDING(V) V(Picture, dispose) + +DART_BIND_ALL(Picture, FOR_EACH_BINDING) + +ftl::RefPtr Picture::Create(sk_sp picture) { + return ftl::MakeRefCounted(std::move(picture)); +} + +Picture::Picture(sk_sp picture) : picture_(std::move(picture)) {} + +Picture::~Picture() {} + +void Picture::dispose() { + ClearDartWrapper(); +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/picture.h b/engine/src/flutter/lib/ui/painting/picture.h new file mode 100644 index 0000000000..99c747e517 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/picture.h @@ -0,0 +1,41 @@ +// 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 FLUTTER_LIB_UI_PAINTING_PICTURE_H_ +#define FLUTTER_LIB_UI_PAINTING_PICTURE_H_ + +#include "lib/tonic/dart_wrappable.h" +#include "third_party/skia/include/core/SkPicture.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { +class Canvas; + +class Picture : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(Picture); + + public: + ~Picture() override; + static ftl::RefPtr Create(sk_sp picture); + + const sk_sp& picture() const { return picture_; } + + void dispose(); + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + explicit Picture(sk_sp picture); + + sk_sp picture_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_PICTURE_H_ diff --git a/engine/src/flutter/lib/ui/painting/picture_recorder.cc b/engine/src/flutter/lib/ui/painting/picture_recorder.cc new file mode 100644 index 0000000000..8938d4cf34 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/picture_recorder.cc @@ -0,0 +1,62 @@ +// 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 "flutter/lib/ui/painting/picture_recorder.h" + +#include "flutter/lib/ui/painting/canvas.h" +#include "flutter/lib/ui/painting/picture.h" +#include "lib/tonic/dart_args.h" +#include "lib/tonic/dart_binding_macros.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_library_natives.h" + +namespace blink { + +static void PictureRecorder_constructor(Dart_NativeArguments args) { + DartCallConstructor(&PictureRecorder::Create, args); +} + +IMPLEMENT_WRAPPERTYPEINFO(ui, PictureRecorder); + +#define FOR_EACH_BINDING(V) \ + V(PictureRecorder, isRecording) \ + V(PictureRecorder, endRecording) + +FOR_EACH_BINDING(DART_NATIVE_CALLBACK) + +void PictureRecorder::RegisterNatives(tonic::DartLibraryNatives* natives) { + natives->Register( + {{"PictureRecorder_constructor", PictureRecorder_constructor, 1, true}, + FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); +} + +ftl::RefPtr PictureRecorder::Create() { + return ftl::MakeRefCounted(); +} + +PictureRecorder::PictureRecorder() {} + +PictureRecorder::~PictureRecorder() {} + +bool PictureRecorder::isRecording() { + return canvas_ && canvas_->IsRecording(); +} + +SkCanvas* PictureRecorder::BeginRecording(SkRect bounds) { + return picture_recorder_.beginRecording(bounds, &rtree_factory_); +} + +ftl::RefPtr PictureRecorder::endRecording() { + if (!isRecording()) + return nullptr; + ftl::RefPtr picture = + Picture::Create(picture_recorder_.finishRecordingAsPicture()); + canvas_->Clear(); + canvas_->ClearDartWrapper(); + canvas_ = nullptr; + ClearDartWrapper(); + return picture; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/picture_recorder.h b/engine/src/flutter/lib/ui/painting/picture_recorder.h new file mode 100644 index 0000000000..155dfc65ed --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/picture_recorder.h @@ -0,0 +1,47 @@ +// 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 FLUTTER_LIB_UI_PAINTING_PICTURE_RECORDER_H_ +#define FLUTTER_LIB_UI_PAINTING_PICTURE_RECORDER_H_ + +#include "lib/tonic/dart_wrappable.h" +#include "third_party/skia/include/core/SkPictureRecorder.h" + +namespace tonic { +class DartLibraryNatives; +} // namespace tonic + +namespace blink { +class Canvas; +class Picture; + +class PictureRecorder : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(PictureRecorder); + + public: + static ftl::RefPtr Create(); + + ~PictureRecorder(); + + SkCanvas* BeginRecording(SkRect bounds); + ftl::RefPtr endRecording(); + bool isRecording(); + + void set_canvas(ftl::RefPtr canvas) { canvas_ = std::move(canvas); } + + static void RegisterNatives(tonic::DartLibraryNatives* natives); + + private: + PictureRecorder(); + + SkRTreeFactory rtree_factory_; + SkPictureRecorder picture_recorder_; + ftl::RefPtr canvas_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_PICTURE_RECORDER_H_ diff --git a/engine/src/flutter/lib/ui/painting/resource_context.cc b/engine/src/flutter/lib/ui/painting/resource_context.cc new file mode 100644 index 0000000000..8e565faf1d --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/resource_context.cc @@ -0,0 +1,25 @@ +// Copyright 2016 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 "flutter/lib/ui/painting/resource_context.h" + +#include "lib/ftl/logging.h" + +namespace blink { +namespace { + +static GrContext* g_context = nullptr; + +} // namespace + +void ResourceContext::Set(GrContext* context) { + FTL_DCHECK(!g_context); + g_context = context; +} + +GrContext* ResourceContext::Get() { + return g_context; +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/resource_context.h b/engine/src/flutter/lib/ui/painting/resource_context.h new file mode 100644 index 0000000000..0d800f4e37 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/resource_context.h @@ -0,0 +1,20 @@ +// Copyright 2016 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 FLUTTER_LIB_UI_PAINTING_RESOURCE_CONTEXT_H_ +#define FLUTTER_LIB_UI_PAINTING_RESOURCE_CONTEXT_H_ + +#include "third_party/skia/include/gpu/GrContext.h" + +namespace blink { + +class ResourceContext { + public: + static void Set(GrContext* context); + static GrContext* Get(); +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_RESOURCE_CONTEXT_H_ diff --git a/engine/src/flutter/lib/ui/painting/rrect.cc b/engine/src/flutter/lib/ui/painting/rrect.cc new file mode 100644 index 0000000000..c310a61220 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/rrect.cc @@ -0,0 +1,46 @@ +// 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 "flutter/lib/ui/painting/rrect.h" + +#include "lib/tonic/logging/dart_error.h" +#include "lib/ftl/logging.h" +#include "lib/tonic/typed_data/float32_list.h" + +using namespace blink; + +namespace tonic { + +// Construct an SkRRect from a Dart RRect object. +// The Dart RRect is a Float32List containing +// [left, top, right, bottom, xRadius, yRadius] +RRect DartConverter::FromDart(Dart_Handle value) { + Float32List buffer(value); + + RRect result; + result.is_null = true; + if (buffer.data() == nullptr) + return result; + + SkVector radii[4] = {{buffer[4], buffer[5]}, + {buffer[6], buffer[7]}, + {buffer[8], buffer[9]}, + {buffer[10], buffer[11]}}; + + result.sk_rrect.setRectRadii( + SkRect::MakeLTRB(buffer[0], buffer[1], buffer[2], buffer[3]), radii); + + result.is_null = false; + return result; +} + +RRect DartConverter::FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception) { + Dart_Handle value = Dart_GetNativeArgument(args, index); + FTL_DCHECK(!LogIfError(value)); + return FromDart(value); +} + +} // namespace tonic diff --git a/engine/src/flutter/lib/ui/painting/rrect.h b/engine/src/flutter/lib/ui/painting/rrect.h new file mode 100644 index 0000000000..e7530c1702 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/rrect.h @@ -0,0 +1,34 @@ +// 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 FLUTTER_LIB_UI_PAINTING_RRECT_H_ +#define FLUTTER_LIB_UI_PAINTING_RRECT_H_ + +#include "dart/runtime/include/dart_api.h" +#include "lib/tonic/converter/dart_converter.h" +#include "third_party/skia/include/core/SkRRect.h" + +namespace blink { + +class RRect { + public: + SkRRect sk_rrect; + bool is_null; +}; + +} // namespace blink + +namespace tonic { + +template <> +struct DartConverter { + static blink::RRect FromDart(Dart_Handle handle); + static blink::RRect FromArguments(Dart_NativeArguments args, + int index, + Dart_Handle& exception); +}; + +} // namespace tonic + +#endif // FLUTTER_LIB_UI_PAINTING_RRECT_H_ diff --git a/engine/src/flutter/lib/ui/painting/shader.cc b/engine/src/flutter/lib/ui/painting/shader.cc new file mode 100644 index 0000000000..098c8319c0 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/shader.cc @@ -0,0 +1,17 @@ +// 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 "flutter/lib/ui/painting/shader.h" + +namespace blink { + +IMPLEMENT_WRAPPERTYPEINFO(ui, Shader); + +Shader::Shader(sk_sp shader) : shader_(shader) { +} + +Shader::~Shader() { +} + +} // namespace blink diff --git a/engine/src/flutter/lib/ui/painting/shader.h b/engine/src/flutter/lib/ui/painting/shader.h new file mode 100644 index 0000000000..6bee161741 --- /dev/null +++ b/engine/src/flutter/lib/ui/painting/shader.h @@ -0,0 +1,33 @@ +// 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 FLUTTER_LIB_UI_PAINTING_SHADER_H_ +#define FLUTTER_LIB_UI_PAINTING_SHADER_H_ + +#include "lib/tonic/dart_wrappable.h" +#include "third_party/skia/include/core/SkShader.h" + +namespace blink { + +class Shader : public ftl::RefCountedThreadSafe, + public tonic::DartWrappable { + DEFINE_WRAPPERTYPEINFO(); + FRIEND_MAKE_REF_COUNTED(Shader); + + public: + ~Shader() override; + + const sk_sp& shader() { return shader_; } + void set_shader(sk_sp shader) { shader_ = std::move(shader); } + + protected: + Shader(sk_sp shader); + + private: + sk_sp shader_; +}; + +} // namespace blink + +#endif // FLUTTER_LIB_UI_PAINTING_SHADER_H_ diff --git a/engine/src/flutter/lib/ui/ui.dart b/engine/src/flutter/lib/ui/ui.dart new file mode 100644 index 0000000000..cedf951dbe --- /dev/null +++ b/engine/src/flutter/lib/ui/ui.dart @@ -0,0 +1,31 @@ +// 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. + +/// Built-in types and core primitives for a Flutter application. +/// +/// To use, import `dart:ui`. +/// +/// This library exposes the lowest-level services that Flutter frameworks use +/// to bootstrap applications, such as methods to obtain handles for the mojo +/// IPC system, classes for driving the graphics and text layout and rendering +/// subsystems, callbacks for integrating with the engine scheduler and the +/// pointer input system, and functions for image decoding. +library dart_ui; + +import 'dart:_internal'; +import 'dart:math' as math; +import 'dart:mojo.internal'; +import 'dart:nativewrappers'; +import 'dart:typed_data'; + +part 'compositing.dart'; +part 'geometry.dart'; +part 'hash_codes.dart'; +part 'hooks.dart'; +part 'lerp.dart'; +part 'mojo_services.dart'; +part 'natives.dart'; +part 'painting.dart'; +part 'text.dart'; +part 'window.dart'; diff --git a/engine/src/flutter/sky/BUILD.gn b/engine/src/flutter/sky/BUILD.gn index bb8a6e5e41..22405430b3 100644 --- a/engine/src/flutter/sky/BUILD.gn +++ b/engine/src/flutter/sky/BUILD.gn @@ -2,27 +2,27 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. -import("//sky/engine/bindings/bindings.gni") +import("//flutter/sky/engine/bindings/bindings.gni") group("sky") { testonly = true deps = [ - "//sky/engine/platform:platform_unittests($host_toolchain)", - "//sky/engine/wtf:unittests($host_toolchain)", - "//sky/packages", - "//sky/shell", + "//flutter/sky/engine/platform:platform_unittests($host_toolchain)", + "//flutter/sky/engine/wtf:unittests($host_toolchain)", + "//flutter/sky/packages", + "//flutter/sky/shell", ] if (dart_host_toolchain == host_toolchain) { - deps += [ "//sky/tools/sky_snapshot($dart_host_toolchain)" ] + deps += [ "//flutter/sky/tools/sky_snapshot($dart_host_toolchain)" ] } if (is_linux || is_android) { - deps += [ "//sky/shell/platform/mojo" ] + deps += [ "//flutter/sky/shell/platform/mojo" ] } if (is_android) { - deps += [ "//sky/services/activity" ] + deps += [ "//flutter/services/activity" ] } } diff --git a/engine/src/flutter/sky/dist/BUILD.gn b/engine/src/flutter/sky/dist/BUILD.gn index 3818ddcac1..d80e582353 100644 --- a/engine/src/flutter/sky/dist/BUILD.gn +++ b/engine/src/flutter/sky/dist/BUILD.gn @@ -13,8 +13,8 @@ copy("sky_shell") { ] deps = [ - "//sky/shell", - "//sky/shell/platform/mojo", + "//flutter/sky/shell", + "//flutter/sky/shell/platform/mojo", ] } else if (is_mac) { sources = [ @@ -22,7 +22,7 @@ copy("sky_shell") { ] deps = [ - "//sky/shell", + "//flutter/sky/shell", ] } else if (!is_ios) { sources = [ @@ -33,9 +33,9 @@ copy("sky_shell") { ] deps = [ - "//sky/shell", - "//sky/shell/platform/mojo", - "//sky/shell/platform/mojo", + "//flutter/sky/shell", + "//flutter/sky/shell/platform/mojo", + "//flutter/sky/shell/platform/mojo", "//third_party/icu:icudata", ] } else { @@ -44,12 +44,12 @@ copy("sky_shell") { } sky_snapshot_dir = - get_label_info("//sky/tools/sky_snapshot($host_toolchain)", "root_out_dir") + get_label_info("//flutter/sky/tools/sky_snapshot($host_toolchain)", "root_out_dir") sources += [ "$sky_snapshot_dir/sky_snapshot" ] deps += [ - "//sky/tools/sky_snapshot($host_toolchain)", + "//flutter/sky/tools/sky_snapshot($host_toolchain)", ] outputs = [ "$root_dist_dir/shell/{{source_file_part}}" ] @@ -57,7 +57,7 @@ copy("sky_shell") { if (is_android) { action("sky_engine") { - script = "//sky/tools/dist_dart_pkg.py" + script = "//flutter/sky/tools/dist_dart_pkg.py" source = "$root_gen_dir/dart-pkg/sky_engine" dest = "$root_dist_dir/packages/sky_engine" @@ -73,12 +73,12 @@ if (is_android) { ] deps = [ - "//sky/packages/sky_engine", + "//flutter/sky/packages/sky_engine", ] } action("sky_services") { - script = "//sky/tools/dist_dart_pkg.py" + script = "//flutter/sky/tools/dist_dart_pkg.py" source = "$root_gen_dir/dart-pkg/sky_services" dest = "$root_dist_dir/packages/sky_services" @@ -94,7 +94,7 @@ if (is_android) { ] deps = [ - "//sky/packages/sky_services", + "//flutter/sky/packages/sky_services", ] } } diff --git a/engine/src/flutter/sky/packages/BUILD.gn b/engine/src/flutter/sky/packages/BUILD.gn index 0014e9d2d8..3c81136a1a 100644 --- a/engine/src/flutter/sky/packages/BUILD.gn +++ b/engine/src/flutter/sky/packages/BUILD.gn @@ -6,7 +6,7 @@ group("packages") { testonly = true deps = [ - "//sky/packages/sky_engine", - "//sky/packages/sky_services", + "//flutter/sky/packages/sky_engine", + "//flutter/sky/packages/sky_services", ] } diff --git a/engine/src/flutter/sky/packages/sky_engine/BUILD.gn b/engine/src/flutter/sky/packages/sky_engine/BUILD.gn index d71096c02c..ed7fa40edb 100644 --- a/engine/src/flutter/sky/packages/sky_engine/BUILD.gn +++ b/engine/src/flutter/sky/packages/sky_engine/BUILD.gn @@ -6,7 +6,7 @@ import("//dart/sdk/lib/rules.gni") import("//flutter/lib/jni/dart_jni.gni") import("//flutter/lib/ui/dart_ui.gni") import("//mojo/public/dart/rules.gni") -import("//sky/engine/core/core.gni") +import("//flutter/sky/engine/core/core.gni") copy("copy_sky_engine_authors") { sources = [ @@ -107,13 +107,13 @@ dart_pkg("sky_engine") { ":copy_dart_sdk", ":copy_dart_ui", ":copy_sky_engine_authors", - "//sky/engine/bindings", + "//flutter/sky/engine/bindings", ] service_isolate_dir = "//dart/runtime/bin/vmservice" sdk_ext_directory = "$root_gen_dir/sky/bindings" sdk_ext_files = [ - "//sky/engine/bindings/internals.dart", + "//flutter/sky/engine/bindings/internals.dart", "$service_isolate_dir/vmservice_io.dart", "$service_isolate_dir/loader.dart", "$service_isolate_dir/server.dart", diff --git a/engine/src/flutter/sky/packages/sky_services/BUILD.gn b/engine/src/flutter/sky/packages/sky_services/BUILD.gn index 0a2c0d3f31..955075f585 100644 --- a/engine/src/flutter/sky/packages/sky_services/BUILD.gn +++ b/engine/src/flutter/sky/packages/sky_services/BUILD.gn @@ -23,12 +23,12 @@ dart_pkg("sky_services") { deps = [ ":copy_sky_services_license", - "//sky/services/activity:interfaces", - "//sky/services/editing:interfaces", - "//sky/services/media:interfaces", - "//sky/services/platform:interfaces", - "//sky/services/pointer:interfaces", - "//sky/services/raw_keyboard:interfaces", - "//sky/services/semantics:interfaces", + "//flutter/services/activity:interfaces", + "//flutter/services/editing:interfaces", + "//flutter/services/media:interfaces", + "//flutter/services/platform:interfaces", + "//flutter/services/pointer:interfaces", + "//flutter/services/raw_keyboard:interfaces", + "//flutter/services/semantics:interfaces", ] } diff --git a/engine/src/flutter/sky/tools/gn b/engine/src/flutter/sky/tools/gn index 4e0b4a7a9c..0ceb0ce52d 100755 --- a/engine/src/flutter/sky/tools/gn +++ b/engine/src/flutter/sky/tools/gn @@ -8,7 +8,7 @@ import subprocess import sys import os -SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) def get_out_dir(args): if args.target_os is not None: @@ -144,7 +144,21 @@ def parse_args(args): def main(argv): args = parse_args(argv) - command = ['gn', 'gen', '--check'] + + if sys.platform.startswith(('cygwin', 'win')): + subdir = 'win' + elif sys.platform == 'darwin': + subdir = 'mac' + elif sys.platform.startswith('linux'): + subdir = 'linux64' + else: + raise Error('Unknown platform: ' + sys.platform) + + command = [ + '%s/buildtools/%s/gn' % (SRC_ROOT, subdir), + 'gen', + '--check' + ] gn_args = to_command_line(to_gn_args(args)) out_dir = get_out_dir(args) print "gn gen --check in %s" % out_dir diff --git a/engine/src/flutter/sky/tools/sky_snapshot/BUILD.gn b/engine/src/flutter/sky/tools/sky_snapshot/BUILD.gn index fd90235ac6..1966d587dc 100644 --- a/engine/src/flutter/sky/tools/sky_snapshot/BUILD.gn +++ b/engine/src/flutter/sky/tools/sky_snapshot/BUILD.gn @@ -13,7 +13,7 @@ executable("sky_snapshot") { "//lib/ftl", "//lib/tonic/converter", "//lib/tonic/file_loader", - "//sky/engine/bindings:snapshot_cc", + "//flutter/sky/engine/bindings:snapshot_cc", ] if (!is_ios && !is_mac) { diff --git a/engine/src/flutter/tonic/BUILD.gn b/engine/src/flutter/tonic/BUILD.gn new file mode 100644 index 0000000000..8478fc2d2e --- /dev/null +++ b/engine/src/flutter/tonic/BUILD.gn @@ -0,0 +1,41 @@ +# Copyright 2016 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("tonic") { + sources = [ + "dart_debugger.cc", + "dart_debugger.h", + "dart_dependency_catcher.cc", + "dart_dependency_catcher.h", + "dart_io.cc", + "dart_io.h", + "dart_isolate_reloader.cc", + "dart_isolate_reloader.h", + "dart_library_loader.cc", + "dart_library_loader.h", + "dart_library_provider.cc", + "dart_library_provider.h", + "dart_library_provider_files.cc", + "dart_library_provider_files.h", + "dart_snapshot_loader.cc", + "dart_snapshot_loader.h", + "dart_state.cc", + "dart_state.h", + ] + + deps = [ + "//base", + "//dart/runtime/bin:embedded_dart_io", + "//flutter/glue", + "//lib/tonic/parsers", + "//mojo/data_pipe_utils", + "//mojo/public/cpp/system", + ] + + public_deps = [ + "//dart/runtime:libdart", + "//dart/runtime/vm:libdart_platform", + "//lib/tonic", + ] +} diff --git a/engine/src/flutter/tonic/dart_debugger.cc b/engine/src/flutter/tonic/dart_debugger.cc new file mode 100644 index 0000000000..bfad4cfac8 --- /dev/null +++ b/engine/src/flutter/tonic/dart_debugger.cc @@ -0,0 +1,139 @@ +// 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 "flutter/tonic/dart_debugger.h" + +#include "dart/runtime/include/dart_api.h" +#include "dart/runtime/include/dart_native_api.h" +#include "dart/runtime/include/dart_tools_api.h" +#include "lib/ftl/logging.h" + +namespace blink { + +void DartDebuggerIsolate::MessageLoop() { + ftl::MonitorLocker locker(&monitor_); + Dart_MessageNotifyCallback saved_message_notify_callback = + Dart_GetMessageNotifyCallback(); + // Request notification on isolate messages. This allows us to + // respond to vm service messages while at breakpoint. + Dart_SetMessageNotifyCallback(DartDebugger::NotifyIsolate); + while (true) { + // Handle all available vm service messages, up to a resume + // request. + bool resume = false; + while (!resume && Dart_HasServiceMessages()) { + monitor_.Exit(); + resume = Dart_HandleServiceMessages(); + monitor_.Enter(); + } + if (resume) { + break; + } + locker.Wait(); + } + Dart_SetMessageNotifyCallback(saved_message_notify_callback); +} + +void DartDebugger::BptResolvedHandler(Dart_IsolateId isolate_id, + intptr_t bp_id, + const Dart_CodeLocation& location) { + // Nothing to do here. Service event is dispatched to let Observatory know + // that a breakpoint was resolved. +} + +void DartDebugger::PausedEventHandler(Dart_IsolateId isolate_id, + intptr_t bp_id, + const Dart_CodeLocation& loc) { + Dart_EnterScope(); + intptr_t isolate_index = FindIsolateIndexById(isolate_id); + FTL_CHECK(isolate_index != -1); + (*isolates_)[isolate_index]->MessageLoop(); + Dart_ExitScope(); +} + +void DartDebugger::ExceptionThrownHandler(Dart_IsolateId isolate_id, + Dart_Handle exception, + Dart_StackTrace stack_trace) { + Dart_EnterScope(); + intptr_t isolate_index = FindIsolateIndexById(isolate_id); + FTL_CHECK(isolate_index != -1); + (*isolates_)[isolate_index]->MessageLoop(); + Dart_ExitScope(); +} + +void DartDebugger::IsolateEventHandler(Dart_IsolateId isolate_id, + Dart_IsolateEvent kind) { + Dart_EnterScope(); + if (kind == Dart_IsolateEvent::kCreated) { + AddIsolate(isolate_id); + } else { + intptr_t isolate_index = FindIsolateIndexById(isolate_id); + FTL_CHECK(isolate_index != -1); + if (kind == Dart_IsolateEvent::kInterrupted) { + (*isolates_)[isolate_index]->MessageLoop(); + } else { + FTL_CHECK(kind == Dart_IsolateEvent::kShutdown); + RemoveIsolate(isolate_id); + } + } + Dart_ExitScope(); +} + +void DartDebugger::NotifyIsolate(Dart_Isolate isolate) { + ftl::MutexLocker locker(mutex_); + Dart_IsolateId isolate_id = Dart_GetIsolateId(isolate); + intptr_t isolate_index = FindIsolateIndexByIdLocked(isolate_id); + if (isolate_index >= 0) { + (*isolates_)[isolate_index]->Notify(); + } +} + +void DartDebugger::InitDebugger() { + Dart_SetIsolateEventHandler(IsolateEventHandler); + Dart_SetPausedEventHandler(PausedEventHandler); + Dart_SetBreakpointResolvedHandler(BptResolvedHandler); + Dart_SetExceptionThrownHandler(ExceptionThrownHandler); + mutex_ = new ftl::Mutex(); + isolates_ = new std::vector>(); +} + +intptr_t DartDebugger::FindIsolateIndexById(Dart_IsolateId id) { + ftl::MutexLocker locker(mutex_); + return FindIsolateIndexByIdLocked(id); +} + +intptr_t DartDebugger::FindIsolateIndexByIdLocked(Dart_IsolateId id) { + mutex_->AssertHeld(); + for (size_t i = 0; i < isolates_->size(); i++) { + if ((*isolates_)[i]->id() == id) { + return i; + } + } + return -1; +} + +void DartDebugger::AddIsolate(Dart_IsolateId id) { + ftl::MutexLocker locker(mutex_); + FTL_CHECK(FindIsolateIndexByIdLocked(id) == -1); + std::unique_ptr debugger_isolate = + std::unique_ptr(new DartDebuggerIsolate(id)); + isolates_->push_back(std::move(debugger_isolate)); +} + +void DartDebugger::RemoveIsolate(Dart_IsolateId id) { + ftl::MutexLocker locker(mutex_); + for (size_t i = 0; i < isolates_->size(); i++) { + if (id == (*isolates_)[i]->id()) { + isolates_->erase(isolates_->begin() + i); + return; + } + } + FTL_NOTREACHED(); +} + +ftl::Mutex* DartDebugger::mutex_ = nullptr; +std::vector>* DartDebugger::isolates_ = + nullptr; + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_debugger.h b/engine/src/flutter/tonic/dart_debugger.h new file mode 100644 index 0000000000..870e0f02eb --- /dev/null +++ b/engine/src/flutter/tonic/dart_debugger.h @@ -0,0 +1,72 @@ +// 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 FLUTTER_TONIC_DART_DEBUGGER_H_ +#define FLUTTER_TONIC_DART_DEBUGGER_H_ + +#include +#include + +#include "dart/runtime/include/dart_api.h" +#include "dart/runtime/include/dart_native_api.h" +#include "dart/runtime/include/dart_tools_api.h" +#include "lib/ftl/synchronization/monitor.h" +#include "lib/ftl/synchronization/mutex.h" + +namespace blink { + +class DartDebuggerIsolate { + public: + DartDebuggerIsolate(Dart_IsolateId id) : id_(id) {} + + Dart_IsolateId id() const { return id_; } + + void Notify() { monitor_.Signal(); } + + void MessageLoop(); + + private: + const Dart_IsolateId id_; + ftl::Monitor monitor_; +}; + +class DartDebugger { + public: + static void InitDebugger(); + + private: + static void BptResolvedHandler(Dart_IsolateId isolate_id, + intptr_t bp_id, + const Dart_CodeLocation& location); + + static void PausedEventHandler(Dart_IsolateId isolate_id, + intptr_t bp_id, + const Dart_CodeLocation& loc); + + static void ExceptionThrownHandler(Dart_IsolateId isolate_id, + Dart_Handle exception, + Dart_StackTrace stack_trace); + + static void IsolateEventHandler(Dart_IsolateId isolate_id, + Dart_IsolateEvent kind); + + static void NotifyIsolate(Dart_Isolate isolate); + + static intptr_t FindIsolateIndexById(Dart_IsolateId id); + + static intptr_t FindIsolateIndexByIdLocked(Dart_IsolateId id); + + static void AddIsolate(Dart_IsolateId id); + + static void RemoveIsolate(Dart_IsolateId id); + + static ftl::Mutex* mutex_; + static std::vector>* isolates_; + + friend class DartDebuggerIsolate; +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_DEBUGGER_H_ diff --git a/engine/src/flutter/tonic/dart_dependency_catcher.cc b/engine/src/flutter/tonic/dart_dependency_catcher.cc new file mode 100644 index 0000000000..f6eec6793f --- /dev/null +++ b/engine/src/flutter/tonic/dart_dependency_catcher.cc @@ -0,0 +1,24 @@ +// 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 "flutter/tonic/dart_dependency_catcher.h" + +#include "flutter/tonic/dart_library_loader.h" + +namespace blink { + +DartDependencyCatcher::DartDependencyCatcher(DartLibraryLoader& loader) + : loader_(loader) { + loader_.set_dependency_catcher(this); +} + +DartDependencyCatcher::~DartDependencyCatcher() { + loader_.set_dependency_catcher(nullptr); +} + +void DartDependencyCatcher::AddDependency(DartDependency* dependency) { + dependencies_.insert(dependency); +} + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_dependency_catcher.h b/engine/src/flutter/tonic/dart_dependency_catcher.h new file mode 100644 index 0000000000..740c5e2fd1 --- /dev/null +++ b/engine/src/flutter/tonic/dart_dependency_catcher.h @@ -0,0 +1,39 @@ +// 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 FLUTTER_TONIC_DART_DEPENDENCY_CATCHER_H_ +#define FLUTTER_TONIC_DART_DEPENDENCY_CATCHER_H_ + +#include + +#include "lib/ftl/macros.h" + +namespace blink { +class DartLibraryLoader; + +// A base class to represent a dependency. +class DartDependency {}; + +// To catch the dependencies for a library, put a DartDependencyCatcher on the +// stack during the call to Dart_LoadLibrary. +class DartDependencyCatcher { + public: + explicit DartDependencyCatcher(DartLibraryLoader& loader); + ~DartDependencyCatcher(); + + void AddDependency(DartDependency* dependency); + const std::unordered_set& dependencies() const { + return dependencies_; + } + + private: + DartLibraryLoader& loader_; + std::unordered_set dependencies_; + + FTL_DISALLOW_COPY_AND_ASSIGN(DartDependencyCatcher); +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_DEPENDENCY_CATCHER_H_ diff --git a/engine/src/flutter/tonic/dart_io.cc b/engine/src/flutter/tonic/dart_io.cc new file mode 100644 index 0000000000..5cb87a2e01 --- /dev/null +++ b/engine/src/flutter/tonic/dart_io.cc @@ -0,0 +1,21 @@ +// 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 "flutter/tonic/dart_io.h" + +#include "dart/runtime/bin/io_natives.h" +#include "dart/runtime/include/dart_api.h" +#include "lib/tonic/converter/dart_converter.h" + +using tonic::ToDart; + +namespace blink { + +void DartIO::InitForIsolate() { + DART_CHECK_VALID(Dart_SetNativeResolver(Dart_LookupLibrary(ToDart("dart:io")), + dart::bin::IONativeLookup, + dart::bin::IONativeSymbol)); +} + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_io.h b/engine/src/flutter/tonic/dart_io.h new file mode 100644 index 0000000000..8d3ad5283b --- /dev/null +++ b/engine/src/flutter/tonic/dart_io.h @@ -0,0 +1,22 @@ +// 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 FLUTTER_TONIC_DART_IO_H_ +#define FLUTTER_TONIC_DART_IO_H_ + +#include "lib/ftl/macros.h" + +namespace blink { + +class DartIO { + public: + static void InitForIsolate(); + + private: + FTL_DISALLOW_IMPLICIT_CONSTRUCTORS(DartIO); +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_IO_H_ diff --git a/engine/src/flutter/tonic/dart_isolate_reloader.cc b/engine/src/flutter/tonic/dart_isolate_reloader.cc new file mode 100644 index 0000000000..d4bddee30b --- /dev/null +++ b/engine/src/flutter/tonic/dart_isolate_reloader.cc @@ -0,0 +1,315 @@ +// Copyright 2016 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 "flutter/tonic/dart_isolate_reloader.h" + +#include + +#include "flutter/tonic/dart_dependency_catcher.h" +#include "flutter/tonic/dart_library_loader.h" +#include "flutter/tonic/dart_library_provider.h" +#include "flutter/tonic/dart_state.h" +#include "flutter/glue/drain_data_pipe_job.h" +#include "flutter/glue/thread.h" +#include "lib/ftl/logging.h" +#include "lib/ftl/synchronization/monitor.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/logging/dart_error.h" +#include "lib/tonic/scopes/dart_api_scope.h" +#include "lib/tonic/scopes/dart_isolate_scope.h" + +using tonic::ToDart; +using tonic::StdStringToDart; +using tonic::StdStringFromDart; + +namespace blink { + +// As each source file is loaded, a LoadResult is queued to be processed on the +// isolate's thread. A LoadResult contains the payload or an error message. +class DartIsolateReloader::LoadResult { + public: + // Successful load result. + LoadResult(intptr_t tag, + const std::string& url, + const std::string& library_url, + const std::string& resolved_url, + std::vector payload) + : success_(true), + tag_(tag), + url_(url), + library_url_(library_url), + resolved_url_(resolved_url), + payload_(std::move(payload)) { + FTL_DCHECK(success()); + } + + // Error load result. + LoadResult(intptr_t tag, + const std::string& url, + const std::string& library_url, + const std::string& error) + : success_(false), + tag_(tag), + url_(url), + library_url_(library_url), + error_(error) {} + + bool success() const { return success_; } + + Dart_Handle Finish() { + if (!success()) { + return StdStringToDart(error_); + } + Dart_Handle uri = StdStringToDart(url_); + Dart_Handle resolved_uri = Dart_Null(); + if (!resolved_url_.empty()) { + resolved_uri = StdStringToDart(resolved_url_); + } + Dart_Handle library = Dart_Null(); + if (!library_url_.empty()) { + library = Dart_LookupLibrary(StdStringToDart(library_url_)); + } + Dart_Handle source = Dart_NewStringFromUTF8( + reinterpret_cast(payload_.data()), payload_.size()); + Dart_Handle result = Dart_Null(); + switch (tag_) { + case Dart_kImportTag: + result = Dart_LoadLibrary(uri, resolved_uri, source, 0, 0); + break; + case Dart_kSourceTag: + result = Dart_LoadSource(library, uri, resolved_uri, source, 0, 0); + break; + case Dart_kScriptTag: + result = Dart_LoadScript(uri, resolved_uri, source, 0, 0); + break; + } + + if (Dart_IsError(result)) { + return result; + } + return Dart_Null(); + } + + private: + bool success_; + intptr_t tag_; + std::string url_; + std::string library_url_; + std::string resolved_url_; + std::string error_; + std::vector payload_; +}; + +DartIsolateReloader::DartIsolateReloader(DartLibraryProvider* library_provider) + : thread_("DartIsolateReloader"), + library_provider_(library_provider), + load_error_(Dart_Null()), + pending_requests_(0) { + FTL_CHECK(thread_.Start()); +} + +DartIsolateReloader::~DartIsolateReloader() {} + +void DartIsolateReloader::SendRequest(Dart_LibraryTag tag, + Dart_Handle url, + Dart_Handle library_url) { + ftl::RefPtr runner = thread_.task_runner(); + std::string url_string = StdStringFromDart(url); + std::string library_url_string = StdStringFromDart(library_url); + + ftl::MonitorLocker locker(&monitor_); + + // Post a task to the worker thread. This task will request the I/O and + // post a LoadResult to be processed once complete. + runner->PostTask([this, tag, url_string, library_url_string]() { + RequestTask(library_provider_, this, static_cast(tag), url_string, + library_url_string); + }); + + pending_requests_++; +} + +void DartIsolateReloader::PostResult(std::unique_ptr load_result) { + ftl::MonitorLocker locker(&monitor_); + pending_requests_--; + load_results_.push(std::move(load_result)); + locker.Signal(); +} + +// As each source file is requested, a LoadRequest is queued to be processed on +// worker thread. +class DartIsolateReloader::LoadRequest { + public: + LoadRequest(DartLibraryProvider* library_provider, + DartIsolateReloader* isolate_reloader, + intptr_t tag, + const std::string& url, + const std::string& library_url) + : isolate_reloader_(isolate_reloader), + tag_(tag), + url_(url), + library_url_(library_url) { + auto stream = library_provider->GetLibraryAsStream(url_); + OnStreamAvailable(std::move(stream.handle), std::move(stream.resolved_url)); + } + + protected: + void OnStreamAvailable(mojo::ScopedDataPipeConsumerHandle handle, + std::string resolved_url) { + if (!handle.is_valid()) { + std::unique_ptr result( + new DartIsolateReloader::LoadResult( + tag_, url_, library_url_, + "File " + url_ + " could not be read.")); + FTL_LOG(ERROR) << "Load failed for " << url_; + isolate_reloader_->PostResult(std::move(result)); + // We are finished with this request. + delete this; + return; + } + resolved_url_ = std::move(resolved_url); + drainer_.reset(new glue::DrainDataPipeJob( + std::move(handle), [this](std::vector buffer) { + std::unique_ptr result( + new DartIsolateReloader::LoadResult( + tag_, url_, library_url_, resolved_url_, std::move(buffer))); + isolate_reloader_->PostResult(std::move(result)); + // We are finished with this request. + delete this; + })); + } + + private: + DartIsolateReloader* isolate_reloader_; + intptr_t tag_; + std::string url_; + std::string library_url_; + std::string resolved_url_; + std::vector buffer_; + std::unique_ptr drainer_; +}; + +void DartIsolateReloader::RequestTask(DartLibraryProvider* library_provider, + DartIsolateReloader* isolate_reloader, + intptr_t tag, + const std::string& url, + const std::string& library_url) { + FTL_DCHECK(isolate_reloader); + FTL_DCHECK(library_provider); + FTL_DCHECK(tag > 0); + // Construct a new LoadRequest. The pointer is dropped here because + // the request deletes itself on success and failure. + new LoadRequest(library_provider, isolate_reloader, tag, url, library_url); +} + +void DartIsolateReloader::HandleLoadResultLocked(LoadResult* load_result) { + if (load_error_ != Dart_Null()) { + // Already have a sticky error. Just drop this result. + return; + } + + // Drop the lock temporarily around the call to Finish because it may + // trigger a recursive call into the tag handler. + monitor_.Exit(); + Dart_Handle error_or_null = load_result->Finish(); + monitor_.Enter(); + + if (!Dart_IsNull(error_or_null)) { + // Set sticky error. + load_error_ = error_or_null; + } +} + +void DartIsolateReloader::ProcessResultQueueLocked() { + while (load_results_.size() > 0) { + // Grab the first load result. + std::unique_ptr result = std::move(load_results_.front()); + load_results_.pop(); + HandleLoadResultLocked(result.get()); + } +} + +bool DartIsolateReloader::IsCompleteLocked() { + return (pending_requests_ == 0) && load_results_.empty(); +} + +bool DartIsolateReloader::BlockUntilComplete() { + ftl::MonitorLocker locker(&monitor_); + + while (true) { + ProcessResultQueueLocked(); + + if (IsCompleteLocked()) { + break; + } + + // Wait to be notified about new I/O results. + locker.Wait(); + } + return !Dart_IsNull(load_error_); +} + +Dart_Handle DartIsolateReloader::HandleLibraryTag(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url) { + if (tag == Dart_kCanonicalizeUrl) { + // Pass through to actual tag handler. + return DartLibraryLoader::HandleLibraryTag(tag, library, url); + } + DartState* dart_state = DartState::Current(); + FTL_DCHECK(dart_state); + DartIsolateReloader* isolate_reloader = dart_state->isolate_reloader(); + // The first call into the tag handler ends up blocking the calling thread + // until the entire reload has completed. All other calls into the + // tag handler schedule requests and return immediately. + const bool blocking_call = (tag == Dart_kScriptTag); + if (!isolate_reloader) { + // The first call into this tag handler must be for the script. + FTL_DCHECK(tag == Dart_kScriptTag); + // Associate the reloader with the isolate. The reloader is owned + // by the dart_state. + dart_state->set_isolate_reloader( + std::unique_ptr(new DartIsolateReloader( + dart_state->library_loader().library_provider()))); + // Get a pointer to the reloader. + isolate_reloader = dart_state->isolate_reloader(); + // Switch the tag handler. + Dart_SetLibraryTagHandler(DartIsolateReloader::HandleLibraryTag); + } else { + // We should not see another request for the script. + FTL_DCHECK(tag != Dart_kScriptTag); + } + + // Issue I/O request. + isolate_reloader->SendRequest(tag, url, (library != Dart_Null()) + ? Dart_LibraryUrl(library) + : Dart_Null()); + + if (blocking_call) { + // Block and process LoadResults until the load is complete. + const bool load_error = isolate_reloader->BlockUntilComplete(); + // Grab the (possibly null) load error from the reloader before its gone. + Dart_Handle result = isolate_reloader->load_error_; + // The reloader will be deleted once we call set_isolate_reloader below. + isolate_reloader = nullptr; + // Disassociate reloader from the isolate, this causes it to be deleted. + dart_state->set_isolate_reloader(nullptr); + Dart_SetLibraryTagHandler(DartLibraryLoader::HandleLibraryTag); + if (load_error) { + // If we hit an error, return the load error. + return result; + } else { + // Finalize loading. + result = Dart_FinalizeLoading(true); + if (Dart_IsError(result)) { + // If we hit an error, return the load error. + return result; + } + } + } + + return Dart_Null(); +} + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_isolate_reloader.h b/engine/src/flutter/tonic/dart_isolate_reloader.h new file mode 100644 index 0000000000..e546fb99ee --- /dev/null +++ b/engine/src/flutter/tonic/dart_isolate_reloader.h @@ -0,0 +1,71 @@ +// Copyright 2016 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 FLUTTER_TONIC_DART_ISOLATE_RELOADER_H_ +#define FLUTTER_TONIC_DART_ISOLATE_RELOADER_H_ + +#include +#include +#include + +#include "dart/runtime/include/dart_api.h" +#include "flutter/glue/thread.h" +#include "lib/ftl/macros.h" +#include "lib/ftl/synchronization/monitor.h" + +namespace blink { +class DartLibraryProvider; + +// Reloading an isolate must be an atomic operation, meaning, no other tasks +// can run while reloading. A nested run loop is not sufficient because other +// tasks that invoke Dart code can be run. When |HandleLibraryTag| is invoked +// the calling thread will be blocked until the load has fully completed. To +// avoid relying on the message loop we use our own queue and notification +// mechanism. +class DartIsolateReloader { + public: + // The |DartLibraryProvider| used to load the library sources. + DartIsolateReloader(DartLibraryProvider* library_provider); + ~DartIsolateReloader(); + + static Dart_Handle HandleLibraryTag(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url); + + private: + class LoadRequest; + class LoadResult; + + void SendRequest(Dart_LibraryTag tag, + Dart_Handle url, + Dart_Handle library_url); + + void PostResult(std::unique_ptr load_result); + + static void RequestTask(DartLibraryProvider* library_provider, + DartIsolateReloader* isolate_reloader, + intptr_t tag, + const std::string& url, + const std::string& library_url); + + void HandleLoadResultLocked(LoadResult* load_result); + void ProcessResultQueueLocked(); + bool IsCompleteLocked(); + bool BlockUntilComplete(); + + glue::Thread thread_; + DartLibraryProvider* library_provider_; + + ftl::Monitor monitor_; + // The monitor is used to protect the following fields: + Dart_Handle load_error_; + std::queue> load_results_; + intptr_t pending_requests_; + + FTL_DISALLOW_COPY_AND_ASSIGN(DartIsolateReloader); +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_ISOLATE_RELOADER_H_ diff --git a/engine/src/flutter/tonic/dart_library_loader.cc b/engine/src/flutter/tonic/dart_library_loader.cc new file mode 100644 index 0000000000..b4c69ec6e4 --- /dev/null +++ b/engine/src/flutter/tonic/dart_library_loader.cc @@ -0,0 +1,335 @@ +// 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 "flutter/tonic/dart_library_loader.h" + +#include + +#include "flutter/tonic/dart_dependency_catcher.h" +#include "flutter/tonic/dart_isolate_reloader.h" +#include "flutter/tonic/dart_library_provider.h" +#include "flutter/tonic/dart_state.h" +#include "flutter/glue/drain_data_pipe_job.h" +#include "flutter/glue/trace_event.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/dart_persistent_value.h" +#include "lib/tonic/logging/dart_error.h" +#include "lib/tonic/scopes/dart_api_scope.h" +#include "lib/tonic/scopes/dart_isolate_scope.h" + +using tonic::StdStringFromDart; +using tonic::ToDart; + +namespace blink { + +namespace { + +// Helper to erase a T* from a container of std::unique_ptrs. +template +void EraseUniquePtr(C& container, T* item) { + std::unique_ptr key = std::unique_ptr(item); + container.erase(key); + key.release(); +} + +} // namespace + +// A DartLibraryLoader::Job represents a network load. It fetches data from the +// network and buffers the data in std::vector. To cancel the job, delete this +// object. +class DartLibraryLoader::Job : public DartDependency { + public: + Job(DartLibraryLoader* loader, const std::string& name) + : loader_(loader), name_(name) { + auto stream = loader->library_provider()->GetLibraryAsStream(name); + OnStreamAvailable(std::move(stream.handle), std::move(stream.resolved_url)); + } + + const std::string& name() const { return name_; } + const std::string& resolved_url() const { return resolved_url_; } + + protected: + DartLibraryLoader* loader_; + + virtual void OnDataAvailable(std::vector buffer) = 0; + + private: + void OnStreamAvailable(mojo::ScopedDataPipeConsumerHandle pipe, + const std::string& resolved_url) { + if (!pipe.is_valid()) { + loader_->DidFailJob(this); + return; + } + resolved_url_ = resolved_url; + drainer_.reset(new glue::DrainDataPipeJob( + std::move(pipe), [this](std::vector buffer) { + OnDataAvailable(std::move(buffer)); + })); + } + + std::string name_; + std::string resolved_url_; + std::unique_ptr drainer_; +}; + +class DartLibraryLoader::ImportJob : public Job { + public: + ImportJob(DartLibraryLoader* loader, + const std::string& name, + bool should_load_as_script) + : Job(loader, name), should_load_as_script_(should_load_as_script) { + TRACE_EVENT_ASYNC_BEGIN1("flutter", "DartLibraryLoader::ImportJob", this, + "url", name); + } + + bool should_load_as_script() const { return should_load_as_script_; } + + private: + void OnDataAvailable(std::vector buffer) override { + TRACE_EVENT_ASYNC_END0("flutter", "DartLibraryLoader::ImportJob", this); + loader_->DidCompleteImportJob(this, std::move(buffer)); + } + + bool should_load_as_script_; +}; + +class DartLibraryLoader::SourceJob : public Job { + public: + SourceJob(DartLibraryLoader* loader, + const std::string& name, + Dart_Handle library) + : Job(loader, name), library_(loader->dart_state(), library) { + TRACE_EVENT_ASYNC_BEGIN1("flutter", "DartLibraryLoader::SourceJob", this, + "url", name); + } + + Dart_PersistentHandle library() const { return library_.value(); } + + private: + void OnDataAvailable(std::vector buffer) override { + TRACE_EVENT_ASYNC_END0("flutter", "DartLibraryLoader::SourceJob", this); + loader_->DidCompleteSourceJob(this, std::move(buffer)); + } + + tonic::DartPersistentValue library_; +}; + +// A DependencyWatcher represents a request to watch for when a given set of +// dependencies (either libraries or parts of libraries) have finished loading. +// When the dependencies are satisfied (including transitive dependencies), then +// the |callback| will be invoked. +class DartLibraryLoader::DependencyWatcher { + public: + DependencyWatcher(const std::unordered_set& dependencies, + const ftl::Closure& callback) + : dependencies_(dependencies), callback_(callback) { + FTL_DCHECK(!dependencies_.empty()); + } + + bool DidResolveDependency( + DartDependency* resolved_dependency, + const std::unordered_set& new_dependencies) { + const auto& it = dependencies_.find(resolved_dependency); + if (it == dependencies_.end()) + return false; + dependencies_.erase(it); + for (const auto& dependency : new_dependencies) + dependencies_.insert(dependency); + return dependencies_.empty(); + } + + const ftl::Closure& callback() const { return callback_; } + + private: + std::unordered_set dependencies_; + ftl::Closure callback_; +}; + +// A WatcherSignaler is responsible for signaling DependencyWatchers when their +// dependencies resolve and for calling the DependencyWatcher's callback. We use +// a separate object of this task because we want to carefully manage when we +// call the callbacks, which can call into us again reentrantly. +// +// WatcherSignaler is designed to be placed on the stack as a RAII. After its +// destructor runs, we might have executed aribitrary script. +class DartLibraryLoader::WatcherSignaler { + public: + WatcherSignaler(DartLibraryLoader& loader, + DartDependency* resolved_dependency) + : loader_(loader), + catcher_(new DartDependencyCatcher(loader)), + resolved_dependency_(resolved_dependency) {} + + ~WatcherSignaler() { + std::vector completed_watchers; + for (const auto& watcher : loader_.dependency_watchers_) { + if (watcher->DidResolveDependency(resolved_dependency_, + catcher_->dependencies())) + completed_watchers.push_back(watcher.get()); + } + + // Notice that we remove the dependency catcher and extract all the + // callbacks before running any of them. We don't want to be re-entered + // below the callbacks and end up in an inconsistent state. + catcher_ = nullptr; + std::vector callbacks; + for (const auto& watcher : completed_watchers) { + callbacks.push_back(watcher->callback()); + EraseUniquePtr(loader_.dependency_watchers_, watcher); + } + + // Finally, run all the callbacks while touching only data on the stack. + for (const auto& callback : callbacks) + callback(); + } + + private: + DartLibraryLoader& loader_; + std::unique_ptr catcher_; + DartDependency* resolved_dependency_; +}; + +DartLibraryLoader::DartLibraryLoader(DartState* dart_state) + : dart_state_(dart_state), + library_provider_(nullptr), + dependency_catcher_(nullptr) {} + +DartLibraryLoader::~DartLibraryLoader() {} + +Dart_Handle DartLibraryLoader::HandleLibraryTag(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url) { + FTL_DCHECK(Dart_IsLibrary(library) || Dart_IsNull(library)); + FTL_DCHECK(Dart_IsString(url)); + if (tag == Dart_kCanonicalizeUrl) { + return DartState::Current()->library_loader().CanonicalizeURL(library, url); + } + if (tag == Dart_kImportTag) { + return DartState::Current()->library_loader().Import(library, url); + } + if (tag == Dart_kSourceTag) { + return DartState::Current()->library_loader().Source(library, url); + } + if (tag == Dart_kScriptTag) { + return DartIsolateReloader::HandleLibraryTag(tag, library, url); + } + FTL_NOTREACHED(); + return Dart_NewApiError("Unknown library tag."); +} + +void DartLibraryLoader::WaitForDependencies( + const std::unordered_set& dependencies, + const ftl::Closure& callback) { + if (dependencies.empty()) + return callback(); + dependency_watchers_.insert(std::unique_ptr( + new DependencyWatcher(dependencies, callback))); +} + +void DartLibraryLoader::LoadLibrary(const std::string& name) { + const auto& result = pending_libraries_.insert(std::make_pair(name, nullptr)); + if (result.second) { + // New entry. + std::unique_ptr job = + std::unique_ptr(new ImportJob(this, name, false)); + result.first->second = job.get(); + jobs_.insert(std::move(job)); + } + if (dependency_catcher_) + dependency_catcher_->AddDependency(result.first->second); +} + +void DartLibraryLoader::LoadScript(const std::string& name) { + const auto& result = pending_libraries_.insert(std::make_pair(name, nullptr)); + if (result.second) { + // New entry. + std::unique_ptr job = + std::unique_ptr(new ImportJob(this, name, true)); + result.first->second = job.get(); + jobs_.insert(std::move(job)); + } + if (dependency_catcher_) + dependency_catcher_->AddDependency(result.first->second); +} + +Dart_Handle DartLibraryLoader::Import(Dart_Handle library, Dart_Handle url) { + LoadLibrary(StdStringFromDart(url)); + return Dart_True(); +} + +Dart_Handle DartLibraryLoader::Source(Dart_Handle library, Dart_Handle url) { + std::unique_ptr job = std::unique_ptr( + new SourceJob(this, StdStringFromDart(url), library)); + if (dependency_catcher_) + dependency_catcher_->AddDependency(job.get()); + jobs_.insert(std::move(job)); + return Dart_True(); +} + +Dart_Handle DartLibraryLoader::CanonicalizeURL(Dart_Handle library, + Dart_Handle url) { + return library_provider_->CanonicalizeURL(library, url); +} + +void DartLibraryLoader::DidCompleteImportJob(ImportJob* job, + std::vector buffer) { + tonic::DartIsolateScope scope(dart_state_->isolate()); + tonic::DartApiScope api_scope; + + WatcherSignaler watcher_signaler(*this, job); + + Dart_Handle result; + Dart_Handle source = Dart_NewStringFromUTF8( + reinterpret_cast(buffer.data()), buffer.size()); + + if (job->should_load_as_script()) { + result = Dart_LoadScript(ToDart(job->name()), ToDart(job->resolved_url()), + source, 0, 0); + } else { + result = Dart_LoadLibrary(ToDart(job->name()), ToDart(job->resolved_url()), + source, 0, 0); + } + if (Dart_IsError(result)) { + FTL_LOG(ERROR) << "Error Loading " << job->name() << " " + << Dart_GetError(result); + } + + pending_libraries_.erase(job->name()); + EraseUniquePtr(jobs_, job); +} + +void DartLibraryLoader::DidCompleteSourceJob(SourceJob* job, + std::vector buffer) { + tonic::DartIsolateScope scope(dart_state_->isolate()); + tonic::DartApiScope api_scope; + + WatcherSignaler watcher_signaler(*this, job); + + Dart_Handle source = Dart_NewStringFromUTF8( + reinterpret_cast(buffer.data()), buffer.size()); + Dart_Handle result = Dart_LoadSource( + Dart_HandleFromPersistent(job->library()), ToDart(job->name()), + ToDart(job->resolved_url()), source, 0, 0); + + if (Dart_IsError(result)) { + FTL_LOG(ERROR) << "Error Loading " << job->name() << " " + << Dart_GetError(result); + } + + EraseUniquePtr(jobs_, job); +} + +void DartLibraryLoader::DidFailJob(Job* job) { + tonic::DartIsolateScope scope(dart_state_->isolate()); + tonic::DartApiScope api_scope; + + WatcherSignaler watcher_signaler(*this, job); + + FTL_LOG(ERROR) << "Library Load failed: " << job->name(); + // TODO(eseidel): Call Dart_LibraryHandleError in the SourceJob case? + + EraseUniquePtr(jobs_, job); +} + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_library_loader.h b/engine/src/flutter/tonic/dart_library_loader.h new file mode 100644 index 0000000000..346da4b57f --- /dev/null +++ b/engine/src/flutter/tonic/dart_library_loader.h @@ -0,0 +1,86 @@ +// 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 FLUTTER_TONIC_DART_LIBRARY_LOADER_H_ +#define FLUTTER_TONIC_DART_LIBRARY_LOADER_H_ + +#include +#include +#include +#include +#include + +#include "dart/runtime/include/dart_api.h" +#include "lib/ftl/functional/closure.h" +#include "lib/ftl/logging.h" +#include "lib/ftl/macros.h" + +namespace blink { +class DartDependency; +class DartDependencyCatcher; +class DartLibraryProvider; +class DartState; + +// TODO(abarth): This class seems more complicated than it needs to be. Is +// there some way of simplifying this system? For example, we have a bunch +// of inner classes that could potentially be factored out in some other way. +class DartLibraryLoader { + public: + explicit DartLibraryLoader(DartState* dart_state); + ~DartLibraryLoader(); + + // TODO(dart): This can be called both on the main thread from application + // isolates or from the handle watcher isolate thread. + static Dart_Handle HandleLibraryTag(Dart_LibraryTag tag, + Dart_Handle library, + Dart_Handle url); + + void LoadLibrary(const std::string& name); + void LoadScript(const std::string& name); + + void WaitForDependencies( + const std::unordered_set& dependencies, + const ftl::Closure& callback); + + void set_dependency_catcher(DartDependencyCatcher* dependency_catcher) { + FTL_DCHECK(!dependency_catcher_ || !dependency_catcher); + dependency_catcher_ = dependency_catcher; + } + + DartState* dart_state() const { return dart_state_; } + + DartLibraryProvider* library_provider() const { return library_provider_; } + + // The |DartLibraryProvider| must outlive the |DartLibraryLoader|. + void set_library_provider(DartLibraryProvider* library_provider) { + library_provider_ = library_provider; + } + + private: + class Job; + class ImportJob; + class SourceJob; + class DependencyWatcher; + class WatcherSignaler; + + Dart_Handle Import(Dart_Handle library, Dart_Handle url); + Dart_Handle Source(Dart_Handle library, Dart_Handle url); + Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url); + void DidCompleteImportJob(ImportJob* job, std::vector buffer); + void DidCompleteSourceJob(SourceJob* job, std::vector buffer); + void DidFailJob(Job* job); + + DartState* dart_state_; + DartLibraryProvider* library_provider_; + std::unordered_map pending_libraries_; + std::unordered_set> jobs_; + std::unordered_set> dependency_watchers_; + DartDependencyCatcher* dependency_catcher_; + + FTL_DISALLOW_COPY_AND_ASSIGN(DartLibraryLoader); +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_LIBRARY_LOADER_H_ diff --git a/engine/src/flutter/tonic/dart_library_provider.cc b/engine/src/flutter/tonic/dart_library_provider.cc new file mode 100644 index 0000000000..3495170dd8 --- /dev/null +++ b/engine/src/flutter/tonic/dart_library_provider.cc @@ -0,0 +1,12 @@ +// 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 "flutter/tonic/dart_library_provider.h" + +namespace blink { + +DartLibraryProvider::~DartLibraryProvider() { +} + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_library_provider.h b/engine/src/flutter/tonic/dart_library_provider.h new file mode 100644 index 0000000000..57b397bdec --- /dev/null +++ b/engine/src/flutter/tonic/dart_library_provider.h @@ -0,0 +1,32 @@ +// 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 FLUTTER_TONIC_DART_LIBRARY_PROVIDER_H_ +#define FLUTTER_TONIC_DART_LIBRARY_PROVIDER_H_ + +#include +#include + +#include "dart/runtime/include/dart_api.h" +#include "mojo/public/cpp/system/data_pipe.h" + +namespace blink { + +struct DartLibraryStream { + mojo::ScopedDataPipeConsumerHandle handle; + std::string resolved_url; +}; + +class DartLibraryProvider { + public: + virtual DartLibraryStream GetLibraryAsStream(const std::string& name) = 0; + + virtual Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url) = 0; + + virtual ~DartLibraryProvider(); +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_LIBRARY_PROVIDER_H_ diff --git a/engine/src/flutter/tonic/dart_library_provider_files.cc b/engine/src/flutter/tonic/dart_library_provider_files.cc new file mode 100644 index 0000000000..a8cd455b97 --- /dev/null +++ b/engine/src/flutter/tonic/dart_library_provider_files.cc @@ -0,0 +1,159 @@ +// 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 "flutter/tonic/dart_library_provider_files.h" + +#include "base/bind.h" +#include "base/files/file_util.h" +#include "base/strings/string_util.h" +#include "base/threading/worker_pool.h" +#include "lib/tonic/converter/dart_converter.h" +#include "mojo/data_pipe_utils/data_pipe_utils.h" + +namespace sky { +namespace shell { +namespace { + +void CopyComplete(base::FilePath file, std::string uri, bool success) { + if (!success) + LOG(FATAL) << "Failed to load " << file.AsUTF8Unsafe() << " (" << uri + << ")"; +} + +// Extract the scheme prefix ('package:' or 'file:' from ) +static std::string ExtractSchemePrefix(std::string url) { + if (base::StartsWithASCII(url, "package:", true)) { + return "package:"; + } else if (base::StartsWithASCII(url, "file:", true)) { + return "file:"; + } + return ""; +} + +// Extract the path from a package: or file: url. +static std::string ExtractPath(std::string url) { + if (base::StartsWithASCII(url, "package:", true)) { + base::ReplaceFirstSubstringAfterOffset(&url, 0, "package:", ""); + } else if (base::StartsWithASCII(url, "file:", true)) { + base::ReplaceFirstSubstringAfterOffset(&url, 0, "file:", ""); + } + return url; +} + +base::FilePath SimplifyPath(const base::FilePath& path) { + std::vector components; + path.GetComponents(&components); + auto it = components.begin(); + base::FilePath result(*it++); + for (; it != components.end(); it++) { + auto& component = *it; + if (component == base::FilePath::kCurrentDirectory) + continue; + if (component == base::FilePath::kParentDirectory) + result = result.DirName(); + else + result = result.Append(component); + } + return result; +} + +} // namespace + +DartLibraryProviderFiles::DartLibraryProviderFiles() {} + +DartLibraryProviderFiles::~DartLibraryProviderFiles() {} + +void DartLibraryProviderFiles::LoadPackagesMap(const std::string& packages) { + packages_ = base::FilePath(packages); + std::string packages_source; + if (!base::ReadFileToString(base::MakeAbsoluteFilePath(packages_), + &packages_source)) { + LOG(ERROR) << "error: Unable to load .packages file '" + << packages_.AsUTF8Unsafe() << "'."; + exit(1); + } + std::string error; + if (!packages_map_.Parse(packages_source, &error)) { + LOG(ERROR) << "error: Unable to parse .packages file '" + << packages_.AsUTF8Unsafe() << "'.\n" + << error; + exit(1); + } +} + +blink::DartLibraryStream DartLibraryProviderFiles::GetLibraryAsStream( + const std::string& name) { + mojo::DataPipe pipe; + base::FilePath path = GetFilePathForURL(name); + base::FilePath source = base::MakeAbsoluteFilePath(path); + blink::DartLibraryStream result; + result.handle = std::move(pipe.consumer_handle); + result.resolved_url = "file://" + source.value(); + scoped_refptr runner = + base::WorkerPool::GetTaskRunner(true); + mojo::common::CopyFromFile(source, pipe.producer_handle.Pass(), 0, + runner.get(), + base::Bind(&CopyComplete, source, name)); + return result; +} + +Dart_Handle DartLibraryProviderFiles::CanonicalizeURL(Dart_Handle library, + Dart_Handle url) { + std::string string = tonic::StdStringFromDart(url); + if (base::StartsWithASCII(string, "dart:", true)) + return url; + if (base::StartsWithASCII(string, "package:", true)) + return url; + if (base::StartsWithASCII(string, "file:", true)) { + base::ReplaceFirstSubstringAfterOffset(&string, 0, "file:", ""); + return tonic::StdStringToDart(string); + ; + } + + std::string library_url = tonic::StdStringFromDart(Dart_LibraryUrl(library)); + std::string prefix = ExtractSchemePrefix(library_url); + std::string path = ExtractPath(library_url); + base::FilePath base_path(path); + base::FilePath resolved_path = base_path.DirName().Append(string); + base::FilePath normalized_path = SimplifyPath(resolved_path); + return tonic::StdStringToDart(prefix + normalized_path.AsUTF8Unsafe()); +} + +base::FilePath DartLibraryProviderFiles::GetFilePathForURL(std::string url) { + if (base::StartsWithASCII(url, "package:", true)) + return GetFilePathForPackageURL(url); + if (base::StartsWithASCII(url, "file:", true)) + return GetFilePathForFileURL(url); + + return base::FilePath(url); +} + +base::FilePath DartLibraryProviderFiles::GetFilePathForPackageURL( + std::string url) { + DCHECK(base::StartsWithASCII(url, "package:", true)); + base::ReplaceFirstSubstringAfterOffset(&url, 0, "package:", ""); + size_t slash = url.find('/'); + if (slash == std::string::npos) + return base::FilePath(); + std::string package = url.substr(0, slash); + std::string library_path = url.substr(slash + 1); + std::string package_path = packages_map_.Resolve(package); + if (package_path.empty()) + return base::FilePath(); + if (base::StartsWithASCII(package_path, "file://", true)) { + base::ReplaceFirstSubstringAfterOffset(&package_path, 0, "file://", ""); + return base::FilePath(package_path + library_path); + } + return packages_.DirName().Append(package_path).Append(library_path); +} + +base::FilePath DartLibraryProviderFiles::GetFilePathForFileURL( + std::string url) { + DCHECK(base::StartsWithASCII(url, "file://", true)); + base::ReplaceFirstSubstringAfterOffset(&url, 0, "file://", ""); + return base::FilePath(url); +} + +} // namespace shell +} // namespace sky diff --git a/engine/src/flutter/tonic/dart_library_provider_files.h b/engine/src/flutter/tonic/dart_library_provider_files.h new file mode 100644 index 0000000000..7746c5b60c --- /dev/null +++ b/engine/src/flutter/tonic/dart_library_provider_files.h @@ -0,0 +1,42 @@ +// 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_FILES_H_ +#define SKY_SHELL_DART_DART_LIBRARY_PROVIDER_FILES_H_ + +#include "base/files/file_path.h" +#include "flutter/tonic/dart_library_provider.h" +#include "lib/ftl/macros.h" +#include "lib/tonic/parsers/packages_map.h" + +namespace sky { +namespace shell { + +class DartLibraryProviderFiles : public blink::DartLibraryProvider { + public: + DartLibraryProviderFiles(); + ~DartLibraryProviderFiles() override; + + void LoadPackagesMap(const std::string& packages); + + protected: + // |DartLibraryProvider| implementation: + blink::DartLibraryStream GetLibraryAsStream(const std::string& name) override; + Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url) override; + + private: + base::FilePath GetFilePathForURL(std::string url); + base::FilePath GetFilePathForPackageURL(std::string url); + base::FilePath GetFilePathForFileURL(std::string url); + + base::FilePath packages_; + tonic::PackagesMap packages_map_; + + FTL_DISALLOW_COPY_AND_ASSIGN(DartLibraryProviderFiles); +}; + +} // namespace shell +} // namespace sky + +#endif // SKY_SHELL_DART_DART_LIBRARY_PROVIDER_FILES_H_ diff --git a/engine/src/flutter/tonic/dart_snapshot_loader.cc b/engine/src/flutter/tonic/dart_snapshot_loader.cc new file mode 100644 index 0000000000..c6546df4d1 --- /dev/null +++ b/engine/src/flutter/tonic/dart_snapshot_loader.cc @@ -0,0 +1,46 @@ +// 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 "flutter/tonic/dart_snapshot_loader.h" + +#include + +#include "flutter/tonic/dart_state.h" +#include "flutter/glue/trace_event.h" +#include "lib/tonic/converter/dart_converter.h" +#include "lib/tonic/logging/dart_error.h" +#include "lib/tonic/scopes/dart_api_scope.h" +#include "lib/tonic/scopes/dart_isolate_scope.h" + +using tonic::LogIfError; + +namespace blink { + +DartSnapshotLoader::DartSnapshotLoader(tonic::DartState* dart_state) + : dart_state_(dart_state->GetWeakPtr()) {} + +DartSnapshotLoader::~DartSnapshotLoader() {} + +void DartSnapshotLoader::LoadSnapshot(mojo::ScopedDataPipeConsumerHandle pipe, + const ftl::Closure& callback) { + TRACE_EVENT_ASYNC_BEGIN0("flutter", "DartSnapshotLoader::LoadSnapshot", this); + + drainer_.reset(new glue::DrainDataPipeJob( + std::move(pipe), [this, callback](std::vector buffer) { + TRACE_EVENT_ASYNC_END0("flutter", "DartSnapshotLoader::LoadSnapshot", + this); + // TODO(abarth): Should we check dart_state_ for null? + { + tonic::DartIsolateScope scope(dart_state_->isolate()); + tonic::DartApiScope api_scope; + + LogIfError(Dart_LoadScriptFromSnapshot( + reinterpret_cast(buffer.data()), buffer.size())); + } + + callback(); + })); +} + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_snapshot_loader.h b/engine/src/flutter/tonic/dart_snapshot_loader.h new file mode 100644 index 0000000000..237186c3f1 --- /dev/null +++ b/engine/src/flutter/tonic/dart_snapshot_loader.h @@ -0,0 +1,35 @@ +// 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 FLUTTER_TONIC_DART_SNAPSHOT_LOADER_H_ +#define FLUTTER_TONIC_DART_SNAPSHOT_LOADER_H_ + +#include + +#include "dart/runtime/include/dart_api.h" +#include "flutter/glue/drain_data_pipe_job.h" +#include "lib/ftl/functional/closure.h" +#include "lib/ftl/macros.h" +#include "lib/tonic/dart_state.h" + +namespace blink { + +class DartSnapshotLoader { + public: + explicit DartSnapshotLoader(tonic::DartState* dart_state); + ~DartSnapshotLoader(); + + void LoadSnapshot(mojo::ScopedDataPipeConsumerHandle pipe, + const ftl::Closure& callback); + + private: + ftl::WeakPtr dart_state_; + std::unique_ptr drainer_; + + FTL_DISALLOW_COPY_AND_ASSIGN(DartSnapshotLoader); +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_SNAPSHOT_LOADER_H_ diff --git a/engine/src/flutter/tonic/dart_state.cc b/engine/src/flutter/tonic/dart_state.cc new file mode 100644 index 0000000000..c0a85d5a51 --- /dev/null +++ b/engine/src/flutter/tonic/dart_state.cc @@ -0,0 +1,25 @@ +// 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 "flutter/tonic/dart_state.h" + +#include "lib/tonic/converter/dart_converter.h" +#include "flutter/tonic/dart_library_loader.h" + +namespace blink { + +DartState::DartState() + : library_loader_(new DartLibraryLoader(this)) {} + +DartState::~DartState() {} + +DartState* DartState::From(Dart_Isolate isolate) { + return static_cast(tonic::DartState::From(isolate)); +} + +DartState* DartState::Current() { + return static_cast(tonic::DartState::Current()); +} + +} // namespace blink diff --git a/engine/src/flutter/tonic/dart_state.h b/engine/src/flutter/tonic/dart_state.h new file mode 100644 index 0000000000..37724a0de2 --- /dev/null +++ b/engine/src/flutter/tonic/dart_state.h @@ -0,0 +1,51 @@ +// 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 FLUTTER_TONIC_DART_STATE_H_ +#define FLUTTER_TONIC_DART_STATE_H_ + +#include "dart/runtime/include/dart_api.h" +#include "flutter/tonic/dart_isolate_reloader.h" +#include "lib/tonic/dart_persistent_value.h" +#include "lib/tonic/dart_state.h" +#include "lib/tonic/scopes/dart_api_scope.h" +#include "lib/tonic/scopes/dart_isolate_scope.h" + +namespace blink { +class DartExceptionFactory; +class DartLibraryLoader; + +// DartState represents the state associated with a given Dart isolate. The +// lifetime of this object is controlled by the DartVM. If you want to hold a +// reference to a DartState instance, please hold a base::WeakPtr. +// +// DartState is analogous to gin::PerIsolateData and JSC::ExecState. +class DartState : public tonic::DartState { + public: + DartState(); + virtual ~DartState(); + + static DartState* From(Dart_Isolate isolate); + static DartState* Current(); + + DartLibraryLoader& library_loader() { return *library_loader_; } + + // Takes ownership of |isolate_reloader|. + void set_isolate_reloader( + std::unique_ptr isolate_reloader) { + isolate_reloader_ = std::move(isolate_reloader); + } + DartIsolateReloader* isolate_reloader() { return isolate_reloader_.get(); } + + private: + std::unique_ptr library_loader_; + std::unique_ptr isolate_reloader_; + + protected: + FTL_DISALLOW_COPY_AND_ASSIGN(DartState); +}; + +} // namespace blink + +#endif // FLUTTER_TONIC_DART_STATE_H_