Initial import of GLFW Linux shell from FDE (flutter/engine#8159)

Changes include:
- File structure
- Header guards
- Include paths
- Namespaces
- Integration with the engine's GN build
- Conversion from jsoncpp to rapidjson
- Style and clang-format adjustment to match engine repository
This commit is contained in:
stuartmorgan
2019-03-20 17:15:52 -04:00
committed by GitHub
parent 285eec928c
commit c3a14b5501
48 changed files with 3879 additions and 3 deletions

View File

@@ -544,6 +544,31 @@ FILE: ../../../flutter/shell/platform/android/platform_view_android_jni.cc
FILE: ../../../flutter/shell/platform/android/platform_view_android_jni.h
FILE: ../../../flutter/shell/platform/android/vsync_waiter_android.cc
FILE: ../../../flutter/shell/platform/android/vsync_waiter_android.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/engine_method_result.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/basic_message_channel.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/binary_messenger.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/engine_method_result.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/json_message_codec.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/json_method_codec.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/json_type.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/message_codec.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_call.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_channel.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_codec.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_result.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/include/flutter/plugin_registrar.h
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/json_message_codec.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/json_method_codec.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/method_call_unittests.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/plugin_registrar.cc
FILE: ../../../flutter/shell/platform/common/cpp/client_wrapper/plugin_registrar_unittests.cc
FILE: ../../../flutter/shell/platform/common/cpp/incoming_message_dispatcher.cc
FILE: ../../../flutter/shell/platform/common/cpp/incoming_message_dispatcher.h
FILE: ../../../flutter/shell/platform/common/cpp/public/flutter_export.h
FILE: ../../../flutter/shell/platform/common/cpp/public/flutter_messenger.h
FILE: ../../../flutter/shell/platform/common/cpp/public/flutter_plugin_registrar.h
FILE: ../../../flutter/shell/platform/common/cpp/text_input_model.cc
FILE: ../../../flutter/shell/platform/common/cpp/text_input_model.h
FILE: ../../../flutter/shell/platform/darwin/common/buffer_conversions.h
FILE: ../../../flutter/shell/platform/darwin/common/buffer_conversions.mm
FILE: ../../../flutter/shell/platform/darwin/common/command_line.h
@@ -660,6 +685,16 @@ FILE: ../../../flutter/shell/platform/embedder/platform_view_embedder.cc
FILE: ../../../flutter/shell/platform/embedder/platform_view_embedder.h
FILE: ../../../flutter/shell/platform/embedder/vsync_waiter_embedder.cc
FILE: ../../../flutter/shell/platform/embedder/vsync_waiter_embedder.h
FILE: ../../../flutter/shell/platform/glfw/client_wrapper/flutter_window_controller.cc
FILE: ../../../flutter/shell/platform/glfw/client_wrapper/flutter_window_controller_unittests.cc
FILE: ../../../flutter/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h
FILE: ../../../flutter/shell/platform/glfw/flutter_glfw.cc
FILE: ../../../flutter/shell/platform/glfw/key_event_handler.cc
FILE: ../../../flutter/shell/platform/glfw/key_event_handler.h
FILE: ../../../flutter/shell/platform/glfw/keyboard_hook_handler.h
FILE: ../../../flutter/shell/platform/glfw/public/flutter_glfw.h
FILE: ../../../flutter/shell/platform/glfw/text_input_plugin.cc
FILE: ../../../flutter/shell/platform/glfw/text_input_plugin.h
FILE: ../../../flutter/sky/packages/flutter_services/lib/empty.dart
FILE: ../../../flutter/sky/tools/roll/patches/chromium/android_build.patch
FILE: ../../../flutter/synchronization/pipeline.cc

View File

@@ -0,0 +1,63 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
config("desktop_library_implementation") {
defines = [ "FLUTTER_DESKTOP_LIBRARY" ]
}
_public_headers = [
"public/flutter_export.h",
"public/flutter_messenger.h",
"public/flutter_plugin_registrar.h",
]
# Any files that are built by clients (client_wrapper code, library headers for
# implementations using this shared code, etc.) include the public headers
# assuming they are in the include path. This configuration should be added to
# any such code that is also built by GN to make the includes work.
config("relative_flutter_library_headers") {
include_dirs = [ "public" ]
}
# The headers are a separate source set since the client wrapper is allowed
# to depend on the public headers, but none of the rest of the code.
source_set("common_cpp_library_headers") {
public = _public_headers
configs += [ ":desktop_library_implementation" ]
}
source_set("common_cpp") {
public = [
"incoming_message_dispatcher.h",
"text_input_model.h",
]
# TODO: Refactor flutter_glfw.cc to move the implementations corresponding
# to the _public_headers above into this target.
sources = [
"incoming_message_dispatcher.cc",
"text_input_model.cc",
]
configs += [ ":desktop_library_implementation" ]
deps = [
":common_cpp_library_headers",
"$flutter_root/shell/platform/common/cpp/client_wrapper:client_wrapper",
"$flutter_root/shell/platform/embedder:embedder",
]
# TODO: Remove once text input model refactor lands, at which point this code
# won't have a JSON dependency.
defines = [ "USE_RAPID_JSON" ]
deps += [ "//third_party/rapidjson" ]
}
copy("publish_headers") {
sources = _public_headers
outputs = [
"$root_out_dir/{{source_file_part}}",
]
}

View File

@@ -0,0 +1,88 @@
# Copyright 2013 The Flutter 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("publish.gni")
_wrapper_includes = [
"include/flutter/basic_message_channel.h",
"include/flutter/binary_messenger.h",
"include/flutter/engine_method_result.h",
"include/flutter/json_message_codec.h",
"include/flutter/json_method_codec.h",
"include/flutter/json_type.h",
"include/flutter/message_codec.h",
"include/flutter/method_call.h",
"include/flutter/method_channel.h",
"include/flutter/method_codec.h",
"include/flutter/method_result.h",
"include/flutter/plugin_registrar.h",
]
# TODO: Once the wrapper API is more stable, consolidate to as few files as is
# reasonable (without forcing different kinds of clients to take unnecessary
# code) to simplify use.
_wrapper_sources = [
"engine_method_result.cc",
"json_message_codec.cc",
"json_method_codec.cc",
"plugin_registrar.cc",
]
# Client library build for internal use by the shell implementation.
source_set("client_wrapper") {
sources = _wrapper_sources
public = _wrapper_includes
deps = [
"$flutter_root/shell/platform/common/cpp:common_cpp_library_headers",
"//third_party/rapidjson",
]
defines = [ "USE_RAPID_JSON" ]
configs += [
"$flutter_root/shell/platform/common/cpp:desktop_library_implementation",
]
public_configs = [
"$flutter_root/shell/platform/common/cpp:relative_flutter_library_headers",
]
}
# Copies the client wrapper code to the output directory.
publish_client_wrapper("publish_wrapper") {
public = _wrapper_includes
sources = _wrapper_sources + [ "README" ]
}
source_set("client_wrapper_library_stubs") {
sources = [
"testing/stub_flutter_api.cc",
"testing/stub_flutter_api.h",
]
public_deps = [
"$flutter_root/shell/platform/common/cpp:common_cpp_library_headers",
]
}
executable("client_wrapper_unittests") {
testonly = true
# TODO: Add more unit tests.
sources = [
"method_call_unittests.cc",
"plugin_registrar_unittests.cc",
]
deps = [
":client_wrapper",
":client_wrapper_library_stubs",
"$flutter_root/testing",
# TODO: Consider refactoring flutter_root/testing so that there's a testing
# target that doesn't require a Dart runtime to be linked in.
"//third_party/dart/runtime:libdart_jit",
]
}

View File

@@ -0,0 +1,9 @@
This code is intended to be built into plugins and applications to provide
higher-level, C++ abstractions for interacting with the Flutter library.
Over time, the goal is to move more of this code into the library in a way that
provides a usable ABI (e.g., does not use standard libary in the interfaces).
Note that this wrapper is still in early stages. Expect significant churn in
both the APIs and the structure of the wrapper (e.g., the exact set of files
that need to be built).

View File

@@ -0,0 +1,45 @@
// Copyright 2013 The Flutter 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 "include/flutter/engine_method_result.h"
#include <assert.h>
#include <iostream>
namespace flutter {
namespace internal {
ReplyManager::ReplyManager(BinaryReply reply_handler)
: reply_handler_(std::move(reply_handler)) {
assert(reply_handler_);
}
ReplyManager::~ReplyManager() {
if (reply_handler_) {
// Warn, rather than send a not-implemented response, since the engine may
// no longer be valid at this point.
std::cerr
<< "Warning: Failed to respond to a message. This is a memory leak."
<< std::endl;
}
}
void ReplyManager::SendResponseData(const std::vector<uint8_t>* data) {
if (!reply_handler_) {
std::cerr
<< "Error: Only one of Success, Error, or NotImplemented can be "
"called,"
<< " and it can be called exactly once. Ignoring duplicate result."
<< std::endl;
return;
}
const uint8_t* message = data && !data->empty() ? data->data() : nullptr;
size_t message_size = data ? data->size() : 0;
reply_handler_(message, message_size);
reply_handler_ = nullptr;
}
} // namespace internal
} // namespace flutter

View File

@@ -0,0 +1,98 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_
#include <iostream>
#include <string>
#include "binary_messenger.h"
#include "message_codec.h"
namespace flutter {
// A message reply callback.
//
// Used for submitting a reply back to a Flutter message sender.
template <typename T>
using MessageReply = std::function<void(const T& reply)>;
// A handler for receiving a message from the Flutter engine.
//
// Implementations must asynchronously call reply exactly once with the reply
// to the message.
template <typename T>
using MessageHandler =
std::function<void(const T& message, MessageReply<T> reply)>;
// A channel for communicating with the Flutter engine by sending asynchronous
// messages.
template <typename T>
class BasicMessageChannel {
public:
// Creates an instance that sends and receives method calls on the channel
// named |name|, encoded with |codec| and dispatched via |messenger|.
//
// TODO: Make codec optional once the standard codec is supported (Issue #67).
BasicMessageChannel(BinaryMessenger* messenger,
const std::string& name,
const MessageCodec<T>* codec)
: messenger_(messenger), name_(name), codec_(codec) {}
~BasicMessageChannel() = default;
// Prevent copying.
BasicMessageChannel(BasicMessageChannel const&) = delete;
BasicMessageChannel& operator=(BasicMessageChannel const&) = delete;
// Sends a message to the Flutter engine on this channel.
void Send(const T& message) {
std::unique_ptr<std::vector<uint8_t>> raw_message =
codec_->EncodeMessage(message);
messenger_->Send(name_, raw_message->data(), raw_message->size());
}
// TODO: Add support for a version of Send expecting a reply once
// https://github.com/flutter/flutter/issues/18852 is fixed.
// Registers a handler that should be called any time a message is
// received on this channel.
void SetMessageHandler(MessageHandler<T> handler) const {
const auto* codec = codec_;
std::string channel_name = name_;
BinaryMessageHandler binary_handler = [handler, codec, channel_name](
const uint8_t* binary_message,
const size_t binary_message_size,
BinaryReply binary_reply) {
// Use this channel's codec to decode the message and build a reply
// handler.
std::unique_ptr<T> message =
codec->DecodeMessage(binary_message, binary_message_size);
if (!message) {
std::cerr << "Unable to decode message on channel " << channel_name
<< std::endl;
binary_reply(nullptr, 0);
return;
}
MessageReply<T> unencoded_reply = [binary_reply,
codec](const T& unencoded_response) {
auto binary_response = codec->EncodeMessage(unencoded_response);
binary_reply(binary_response->data(), binary_response->size());
};
handler(*message, std::move(unencoded_reply));
};
messenger_->SetMessageHandler(name_, std::move(binary_handler));
}
private:
BinaryMessenger* messenger_;
std::string name_;
const MessageCodec<T>* codec_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_BASIC_MESSAGE_CHANNEL_H_

View File

@@ -0,0 +1,56 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_
#include <functional>
#include <string>
// TODO: Consider adding absl as a dependency and using absl::Span for all of
// the message/message_size pairs.
namespace flutter {
// A binary message reply callback.
//
// Used for submitting a binary reply back to a Flutter message sender.
typedef std::function<void(const uint8_t* reply, const size_t reply_size)>
BinaryReply;
// A message handler callback.
//
// Used for receiving messages from Flutter and providing an asynchronous reply.
typedef std::function<
void(const uint8_t* message, const size_t message_size, BinaryReply reply)>
BinaryMessageHandler;
// A protocol for a class that handles communication of binary data on named
// channels to and from the Flutter engine.
class BinaryMessenger {
public:
virtual ~BinaryMessenger() = default;
// Sends a binary message to the Flutter side on the specified channel,
// expecting no reply.
//
// TODO: Consider adding absl as a dependency and using absl::Span.
virtual void Send(const std::string& channel,
const uint8_t* message,
const size_t message_size) const = 0;
// TODO: Add support for a version of Send expecting a reply once
// https://github.com/flutter/flutter/issues/18852 is fixed.
// Registers a message handler for incoming binary messages from the Flutter
// side on the specified channel.
//
// Replaces any existing handler. Provide a null handler to unregister the
// existing handler.
virtual void SetMessageHandler(const std::string& channel,
BinaryMessageHandler handler) = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_BINARY_MESSENGER_H_

View File

@@ -0,0 +1,86 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENGINE_METHOD_RESULT_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENGINE_METHOD_RESULT_H_
#include <memory>
#include <string>
#include <vector>
#include "binary_messenger.h"
#include "method_codec.h"
#include "method_result.h"
namespace flutter {
namespace internal {
// Manages the one-time sending of response data. This is an internal helper
// class for EngineMethodResult, separated out since the implementation doesn't
// vary based on the template type.
class ReplyManager {
public:
ReplyManager(BinaryReply reply_handler_);
~ReplyManager();
// Prevent copying.
ReplyManager(ReplyManager const&) = delete;
ReplyManager& operator=(ReplyManager const&) = delete;
// Sends the given response data (which must either be nullptr, which
// indicates an unhandled method, or a response serialized with |codec_|) to
// the engine.
void SendResponseData(const std::vector<uint8_t>* data);
private:
BinaryReply reply_handler_;
};
} // namespace internal
// Implemention of MethodResult that sends a response to the Flutter engine
// exactly once, encoded using a given codec.
template <typename T>
class EngineMethodResult : public MethodResult<T> {
public:
// Creates a result object that will send results to |reply_handler|, encoded
// using |codec|. The |codec| pointer must remain valid for as long as this
// object exists.
EngineMethodResult(BinaryReply reply_handler, const MethodCodec<T>* codec)
: reply_manager_(
std::make_unique<internal::ReplyManager>(std::move(reply_handler))),
codec_(codec) {}
~EngineMethodResult() = default;
protected:
// |flutter::MethodResult|
void SuccessInternal(const T* result) override {
std::unique_ptr<std::vector<uint8_t>> data =
codec_->EncodeSuccessEnvelope(result);
reply_manager_->SendResponseData(data.get());
}
// |flutter::MethodResult|
void ErrorInternal(const std::string& error_code,
const std::string& error_message,
const T* error_details) override {
std::unique_ptr<std::vector<uint8_t>> data =
codec_->EncodeErrorEnvelope(error_code, error_message, error_details);
reply_manager_->SendResponseData(data.get());
}
// |flutter::MethodResult|
void NotImplementedInternal() override {
reply_manager_->SendResponseData(nullptr);
}
private:
std::unique_ptr<internal::ReplyManager> reply_manager_;
const MethodCodec<T>* codec_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_ENGINE_METHOD_RESULT_H_

View File

@@ -0,0 +1,42 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_MESSAGE_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_MESSAGE_CODEC_H_
#include "json_type.h"
#include "message_codec.h"
namespace flutter {
// A message encoding/decoding mechanism for communications to/from the
// Flutter engine via JSON channels.
class JsonMessageCodec : public MessageCodec<JsonValueType> {
public:
// Returns the shared instance of the codec.
static const JsonMessageCodec& GetInstance();
~JsonMessageCodec() = default;
// Prevent copying.
JsonMessageCodec(JsonMessageCodec const&) = delete;
JsonMessageCodec& operator=(JsonMessageCodec const&) = delete;
protected:
// Instances should be obtained via GetInstance.
JsonMessageCodec() = default;
// |flutter::MessageCodec|
std::unique_ptr<JsonValueType> DecodeMessageInternal(
const uint8_t* binary_message,
const size_t message_size) const override;
// |flutter::MessageCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeMessageInternal(
const JsonValueType& message) const override;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_MESSAGE_CODEC_H_

View File

@@ -0,0 +1,52 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_METHOD_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_METHOD_CODEC_H_
#include "json_type.h"
#include "method_call.h"
#include "method_codec.h"
namespace flutter {
// An implementation of MethodCodec that uses JSON strings as the serialization.
class JsonMethodCodec : public MethodCodec<JsonValueType> {
public:
// Returns the shared instance of the codec.
static const JsonMethodCodec& GetInstance();
~JsonMethodCodec() = default;
// Prevent copying.
JsonMethodCodec(JsonMethodCodec const&) = delete;
JsonMethodCodec& operator=(JsonMethodCodec const&) = delete;
protected:
// Instances should be obtained via GetInstance.
JsonMethodCodec() = default;
// |flutter::MethodCodec|
std::unique_ptr<MethodCall<JsonValueType>> DecodeMethodCallInternal(
const uint8_t* message,
const size_t message_size) const override;
// |flutter::MethodCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeMethodCallInternal(
const MethodCall<JsonValueType>& method_call) const override;
// |flutter::MethodCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelopeInternal(
const JsonValueType* result) const override;
// |flutter::MethodCodec|
std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelopeInternal(
const std::string& error_code,
const std::string& error_message,
const JsonValueType* error_details) const override;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_METHOD_CODEC_H_

View File

@@ -0,0 +1,26 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_TYPE_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_TYPE_H_
// By default, the Json codecs use jsoncpp, but a version using RapidJSON is
// implemented as well. To use the latter, set USE_RAPID_JSON.
//
// When writing code using the JSON codec classes, do not use JsonValueType;
// instead use the underlying type for the library you have selected directly.
#ifdef USE_RAPID_JSON
#include <rapidjson/document.h>
// The APIs often pass owning references, which in RapidJSON must include the
// allocator, so the value type for the APIs is Document rather than Value.
using JsonValueType = rapidjson::Document;
#else
#include <json/json.h>
using JsonValueType = Json::Value;
#endif
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_JSON_TYPE_H_

View File

@@ -0,0 +1,54 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_
#include <memory>
#include <string>
#include <vector>
namespace flutter {
// Translates between a binary message and higher-level method call and
// response/error objects.
template <typename T>
class MessageCodec {
public:
MessageCodec() = default;
virtual ~MessageCodec() = default;
// Prevent copying.
MessageCodec(MessageCodec<T> const&) = delete;
MessageCodec& operator=(MessageCodec<T> const&) = delete;
// Returns the message encoded in |binary_message|, or nullptr if it cannot be
// decoded by this codec.
// TODO: Consider adding absl as a dependency and using absl::Span.
std::unique_ptr<T> DecodeMessage(const uint8_t* binary_message,
const size_t message_size) const {
return std::move(DecodeMessageInternal(binary_message, message_size));
}
// Returns a binary encoding of the given |message|, or nullptr if the
// message cannot be serialized by this codec.
std::unique_ptr<std::vector<uint8_t>> EncodeMessage(const T& message) const {
return std::move(EncodeMessageInternal(message));
}
protected:
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<T> DecodeMessageInternal(
const uint8_t* binary_message,
const size_t message_size) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<std::vector<uint8_t>> EncodeMessageInternal(
const T& message) const = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_MESSAGE_CODEC_H_

View File

@@ -0,0 +1,41 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_TYPED_METHOD_CALL_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_TYPED_METHOD_CALL_H_
#include <memory>
#include <string>
namespace flutter {
// An object encapsulating a method call from Flutter whose arguments are of
// type T.
template <typename T>
class MethodCall {
public:
// Creates a MethodCall with the given name and arguments.
MethodCall(const std::string& method_name, std::unique_ptr<T> arguments)
: method_name_(method_name), arguments_(std::move(arguments)) {}
virtual ~MethodCall() = default;
// Prevent copying.
MethodCall(MethodCall<T> const&) = delete;
MethodCall& operator=(MethodCall<T> const&) = delete;
// The name of the method being called.
const std::string& method_name() const { return method_name_; }
// The arguments to the method call, or NULL if there are none.
const T* arguments() const { return arguments_.get(); }
private:
std::string method_name_;
std::unique_ptr<T> arguments_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_TYPED_METHOD_CALL_H_

View File

@@ -0,0 +1,92 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_
#include <iostream>
#include <string>
#include "binary_messenger.h"
#include "engine_method_result.h"
#include "method_call.h"
#include "method_codec.h"
#include "method_result.h"
namespace flutter {
// A handler for receiving a method call from the Flutter engine.
//
// Implementations must asynchronously call exactly one of the methods on
// |result| to indicate the result of the method call.
template <typename T>
using MethodCallHandler =
std::function<void(const MethodCall<T>& call,
std::unique_ptr<MethodResult<T>> result)>;
// A channel for communicating with the Flutter engine using invocation of
// asynchronous methods.
template <typename T>
class MethodChannel {
public:
// Creates an instance that sends and receives method calls on the channel
// named |name|, encoded with |codec| and dispatched via |messenger|.
//
// TODO: Make codec optional once the standard codec is supported (Issue #67).
MethodChannel(BinaryMessenger* messenger,
const std::string& name,
const MethodCodec<T>* codec)
: messenger_(messenger), name_(name), codec_(codec) {}
~MethodChannel() = default;
// Prevent copying.
MethodChannel(MethodChannel const&) = delete;
MethodChannel& operator=(MethodChannel const&) = delete;
// Sends a message to the Flutter engine on this channel.
void InvokeMethod(const std::string& method, std::unique_ptr<T> arguments) {
MethodCall<T> method_call(method, std::move(arguments));
std::unique_ptr<std::vector<uint8_t>> message =
codec_->EncodeMethodCall(method_call);
messenger_->Send(name_, message->data(), message->size());
}
// TODO: Add support for a version of InvokeMethod expecting a reply once
// https://github.com/flutter/flutter/issues/18852 is fixed.
// Registers a handler that should be called any time a method call is
// received on this channel.
void SetMethodCallHandler(MethodCallHandler<T> handler) const {
const auto* codec = codec_;
std::string channel_name = name_;
BinaryMessageHandler binary_handler = [handler, codec, channel_name](
const uint8_t* message,
const size_t message_size,
BinaryReply reply) {
// Use this channel's codec to decode the call and build a result handler.
auto result =
std::make_unique<EngineMethodResult<T>>(std::move(reply), codec);
std::unique_ptr<MethodCall<T>> method_call =
codec->DecodeMethodCall(message, message_size);
if (!method_call) {
std::cerr << "Unable to construct method call from message on channel "
<< channel_name << std::endl;
result->NotImplemented();
return;
}
handler(*method_call, std::move(result));
};
messenger_->SetMessageHandler(name_, std::move(binary_handler));
}
private:
BinaryMessenger* messenger_;
std::string name_;
const MethodCodec<T>* codec_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CHANNEL_H_

View File

@@ -0,0 +1,85 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_
#include <memory>
#include <string>
#include <vector>
#include "method_call.h"
namespace flutter {
// Translates between a binary message and higher-level method call and
// response/error objects.
template <typename T>
class MethodCodec {
public:
MethodCodec() = default;
virtual ~MethodCodec() = default;
// Prevent copying.
MethodCodec(MethodCodec<T> const&) = delete;
MethodCodec& operator=(MethodCodec<T> const&) = delete;
// Returns the MethodCall encoded in |message|, or nullptr if it cannot be
// decoded.
// TODO: Consider adding absl as a dependency and using absl::Span.
std::unique_ptr<MethodCall<T>> DecodeMethodCall(
const uint8_t* message,
const size_t message_size) const {
return std::move(DecodeMethodCallInternal(message, message_size));
}
// Returns a binary encoding of the given |method_call|, or nullptr if the
// method call cannot be serialized by this codec.
std::unique_ptr<std::vector<uint8_t>> EncodeMethodCall(
const MethodCall<T>& method_call) const {
return std::move(EncodeMethodCallInternal(method_call));
}
// Returns a binary encoding of |result|. |result| must be a type supported
// by the codec.
std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelope(
const T* result = nullptr) const {
return std::move(EncodeSuccessEnvelopeInternal(result));
}
// Returns a binary encoding of |error|. The |error_details| must be a type
// supported by the codec.
std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelope(
const std::string& error_code,
const std::string& error_message = "",
const T* error_details = nullptr) const {
return std::move(
EncodeErrorEnvelopeInternal(error_code, error_message, error_details));
}
protected:
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<MethodCall<T>> DecodeMethodCallInternal(
const uint8_t* message,
const size_t message_size) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<std::vector<uint8_t>> EncodeMethodCallInternal(
const MethodCall<T>& method_call) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<std::vector<uint8_t>> EncodeSuccessEnvelopeInternal(
const T* result) const = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual std::unique_ptr<std::vector<uint8_t>> EncodeErrorEnvelopeInternal(
const std::string& error_code,
const std::string& error_message,
const T* error_details) const = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_CODEC_H_

View File

@@ -0,0 +1,58 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_
#include <string>
namespace flutter {
// Encapsulates a result sent back to the Flutter engine in response to a
// MethodCall. Only one method should be called on any given instance.
template <typename T>
class MethodResult {
public:
MethodResult() = default;
virtual ~MethodResult() = default;
// Prevent copying.
MethodResult(MethodResult const&) = delete;
MethodResult& operator=(MethodResult const&) = delete;
// Sends a success response, indicating that the call completed successfully.
// An optional value can be provided as part of the success message.
void Success(const T* result = nullptr) { SuccessInternal(result); }
// Sends an error response, indicating that the call was understood but
// handling failed in some way. A string error code must be provided, and in
// addition an optional user-readable error_message and/or details object can
// be included.
void Error(const std::string& error_code,
const std::string& error_message = "",
const T* error_details = nullptr) {
ErrorInternal(error_code, error_message, error_details);
}
// Sends a not-implemented response, indicating that the method either was not
// recognized, or has not been implemented.
void NotImplemented() { NotImplementedInternal(); }
protected:
// Implementation of the public interface, to be provided by subclasses.
virtual void SuccessInternal(const T* result) = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual void ErrorInternal(const std::string& error_code,
const std::string& error_message,
const T* error_details) = 0;
// Implementation of the public interface, to be provided by subclasses.
virtual void NotImplementedInternal() = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_METHOD_RESULT_H_

View File

@@ -0,0 +1,74 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_
#include <memory>
#include <set>
#include <string>
#include <flutter_plugin_registrar.h>
#include "binary_messenger.h"
namespace flutter {
class Plugin;
// A object managing the registration of a plugin for various events.
//
// Currently this class has very limited functionality, but is expected to
// expand over time to more closely match the functionality of
// the Flutter mobile plugin APIs' plugin registrars.
class PluginRegistrar {
public:
// Creates a new PluginRegistrar. |core_registrar| and the messenger it
// provides must remain valid as long as this object exists.
explicit PluginRegistrar(FlutterDesktopPluginRegistrarRef core_registrar);
~PluginRegistrar();
// Prevent copying.
PluginRegistrar(PluginRegistrar const&) = delete;
PluginRegistrar& operator=(PluginRegistrar const&) = delete;
// Returns the messenger to use for creating channels to communicate with the
// Flutter engine.
//
// This pointer will remain valid for the lifetime of this instance.
BinaryMessenger* messenger() { return messenger_.get(); }
// Takes ownership of |plugin|.
//
// Plugins are not required to call this method if they have other lifetime
// management, but this is a convient place for plugins to be owned to ensure
// that they stay valid for any registered callbacks.
void AddPlugin(std::unique_ptr<Plugin> plugin);
// Enables input blocking on the given channel name.
//
// If set, then the parent window should disable input callbacks
// while waiting for the handler for messages on that channel to run.
void EnableInputBlockingForChannel(const std::string& channel);
private:
// Handle for interacting with the C API's registrar.
FlutterDesktopPluginRegistrarRef registrar_;
std::unique_ptr<BinaryMessenger> messenger_;
// Plugins registered for ownership.
std::set<std::unique_ptr<Plugin>> plugins_;
};
// A plugin that can be registered for ownership by a PluginRegistrar.
class Plugin {
public:
virtual ~Plugin() = default;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_INCLUDE_FLUTTER_PLUGIN_REGISTRAR_H_

View File

@@ -0,0 +1,70 @@
// Copyright 2013 The Flutter 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 "include/flutter/json_message_codec.h"
#include <iostream>
#include <string>
#ifdef USE_RAPID_JSON
#include "rapidjson/error/en.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#endif
namespace flutter {
// static
const JsonMessageCodec& JsonMessageCodec::GetInstance() {
static JsonMessageCodec sInstance;
return sInstance;
}
std::unique_ptr<std::vector<uint8_t>> JsonMessageCodec::EncodeMessageInternal(
const JsonValueType& message) const {
#ifdef USE_RAPID_JSON
// TODO: Look into alternate writers that would avoid the buffer copy.
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
message.Accept(writer);
const char* buffer_start = buffer.GetString();
return std::make_unique<std::vector<uint8_t>>(
buffer_start, buffer_start + buffer.GetSize());
#else
Json::StreamWriterBuilder writer_builder;
std::string serialization = Json::writeString(writer_builder, message);
return std::make_unique<std::vector<uint8_t>>(serialization.begin(),
serialization.end());
#endif
}
std::unique_ptr<JsonValueType> JsonMessageCodec::DecodeMessageInternal(
const uint8_t* binary_message,
const size_t message_size) const {
auto raw_message = reinterpret_cast<const char*>(binary_message);
auto json_message = std::make_unique<JsonValueType>();
std::string parse_errors;
bool parsing_successful = false;
#ifdef USE_RAPID_JSON
rapidjson::ParseResult result =
json_message->Parse(raw_message, message_size);
parsing_successful = result == rapidjson::ParseErrorCode::kParseErrorNone;
if (!parsing_successful) {
parse_errors = rapidjson::GetParseError_En(result.Code());
}
#else
Json::CharReaderBuilder reader_builder;
std::unique_ptr<Json::CharReader> parser(reader_builder.newCharReader());
parsing_successful = parser->parse(raw_message, raw_message + message_size,
json_message.get(), &parse_errors);
#endif
if (!parsing_successful) {
std::cerr << "Unable to parse JSON message:" << std::endl
<< parse_errors << std::endl;
return nullptr;
}
return json_message;
}
} // namespace flutter

View File

@@ -0,0 +1,135 @@
// Copyright 2013 The Flutter 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 "include/flutter/json_method_codec.h"
#include "include/flutter/json_message_codec.h"
namespace flutter {
namespace {
// Keys used in MethodCall encoding.
constexpr char kMessageMethodKey[] = "method";
constexpr char kMessageArgumentsKey[] = "args";
} // namespace
// static
const JsonMethodCodec& JsonMethodCodec::GetInstance() {
static JsonMethodCodec sInstance;
return sInstance;
}
std::unique_ptr<MethodCall<JsonValueType>>
JsonMethodCodec::DecodeMethodCallInternal(const uint8_t* message,
const size_t message_size) const {
std::unique_ptr<JsonValueType> json_message =
JsonMessageCodec::GetInstance().DecodeMessage(message, message_size);
if (!json_message) {
return nullptr;
}
#if USE_RAPID_JSON
auto method_name_iter = json_message->FindMember(kMessageMethodKey);
if (method_name_iter == json_message->MemberEnd()) {
return nullptr;
}
if (!method_name_iter->value.IsString()) {
return nullptr;
}
std::string method_name(method_name_iter->value.GetString());
auto arguments_iter = json_message->FindMember(kMessageArgumentsKey);
std::unique_ptr<rapidjson::Document> arguments;
if (arguments_iter != json_message->MemberEnd()) {
// Pull the arguments subtree up to the root of json_message. This is
// destructive to json_message, but the full value is no longer needed, and
// this avoids a subtree copy.
json_message->Swap(arguments_iter->value);
// Swap it into |arguments|. This moves the allocator ownership, so that
// the data won't be deleted when json_message goes out of scope.
arguments = std::make_unique<rapidjson::Document>();
arguments->Swap(*json_message);
}
return std::make_unique<MethodCall<rapidjson::Document>>(
method_name, std::move(arguments));
#else
Json::Value method = (*json_message)[kMessageMethodKey];
if (method.isNull()) {
return nullptr;
}
return std::make_unique<MethodCall<Json::Value>>(
method.asString(),
std::make_unique<Json::Value>((*json_message)[kMessageArgumentsKey]));
#endif
}
std::unique_ptr<std::vector<uint8_t>> JsonMethodCodec::EncodeMethodCallInternal(
const MethodCall<JsonValueType>& method_call) const {
#if USE_RAPID_JSON
// TODO: Consider revisiting the codec APIs to avoid the need to copy
// everything when doing encoding (e.g., by having a version that takes
// owership of the object to encode, so that it can be moved instead).
rapidjson::Document message(rapidjson::kObjectType);
auto& allocator = message.GetAllocator();
rapidjson::Value name(method_call.method_name(), allocator);
rapidjson::Value arguments;
if (method_call.arguments()) {
arguments.CopyFrom(*method_call.arguments(), allocator);
}
message.AddMember(kMessageMethodKey, name, allocator);
message.AddMember(kMessageArgumentsKey, arguments, allocator);
#else
Json::Value message(Json::objectValue);
message[kMessageMethodKey] = method_call.method_name();
const Json::Value* arguments = method_call.arguments();
message[kMessageArgumentsKey] = arguments ? *arguments : Json::Value();
#endif
return JsonMessageCodec::GetInstance().EncodeMessage(message);
}
std::unique_ptr<std::vector<uint8_t>>
JsonMethodCodec::EncodeSuccessEnvelopeInternal(
const JsonValueType* result) const {
#if USE_RAPID_JSON
rapidjson::Document envelope;
envelope.SetArray();
rapidjson::Value result_value;
if (result) {
result_value.CopyFrom(*result, envelope.GetAllocator());
}
envelope.PushBack(result_value, envelope.GetAllocator());
#else
Json::Value envelope(Json::arrayValue);
envelope.append(result == nullptr ? Json::Value() : *result);
#endif
return JsonMessageCodec::GetInstance().EncodeMessage(envelope);
}
std::unique_ptr<std::vector<uint8_t>>
JsonMethodCodec::EncodeErrorEnvelopeInternal(
const std::string& error_code,
const std::string& error_message,
const JsonValueType* error_details) const {
#if USE_RAPID_JSON
rapidjson::Document envelope(rapidjson::kArrayType);
auto& allocator = envelope.GetAllocator();
envelope.PushBack(rapidjson::Value(error_code, allocator), allocator);
envelope.PushBack(rapidjson::Value(error_message, allocator), allocator);
rapidjson::Value details_value;
if (error_details) {
details_value.CopyFrom(*error_details, allocator);
}
envelope.PushBack(details_value, allocator);
#else
Json::Value envelope(Json::arrayValue);
envelope.append(error_code);
envelope.append(error_message.empty() ? Json::Value() : error_message);
envelope.append(error_details == nullptr ? Json::Value() : *error_details);
#endif
return JsonMessageCodec::GetInstance().EncodeMessage(envelope);
}
} // namespace flutter

View File

@@ -0,0 +1,23 @@
// Copyright 2013 The Flutter 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/shell/platform/common/cpp/client_wrapper/include/flutter/method_call.h"
#include <memory>
#include <string>
#include "gtest/gtest.h"
namespace flutter {
TEST(MethodCallTest, Basic) {
const std::string method_name("method_name");
const int argument = 42;
MethodCall<int> method_call(method_name, std::make_unique<int>(argument));
EXPECT_EQ(method_call.method_name(), method_name);
ASSERT_NE(method_call.arguments(), nullptr);
EXPECT_EQ(*method_call.arguments(), 42);
}
} // namespace flutter

View File

@@ -0,0 +1,125 @@
// Copyright 2013 The Flutter 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 "include/flutter/plugin_registrar.h"
#include "include/flutter/engine_method_result.h"
#include "include/flutter/method_channel.h"
#include <iostream>
#include <map>
namespace flutter {
namespace {
// Passes |message| to |user_data|, which must be a BinaryMessageHandler, along
// with a BinaryReply that will send a response on |message|'s response handle.
//
// This serves as an adaptor between the function-pointer-based message callback
// interface provided by the C API and the std::function-based message handler
// interface of BinaryMessenger.
void ForwardToHandler(FlutterDesktopMessengerRef messenger,
const FlutterDesktopMessage* message,
void* user_data) {
auto* response_handle = message->response_handle;
BinaryReply reply_handler = [messenger, response_handle](
const uint8_t* reply,
const size_t reply_size) mutable {
if (!response_handle) {
std::cerr << "Error: Response can be set only once. Ignoring "
"duplicate response."
<< std::endl;
return;
}
FlutterDesktopMessengerSendResponse(messenger, response_handle, reply,
reply_size);
// The engine frees the response handle once
// FlutterDesktopSendMessageResponse is called.
response_handle = nullptr;
};
const BinaryMessageHandler& message_handler =
*static_cast<BinaryMessageHandler*>(user_data);
message_handler(message->message, message->message_size,
std::move(reply_handler));
}
} // namespace
// Wrapper around a FlutterDesktopMessengerRef that implements the
// BinaryMessenger API.
class BinaryMessengerImpl : public BinaryMessenger {
public:
explicit BinaryMessengerImpl(FlutterDesktopMessengerRef core_messenger)
: messenger_(core_messenger) {}
virtual ~BinaryMessengerImpl() = default;
// Prevent copying.
BinaryMessengerImpl(BinaryMessengerImpl const&) = delete;
BinaryMessengerImpl& operator=(BinaryMessengerImpl const&) = delete;
// |flutter::BinaryMessenger|
void Send(const std::string& channel,
const uint8_t* message,
const size_t message_size) const override;
// |flutter::BinaryMessenger|
void SetMessageHandler(const std::string& channel,
BinaryMessageHandler handler) override;
private:
// Handle for interacting with the C API.
FlutterDesktopMessengerRef messenger_;
// A map from channel names to the BinaryMessageHandler that should be called
// for incoming messages on that channel.
std::map<std::string, BinaryMessageHandler> handlers_;
};
void BinaryMessengerImpl::Send(const std::string& channel,
const uint8_t* message,
const size_t message_size) const {
FlutterDesktopMessengerSend(messenger_, channel.c_str(), message,
message_size);
}
void BinaryMessengerImpl::SetMessageHandler(const std::string& channel,
BinaryMessageHandler handler) {
if (!handler) {
handlers_.erase(channel);
FlutterDesktopMessengerSetCallback(messenger_, channel.c_str(), nullptr,
nullptr);
return;
}
// Save the handler, to keep it alive.
handlers_[channel] = std::move(handler);
BinaryMessageHandler* message_handler = &handlers_[channel];
// Set an adaptor callback that will invoke the handler.
FlutterDesktopMessengerSetCallback(messenger_, channel.c_str(),
ForwardToHandler, message_handler);
}
// PluginRegistrar:
PluginRegistrar::PluginRegistrar(FlutterDesktopPluginRegistrarRef registrar)
: registrar_(registrar) {
auto core_messenger = FlutterDesktopRegistrarGetMessenger(registrar_);
messenger_ = std::make_unique<BinaryMessengerImpl>(core_messenger);
}
PluginRegistrar::~PluginRegistrar() {}
void PluginRegistrar::AddPlugin(std::unique_ptr<Plugin> plugin) {
plugins_.insert(std::move(plugin));
}
void PluginRegistrar::EnableInputBlockingForChannel(
const std::string& channel) {
FlutterDesktopRegistrarEnableInputBlocking(registrar_, channel.c_str());
}
} // namespace flutter

View File

@@ -0,0 +1,50 @@
// Copyright 2013 The Flutter 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/shell/platform/common/cpp/client_wrapper/include/flutter/plugin_registrar.h"
#include <memory>
#include <vector>
#include "flutter/shell/platform/common/cpp/client_wrapper/testing/stub_flutter_api.h"
#include "gtest/gtest.h"
namespace flutter {
namespace {
// Stub implementation to validate calls to the API.
class TestApi : public testing::StubFlutterApi {
public:
// |flutter::testing::StubFlutterApi|
void MessengerSend(const char* channel,
const uint8_t* message,
const size_t message_size) override {
last_data_sent_ = message;
}
const uint8_t* last_data_sent() { return last_data_sent_; }
private:
const uint8_t* last_data_sent_ = nullptr;
};
} // namespace
// Tests that the registrar returns a messenger that calls through to the C API.
TEST(MethodCallTest, MessengerSend) {
testing::ScopedStubFlutterApi scoped_api_stub(std::make_unique<TestApi>());
auto test_api = static_cast<TestApi*>(scoped_api_stub.stub());
auto dummy_registrar_handle =
reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1);
PluginRegistrar registrar(dummy_registrar_handle);
BinaryMessenger* messenger = registrar.messenger();
std::vector<uint8_t> message = {1, 2, 3, 4};
messenger->Send("some_channel", &message[0], message.size());
EXPECT_EQ(test_api->last_data_sent(), &message[0]);
}
} // namespace flutter

View File

@@ -0,0 +1,42 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Publishes client wrapper files to the output directory for distribution.
# This can be used multiple times to combine various portions of a wrapper
# library into one cohesive library for clients to consume.
#
# Files that should be built by clients go into 'sources', while headers meant
# to be included by the consuming code go into 'public'.
#
# All public code is assumed to be in the 'flutter' namespace.
template("publish_client_wrapper") {
template_target_name = target_name
publish_dir_root = "$root_out_dir/cpp_client_wrapper"
namespace = "flutter"
group(template_target_name) {
deps = [
":${template_target_name}_publish_includes",
":${template_target_name}_publish_sources",
]
}
copy("${template_target_name}_publish_includes") {
visibility = [ ":$template_target_name" ]
sources = invoker.public
outputs = [
"$publish_dir_root/include/$namespace/{{source_file_part}}",
]
}
copy("${template_target_name}_publish_sources") {
visibility = [ ":$template_target_name" ]
sources = invoker.sources
outputs = [
"$publish_dir_root/{{source_file_part}}",
]
}
}

View File

@@ -0,0 +1,81 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Copyright 2013 The Flutter 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/shell/platform/common/cpp/client_wrapper/testing/stub_flutter_api.h"
static flutter::testing::StubFlutterApi* s_stub_implementation;
namespace flutter {
namespace testing {
// static
void StubFlutterApi::SetTestStub(StubFlutterApi* stub) {
s_stub_implementation = stub;
}
// static
StubFlutterApi* StubFlutterApi::GetTestStub() {
return s_stub_implementation;
}
ScopedStubFlutterApi::ScopedStubFlutterApi(std::unique_ptr<StubFlutterApi> stub)
: stub_(std::move(stub)) {
previous_stub_ = StubFlutterApi::GetTestStub();
StubFlutterApi::SetTestStub(stub_.get());
}
ScopedStubFlutterApi::~ScopedStubFlutterApi() {
StubFlutterApi::SetTestStub(previous_stub_);
}
} // namespace testing
} // namespace flutter
// Forwarding dummy implementations of the C API.
FlutterDesktopMessengerRef FlutterDesktopRegistrarGetMessenger(
FlutterDesktopPluginRegistrarRef registrar) {
// The stub ignores this, so just return an arbitrary non-zero value.
return reinterpret_cast<FlutterDesktopMessengerRef>(1);
}
void FlutterDesktopRegistrarEnableInputBlocking(
FlutterDesktopPluginRegistrarRef registrar,
const char* channel) {
if (s_stub_implementation) {
s_stub_implementation->RegistrarEnableInputBlocking(channel);
}
}
void FlutterDesktopMessengerSend(FlutterDesktopMessengerRef messenger,
const char* channel,
const uint8_t* message,
const size_t message_size) {
if (s_stub_implementation) {
s_stub_implementation->MessengerSend(channel, message, message_size);
}
}
void FlutterDesktopMessengerSendResponse(
FlutterDesktopMessengerRef messenger,
const FlutterDesktopMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length) {
if (s_stub_implementation) {
s_stub_implementation->MessengerSendResponse(handle, data, data_length);
}
}
void FlutterDesktopMessengerSetCallback(FlutterDesktopMessengerRef messenger,
const char* channel,
FlutterDesktopMessageCallback callback,
void* user_data) {
if (s_stub_implementation) {
s_stub_implementation->MessengerSetCallback(channel, callback, user_data);
}
}

View File

@@ -0,0 +1,74 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_
#include <memory>
#include "flutter/shell/platform/common/cpp/public/flutter_messenger.h"
#include "flutter/shell/platform/common/cpp/public/flutter_plugin_registrar.h"
namespace flutter {
namespace testing {
// Base class for a object that provides test implementations of the APIs in
// the headers in platform/common/cpp/public/.
// Linking this class into a test binary will provide dummy forwarding
// implementantions of that C API, so that the wrapper can be tested separately
// from the actual library.
class StubFlutterApi {
public:
// Sets |stub| as the instance to which calls to the Flutter library C APIs
// will be forwarded.
static void SetTestStub(StubFlutterApi* stub);
// Returns the current stub, as last set by SetTestFluttterStub.
static StubFlutterApi* GetTestStub();
virtual ~StubFlutterApi() {}
// Called for FlutterDesktopRegistrarEnableInputBlocking.
virtual void RegistrarEnableInputBlocking(const char* channel) {}
// Called for FlutterDesktopMessengerSend.
virtual void MessengerSend(const char* channel,
const uint8_t* message,
const size_t message_size) {}
// Called for FlutterDesktopMessengerSendResponse.
virtual void MessengerSendResponse(
const FlutterDesktopMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length) {}
// Called for FlutterDesktopMessengerSetCallback.
virtual void MessengerSetCallback(const char* channel,
FlutterDesktopMessageCallback callback,
void* user_data) {}
};
// A test helper that owns a stub implementation, making it the test stub for
// the lifetime of the object, then restoring the previous value.
class ScopedStubFlutterApi {
public:
// Calls SetTestFlutterStub with |stub|.
ScopedStubFlutterApi(std::unique_ptr<StubFlutterApi> stub);
// Restores the previous test stub.
~ScopedStubFlutterApi();
StubFlutterApi* stub() { return stub_.get(); }
private:
std::unique_ptr<StubFlutterApi> stub_;
// The previous stub.
StubFlutterApi* previous_stub_;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_API_H_

View File

@@ -0,0 +1,57 @@
// Copyright 2013 The Flutter 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/shell/platform/common/cpp/incoming_message_dispatcher.h"
namespace shell {
IncomingMessageDispatcher::IncomingMessageDispatcher(
FlutterDesktopMessengerRef messenger)
: messenger_(messenger) {}
IncomingMessageDispatcher::~IncomingMessageDispatcher() = default;
void IncomingMessageDispatcher::HandleMessage(
const FlutterDesktopMessage& message,
std::function<void(void)> input_block_cb,
std::function<void(void)> input_unblock_cb) {
std::string channel(message.channel);
// Find the handler for the channel; if there isn't one, report the failure.
if (callbacks_.find(channel) == callbacks_.end()) {
FlutterDesktopMessengerSendResponse(messenger_, message.response_handle,
nullptr, 0);
return;
}
auto& callback_info = callbacks_[channel];
FlutterDesktopMessageCallback message_callback = callback_info.first;
// Process the call, handling input blocking if requested.
bool block_input = input_blocking_channels_.count(channel) > 0;
if (block_input) {
input_block_cb();
}
message_callback(messenger_, &message, callback_info.second);
if (block_input) {
input_unblock_cb();
}
}
void IncomingMessageDispatcher::SetMessageCallback(
const std::string& channel,
FlutterDesktopMessageCallback callback,
void* user_data) {
if (!callback) {
callbacks_.erase(channel);
return;
}
callbacks_[channel] = std::make_pair(callback, user_data);
}
void IncomingMessageDispatcher::EnableInputBlockingForChannel(
const std::string& channel) {
input_blocking_channels_.insert(channel);
}
} // namespace shell

View File

@@ -0,0 +1,78 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_CPP_INCOMING_MESSAGE_DISPATCHER_H_
#define FLUTTER_SHELL_PLATFORM_CPP_INCOMING_MESSAGE_DISPATCHER_H_
#include <functional>
#include <map>
#include <set>
#include <string>
#include <utility>
#include "flutter/shell/platform/common/cpp/public/flutter_messenger.h"
namespace shell {
// Manages per-channel registration of callbacks for handling messages from the
// Flutter engine, and dispatching incoming messages to those handlers.
class IncomingMessageDispatcher {
public:
// Creates a new IncomingMessageDispatcher. |messenger| must remain valid as
// long as this object exists.
explicit IncomingMessageDispatcher(FlutterDesktopMessengerRef messenger);
virtual ~IncomingMessageDispatcher();
// Prevent copying.
IncomingMessageDispatcher(IncomingMessageDispatcher const&) = delete;
IncomingMessageDispatcher& operator=(IncomingMessageDispatcher const&) =
delete;
// Routes |message| to to the registered handler for its channel, if any.
//
// If input blocking has been enabled on that channel, wraps the call to the
// handler with calls to the given callbacks to block and then unblock input.
//
// If no handler is registered for the message's channel, sends a
// NotImplemented response to the engine.
void HandleMessage(
const FlutterDesktopMessage& message,
std::function<void(void)> input_block_cb = [] {},
std::function<void(void)> input_unblock_cb = [] {});
// Registers a message callback for incoming messages from the Flutter
// side on the specified channel. |callback| will be called with the message
// and |user_data| any time a message arrives on that channel.
//
// Replaces any existing callback. Pass a null callback to unregister the
// existing callback.
void SetMessageCallback(const std::string& channel,
FlutterDesktopMessageCallback callback,
void* user_data);
// Enables input blocking on the given channel name.
//
// If set, then the parent window should disable input callbacks
// while waiting for the handler for messages on that channel to run.
void EnableInputBlockingForChannel(const std::string& channel);
private:
// Handle for interacting with the C messaging API.
FlutterDesktopMessengerRef messenger_;
// A map from channel names to the FlutterDesktopMessageCallback that should
// be called for incoming messages on that channel, along with the void* user
// data to pass to it.
std::map<std::string, std::pair<FlutterDesktopMessageCallback, void*>>
callbacks_;
// Channel names for which input blocking should be enabled during the call to
// that channel's handler.
std::set<std::string> input_blocking_channels_;
};
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_CPP_INCOMING_MESSAGE_DISPATCHER_H_

View File

@@ -0,0 +1,28 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_EXPORT_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_EXPORT_H_
#ifdef FLUTTER_DESKTOP_LIBRARY
// Add visibility/export annotations when building the library.
#ifdef _WIN32
#define FLUTTER_EXPORT __declspec(dllexport)
#else
#define FLUTTER_EXPORT __attribute__((visibility("default")))
#endif
#else // FLUTTER_DESKTOP_LIBRARY
// Add import annotations when consuming the library.
#ifdef _WIN32
#define FLUTTER_EXPORT __declspec(dllimport)
#else
#define FLUTTER_EXPORT
#endif
#endif // FLUTTER_DESKTOP_LIBRARY
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_EXPORT_H_

View File

@@ -0,0 +1,81 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_MESSENGER_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_MESSENGER_H_
#include <stddef.h>
#include <stdint.h>
#include "flutter_export.h"
#if defined(__cplusplus)
extern "C" {
#endif
// Opaque reference to a Flutter engine messenger.
typedef struct FlutterDesktopMessenger* FlutterDesktopMessengerRef;
// Opaque handle for tracking responses to messages.
typedef struct _FlutterPlatformMessageResponseHandle
FlutterDesktopMessageResponseHandle;
// A message received from Flutter.
typedef struct {
// Size of this struct as created by Flutter.
size_t struct_size;
// The name of the channel used for this message.
const char* channel;
// The raw message data.
const uint8_t* message;
// The length of |message|.
size_t message_size;
// The response handle. If non-null, the receiver of this message must call
// FlutterDesktopSendMessageResponse exactly once with this handle.
const FlutterDesktopMessageResponseHandle* response_handle;
} FlutterDesktopMessage;
// Function pointer type for message handler callback registration.
//
// The user data will be whatever was passed to FlutterDesktopSetMessageHandler
// for the channel the message is received on.
typedef void (*FlutterDesktopMessageCallback)(
FlutterDesktopMessengerRef /* messenger */,
const FlutterDesktopMessage* /* message*/,
void* /* user data */);
// Sends a binary message to the Flutter side on the specified channel.
FLUTTER_EXPORT void FlutterDesktopMessengerSend(
FlutterDesktopMessengerRef messenger,
const char* channel,
const uint8_t* message,
const size_t message_size);
// Sends a reply to a FlutterDesktopMessage for the given response handle.
//
// Once this has been called, |handle| is invalid and must not be used again.
FLUTTER_EXPORT void FlutterDesktopMessengerSendResponse(
FlutterDesktopMessengerRef messenger,
const FlutterDesktopMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length);
// Registers a callback function for incoming binary messages from the Flutter
// side on the specified channel.
//
// Replaces any existing callback. Provide a null handler to unregister the
// existing callback.
//
// If |user_data| is provided, it will be passed in |callback| calls.
FLUTTER_EXPORT void FlutterDesktopMessengerSetCallback(
FlutterDesktopMessengerRef messenger,
const char* channel,
FlutterDesktopMessageCallback callback,
void* user_data);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_MESSENGER_H_

View File

@@ -0,0 +1,42 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_
#define FLUTTER_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_
#include <stddef.h>
#include <stdint.h>
#include "flutter_export.h"
#include "flutter_messenger.h"
#if defined(__cplusplus)
extern "C" {
#endif
// Opaque reference to a plugin registrar.
typedef struct FlutterDesktopPluginRegistrar* FlutterDesktopPluginRegistrarRef;
// Returns the engine messenger associated with this registrar.
FLUTTER_EXPORT FlutterDesktopMessengerRef
FlutterDesktopRegistrarGetMessenger(FlutterDesktopPluginRegistrarRef registrar);
// Enables input blocking on the given channel.
//
// If set, then the Flutter window will disable input callbacks
// while waiting for the handler for messages on that channel to run. This is
// useful if handling the message involves showing a modal window, for instance.
//
// This must be called after FlutterDesktopSetMessageHandler, as setting a
// handler on a channel will reset the input blocking state back to the
// default of disabled.
FLUTTER_EXPORT void FlutterDesktopRegistrarEnableInputBlocking(
FlutterDesktopPluginRegistrarRef registrar,
const char* channel);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_SHELL_PLATFORM_COMMON_CPP_PUBLIC_FLUTTER_PLUGIN_REGISTRAR_H_

View File

@@ -0,0 +1,181 @@
// Copyright 2013 The Flutter 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/shell/platform/common/cpp/text_input_model.h"
#include <iostream>
// TODO(awdavies): Need to fix this regarding issue #47.
static constexpr char kComposingBaseKey[] = "composingBase";
static constexpr char kComposingExtentKey[] = "composingExtent";
static constexpr char kSelectionAffinityKey[] = "selectionAffinity";
static constexpr char kAffinityDownstream[] = "TextAffinity.downstream";
static constexpr char kSelectionBaseKey[] = "selectionBase";
static constexpr char kSelectionExtentKey[] = "selectionExtent";
static constexpr char kSelectionIsDirectionalKey[] = "selectionIsDirectional";
static constexpr char kTextKey[] = "text";
// Input client configuration keys.
static constexpr char kTextInputAction[] = "inputAction";
static constexpr char kTextInputType[] = "inputType";
static constexpr char kTextInputTypeName[] = "name";
namespace shell {
TextInputModel::TextInputModel(int client_id, const rapidjson::Value& config)
: text_(""),
client_id_(client_id),
selection_base_(text_.begin()),
selection_extent_(text_.begin()) {
// TODO: Improve error handling during refactoring; this is just minimal
// checking to avoid asserts since RapidJSON is stricter than jsoncpp.
if (config.IsObject()) {
auto input_action = config.FindMember(kTextInputAction);
if (input_action != config.MemberEnd() && input_action->value.IsString()) {
input_action_ = input_action->value.GetString();
}
auto input_type_info = config.FindMember(kTextInputType);
if (input_type_info != config.MemberEnd() &&
input_type_info->value.IsObject()) {
auto input_type = input_type_info->value.FindMember(kTextInputTypeName);
if (input_type != input_type_info->value.MemberEnd() &&
input_type->value.IsString()) {
input_type_ = input_type->value.GetString();
}
}
}
}
TextInputModel::~TextInputModel() = default;
bool TextInputModel::SetEditingState(size_t selection_base,
size_t selection_extent,
const std::string& text) {
if (selection_base > selection_extent) {
return false;
}
// Only checks extent since it is implicitly greater-than-or-equal-to base.
if (selection_extent > text.size()) {
return false;
}
text_ = std::string(text);
selection_base_ = text_.begin() + selection_base;
selection_extent_ = text_.begin() + selection_extent;
return true;
}
void TextInputModel::DeleteSelected() {
selection_base_ = text_.erase(selection_base_, selection_extent_);
// Moves extent back to base, so that it is a single cursor placement again.
selection_extent_ = selection_base_;
}
void TextInputModel::AddCharacter(char c) {
if (selection_base_ != selection_extent_) {
DeleteSelected();
}
selection_extent_ = text_.insert(selection_extent_, c);
selection_extent_++;
selection_base_ = selection_extent_;
}
bool TextInputModel::Backspace() {
if (selection_base_ != selection_extent_) {
DeleteSelected();
return true;
}
if (selection_base_ != text_.begin()) {
selection_base_ = text_.erase(selection_base_ - 1, selection_base_);
selection_extent_ = selection_base_;
return true;
}
return false; // No edits happened.
}
bool TextInputModel::Delete() {
if (selection_base_ != selection_extent_) {
DeleteSelected();
return true;
}
if (selection_base_ != text_.end()) {
selection_base_ = text_.erase(selection_base_, selection_base_ + 1);
selection_extent_ = selection_base_;
return true;
}
return false;
}
void TextInputModel::MoveCursorToBeginning() {
selection_base_ = text_.begin();
selection_extent_ = text_.begin();
}
void TextInputModel::MoveCursorToEnd() {
selection_base_ = text_.end();
selection_extent_ = text_.end();
}
bool TextInputModel::MoveCursorForward() {
// If about to move set to the end of the highlight (when not selecting).
if (selection_base_ != selection_extent_) {
selection_base_ = selection_extent_;
return true;
}
// If not at the end, move the extent forward.
if (selection_extent_ != text_.end()) {
selection_extent_++;
selection_base_++;
return true;
}
return false;
}
bool TextInputModel::MoveCursorBack() {
// If about to move set to the beginning of the highlight
// (when not selecting).
if (selection_base_ != selection_extent_) {
selection_extent_ = selection_base_;
return true;
}
// If not at the start, move the beginning backward.
if (selection_base_ != text_.begin()) {
selection_base_--;
selection_extent_--;
return true;
}
return false;
}
std::unique_ptr<rapidjson::Document> TextInputModel::GetState() const {
// TODO(stuartmorgan): Move client_id out up to the plugin so that this
// function just returns the editing state.
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(client_id_, allocator);
rapidjson::Value editing_state(rapidjson::kObjectType);
// TODO(awdavies): Most of these are hard-coded for now.
editing_state.AddMember(kComposingBaseKey, -1, allocator);
editing_state.AddMember(kComposingExtentKey, -1, allocator);
editing_state.AddMember(kSelectionAffinityKey, kAffinityDownstream,
allocator);
editing_state.AddMember(kSelectionBaseKey,
static_cast<int>(selection_base_ - text_.begin()),
allocator);
editing_state.AddMember(kSelectionExtentKey,
static_cast<int>(selection_extent_ - text_.begin()),
allocator);
editing_state.AddMember(kSelectionIsDirectionalKey, false, allocator);
editing_state.AddMember(kTextKey, rapidjson::Value(text_, allocator).Move(),
allocator);
args->PushBack(editing_state, allocator);
return args;
}
} // namespace shell

View File

@@ -0,0 +1,101 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_CPP_TEXT_INPUT_MODEL_H_
#define FLUTTER_SHELL_PLATFORM_CPP_TEXT_INPUT_MODEL_H_
#include <string>
#include "rapidjson/document.h"
namespace shell {
// Handles underlying text input state, using a simple ASCII model.
//
// Ignores special states like "insert mode" for now.
class TextInputModel {
public:
TextInputModel(int client_id, const rapidjson::Value& config);
virtual ~TextInputModel();
// Attempts to set the text state.
//
// Returns false if the state is not valid (base or extent are out of
// bounds, or base is less than extent).
bool SetEditingState(size_t selection_base,
size_t selection_extent,
const std::string& text);
// Adds a character.
//
// Either appends after the cursor (when selection base and extent are the
// same), or deletes the selected characters, replacing the text with the
// character specified.
void AddCharacter(char c);
// Deletes either the selection, or one character ahead of the cursor.
//
// Deleting one character ahead of the cursor occurs when the selection base
// and extent are the same.
//
// Returns true if any deletion actually occurred.
bool Delete();
// Deletes either the selection, or one character behind the cursor.
//
// Deleting one character behind the cursor occurs when the selection base
// and extent are the same.
//
// Returns true if any deletion actually occurred.
bool Backspace();
// Attempts to move the cursor backward.
//
// Returns true if the cursor could be moved. Changes base and extent to be
// equal to either the extent (if extent is at the end of the string), or
// for extent to be equal to
bool MoveCursorBack();
// Attempts to move the cursor forward.
//
// Returns true if the cursor could be moved.
bool MoveCursorForward();
// Attempts to move the cursor to the beginning.
//
// Returns true if the cursor could be moved.
void MoveCursorToBeginning();
// Attempts to move the cursor to the back.
//
// Returns true if the cursor could be moved.
void MoveCursorToEnd();
// Returns the state in the form of a platform message.
std::unique_ptr<rapidjson::Document> GetState() const;
// Id of the text input client.
int client_id() const { return client_id_; }
// Keyboard type of the client. See available options:
// https://docs.flutter.io/flutter/services/TextInputType-class.html
std::string input_type() const { return input_type_; }
// An action requested by the user on the input client. See available options:
// https://docs.flutter.io/flutter/services/TextInputAction-class.html
std::string input_action() const { return input_action_; }
private:
void DeleteSelected();
std::string text_;
int client_id_;
std::string input_type_;
std::string input_action_;
std::string::iterator selection_base_;
std::string::iterator selection_extent_;
};
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_CPP_TEXT_INPUT_MODEL_H_

View File

@@ -0,0 +1,80 @@
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
_public_headers = [ "public/flutter_glfw.h" ]
# Any files that are built by clients (client_wrapper code, library headers for
# implementations using this shared code, etc.) include the public headers
# assuming they are in the include path. This configuration should be added to
# any such code that is also built by GN to make the includes work.
config("relative_flutter_glfw_headers") {
include_dirs = [ "public" ]
}
# The headers are a separate source set since the client wrapper is allowed
# to depend on the public headers, but none of the rest of the code.
source_set("flutter_glfw_headers") {
public = _public_headers
public_deps = [
"$flutter_root/shell/platform/common/cpp:common_cpp_library_headers",
]
configs += [
"$flutter_root/shell/platform/common/cpp:desktop_library_implementation",
]
public_configs = [
"$flutter_root/shell/platform/common/cpp:relative_flutter_library_headers",
]
}
source_set("flutter_glfw") {
sources = [
"flutter_glfw.cc",
"key_event_handler.cc",
"key_event_handler.h",
"keyboard_hook_handler.h",
"text_input_plugin.cc",
"text_input_plugin.h",
]
defines = [ "USE_RAPID_JSON" ]
configs += [
"$flutter_root/shell/platform/common/cpp:desktop_library_implementation",
]
deps = [
":flutter_glfw_headers",
"$flutter_root/shell/platform/common/cpp:common_cpp",
"$flutter_root/shell/platform/common/cpp/client_wrapper:client_wrapper",
"$flutter_root/shell/platform/embedder:embedder",
"$flutter_root/shell/platform/glfw/client_wrapper:client_wrapper_glfw",
"//third_party/rapidjson",
]
if (is_linux) {
libs = [ "GL" ]
configs += [
"$flutter_root/shell/platform/linux/config:epoxy",
"$flutter_root/shell/platform/linux/config:glfw3",
"$flutter_root/shell/platform/linux/config:gtk3",
"$flutter_root/shell/platform/linux/config:x11",
]
}
}
copy("publish_headers_glfw") {
sources = _public_headers
outputs = [
"$root_out_dir/{{source_file_part}}",
]
# The GLFW header assumes the presence of the common headers.
deps = [
"$flutter_root/shell/platform/common/cpp:publish_headers",
]
}

View File

@@ -0,0 +1,78 @@
# Copyright 2013 The Flutter 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("$flutter_root/shell/platform/common/cpp/client_wrapper/publish.gni")
_wrapper_includes = [ "include/flutter/flutter_window_controller.h" ]
_wrapper_sources = [ "flutter_window_controller.cc" ]
# This code will be merged into .../common/cpp/client_wrapper for client use,
# so uses header paths that assume the merged state. Include the header
# header directory of the core wrapper files so these includes will work.
config("relative_core_wrapper_headers") {
include_dirs = [
"$flutter_root/shell/platform/common/cpp/client_wrapper/include/flutter",
]
}
# GLFW client wrapper build for internal use by the shell implementation.
source_set("client_wrapper_glfw") {
sources = _wrapper_sources
public = _wrapper_includes
deps = [
"$flutter_root/shell/platform/common/cpp:common_cpp_library_headers",
"$flutter_root/shell/platform/common/cpp/client_wrapper:client_wrapper",
"$flutter_root/shell/platform/glfw:flutter_glfw_headers",
]
configs += [
"$flutter_root/shell/platform/common/cpp:desktop_library_implementation",
]
public_configs = [
":relative_core_wrapper_headers",
"$flutter_root/shell/platform/common/cpp:relative_flutter_library_headers",
"$flutter_root/shell/platform/glfw:relative_flutter_glfw_headers",
]
}
# Copies the GLFW client wrapper code to the output directory, merging it into
# the core wrapper.
publish_client_wrapper("publish_wrapper_glfw") {
public = _wrapper_includes
sources = _wrapper_sources
}
source_set("client_wrapper_library_stubs_glfw") {
sources = [
"testing/stub_flutter_glfw_api.cc",
"testing/stub_flutter_glfw_api.h",
]
public_deps = [
"$flutter_root/shell/platform/glfw:flutter_glfw_headers",
]
}
executable("client_wrapper_glfw_unittests") {
testonly = true
# TODO: Add more unit tests.
sources = [
"flutter_window_controller_unittests.cc",
]
deps = [
":client_wrapper_glfw",
":client_wrapper_library_stubs_glfw",
"$flutter_root/shell/platform/common/cpp/client_wrapper:client_wrapper_library_stubs",
"$flutter_root/testing",
# TODO: Consider refactoring flutter_root/testing so that there's a testing
# target that doesn't require a Dart runtime to be linked in.
"//third_party/dart/runtime:libdart_jit",
]
}

View File

@@ -0,0 +1,77 @@
// Copyright 2013 The Flutter 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 "include/flutter/flutter_window_controller.h"
#include <algorithm>
#include <iostream>
namespace flutter {
FlutterWindowController::FlutterWindowController(
const std::string& icu_data_path)
: icu_data_path_(icu_data_path) {
init_succeeded_ = FlutterDesktopInit();
}
FlutterWindowController::~FlutterWindowController() {
if (init_succeeded_) {
FlutterDesktopTerminate();
}
}
bool FlutterWindowController::CreateWindow(
int width,
int height,
const std::string& assets_path,
const std::vector<std::string>& arguments) {
if (!init_succeeded_) {
std::cerr << "Could not create window; FlutterDesktopInit failed."
<< std::endl;
return false;
}
if (window_) {
std::cerr << "Only one Flutter window can exist at a time." << std::endl;
return false;
}
std::vector<const char*> engine_arguments;
std::transform(
arguments.begin(), arguments.end(), std::back_inserter(engine_arguments),
[](const std::string& arg) -> const char* { return arg.c_str(); });
size_t arg_count = engine_arguments.size();
window_ = FlutterDesktopCreateWindow(
width, height, assets_path.c_str(), icu_data_path_.c_str(),
arg_count > 0 ? &engine_arguments[0] : nullptr, arg_count);
if (!window_) {
std::cerr << "Failed to create window." << std::endl;
return false;
}
return true;
}
FlutterDesktopPluginRegistrarRef FlutterWindowController::GetRegistrarForPlugin(
const std::string& plugin_name) {
if (!window_) {
std::cerr << "Cannot get plugin registrar without a window; call "
"CreateWindow first."
<< std::endl;
return nullptr;
}
return FlutterDesktopGetPluginRegistrar(window_, plugin_name.c_str());
}
void FlutterWindowController::SetHoverEnabled(bool enabled) {
FlutterDesktopSetHoverEnabled(window_, enabled);
}
void FlutterWindowController::RunEventLoop() {
if (window_) {
FlutterDesktopRunWindowLoop(window_);
}
}
} // namespace flutter

View File

@@ -0,0 +1,54 @@
// Copyright 2013 The Flutter 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/shell/platform/glfw/client_wrapper/include/flutter/flutter_window_controller.h"
#include <memory>
#include <string>
#include "flutter/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h"
#include "gtest/gtest.h"
namespace flutter {
namespace {
// Stub implementation to validate calls to the API.
class TestGlfwApi : public testing::StubFlutterGlfwApi {
public:
// |flutter::testing::StubFlutterGlfwApi|
bool Init() override {
init_called_ = true;
return true;
}
// |flutter::testing::StubFlutterGlfwApi|
void Terminate() override { terminate_called_ = true; }
bool init_called() { return init_called_; }
bool terminate_called() { return terminate_called_; }
private:
bool init_called_ = false;
bool terminate_called_ = false;
};
} // namespace
TEST(FlutterViewControllerTest, CreateDestroy) {
const std::string icu_data_path = "fake/path/to/icu";
testing::ScopedStubFlutterGlfwApi scoped_api_stub(
std::make_unique<TestGlfwApi>());
auto test_api = static_cast<TestGlfwApi*>(scoped_api_stub.stub());
{
FlutterWindowController controller(icu_data_path);
EXPECT_EQ(test_api->init_called(), true);
EXPECT_EQ(test_api->terminate_called(), false);
}
EXPECT_EQ(test_api->init_called(), true);
EXPECT_EQ(test_api->terminate_called(), true);
}
} // namespace flutter

View File

@@ -0,0 +1,83 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_
#include <string>
#include <vector>
#include <flutter_glfw.h>
#include "plugin_registrar.h"
namespace flutter {
// A controller for a window displaying Flutter content.
//
// This is the primary wrapper class for the desktop C API.
// If you use this class, you should not call any of the setup or teardown
// methods in the C API directly, as this class will do that internally.
//
// Note: This is an early implementation (using GLFW internally) which
// requires control of the application's event loop, and is thus useful
// primarily for building a simple one-window shell hosting a Flutter
// application. The final implementation and API will be very different.
class FlutterWindowController {
public:
// There must be only one instance of this class in an application at any
// given time, as Flutter does not support multiple engines in one process,
// or multiple views in one engine.
explicit FlutterWindowController(const std::string& icu_data_path);
~FlutterWindowController();
// Creates and displays a window for displaying Flutter content.
//
// The |assets_path| is the path to the flutter_assets folder for the Flutter
// application to be run. |icu_data_path| is the path to the icudtl.dat file
// for the version of Flutter you are using.
//
// The |arguments| are passed to the Flutter engine. See:
// https://github.com/flutter/engine/blob/master/shell/common/switches.h for
// for details. Not all arguments will apply to desktop.
//
// Only one Flutter window can exist at a time; see constructor comment.
bool CreateWindow(int width,
int height,
const std::string& assets_path,
const std::vector<std::string>& arguments);
// Returns the FlutterDesktopPluginRegistrarRef to register a plugin with the
// given name.
//
// The name must be unique across the application.
FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin(
const std::string& plugin_name);
// Enables or disables hover tracking.
//
// If hover is enabled, mouse movement will send hover events to the Flutter
// engine, rather than only tracking the mouse while the button is pressed.
// Defaults to off.
void SetHoverEnabled(bool enabled);
// Loops on Flutter window events until the window closes.
void RunEventLoop();
private:
// The path to the ICU data file. Set at creation time since it is the same
// for any window created.
std::string icu_data_path_;
// Whether or not FlutterDesktopInit succeeded at creation time.
bool init_succeeded_ = false;
// The curent Flutter window, if any.
FlutterDesktopWindowRef window_ = nullptr;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_WINDOW_CONTROLLER_H_

View File

@@ -0,0 +1,101 @@
// Copyright 2013 The Flutter 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/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h"
static flutter::testing::StubFlutterGlfwApi* s_stub_implementation;
namespace flutter {
namespace testing {
// static
void StubFlutterGlfwApi::SetTestStub(StubFlutterGlfwApi* stub) {
s_stub_implementation = stub;
}
// static
StubFlutterGlfwApi* StubFlutterGlfwApi::GetTestStub() {
return s_stub_implementation;
}
ScopedStubFlutterGlfwApi::ScopedStubFlutterGlfwApi(
std::unique_ptr<StubFlutterGlfwApi> stub)
: stub_(std::move(stub)) {
previous_stub_ = StubFlutterGlfwApi::GetTestStub();
StubFlutterGlfwApi::SetTestStub(stub_.get());
}
ScopedStubFlutterGlfwApi::~ScopedStubFlutterGlfwApi() {
StubFlutterGlfwApi::SetTestStub(previous_stub_);
}
} // namespace testing
} // namespace flutter
// Forwarding dummy implementations of the C API.
bool FlutterDesktopInit() {
if (s_stub_implementation) {
s_stub_implementation->Init();
}
return true;
}
void FlutterDesktopTerminate() {
if (s_stub_implementation) {
s_stub_implementation->Terminate();
}
}
FlutterDesktopWindowRef FlutterDesktopCreateWindow(int initial_width,
int initial_height,
const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count) {
if (s_stub_implementation) {
return s_stub_implementation->CreateWindow(initial_width, initial_height,
assets_path, icu_data_path,
arguments, argument_count);
}
return nullptr;
}
void FlutterDesktopSetHoverEnabled(FlutterDesktopWindowRef flutter_window,
bool enabled) {
if (s_stub_implementation) {
s_stub_implementation->SetHoverEnabled(enabled);
}
}
void FlutterDesktopRunWindowLoop(FlutterDesktopWindowRef flutter_window) {
if (s_stub_implementation) {
s_stub_implementation->RunWindowLoop();
}
}
FlutterDesktopEngineRef FlutterDesktopRunEngine(const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count) {
if (s_stub_implementation) {
return s_stub_implementation->RunEngine(assets_path, icu_data_path,
arguments, argument_count);
}
return nullptr;
}
bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine_ref) {
if (s_stub_implementation) {
return s_stub_implementation->ShutDownEngine();
}
return true;
}
FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar(
FlutterDesktopWindowRef flutter_window,
const char* plugin_name) {
// The stub ignores this, so just return an arbitrary non-zero value.
return reinterpret_cast<FlutterDesktopPluginRegistrarRef>(1);
}

View File

@@ -0,0 +1,87 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_GLFW_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_
#include <memory>
#include "flutter/shell/platform/glfw/public/flutter_glfw.h"
namespace flutter {
namespace testing {
// Base class for a object that provides test implementations of the APIs in
// the headers in platform/glfw/public/.
// Linking this class into a test binary will provide dummy forwarding
// implementantions of that C API, so that the wrapper can be tested separately
// from the actual library.
class StubFlutterGlfwApi {
public:
// Sets |stub| as the instance to which calls to the Flutter library C APIs
// will be forwarded.
static void SetTestStub(StubFlutterGlfwApi* stub);
// Returns the current stub, as last set by SetTestFluttterStub.
static StubFlutterGlfwApi* GetTestStub();
virtual ~StubFlutterGlfwApi() {}
// Called for FlutterDesktopInit.
virtual bool Init() { return true; }
// Called for FlutterDesktopTerminate.
virtual void Terminate() {}
// Called for FlutterDesktopCreateWindow.
virtual FlutterDesktopWindowRef CreateWindow(int initial_width,
int initial_height,
const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count) {
return nullptr;
}
// Called for FlutterDesktopSetHoverEnabled
virtual void SetHoverEnabled(bool enabled) {}
// Called for FlutterDesktopRunWindowLoop.
virtual void RunWindowLoop() {}
// Called for FlutterDesktopRunEngine.
virtual FlutterDesktopEngineRef RunEngine(const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count) {
return nullptr;
}
// Called for FlutterDesktopShutDownEngine.
virtual bool ShutDownEngine() { return true; }
};
// A test helper that owns a stub implementation, making it the test stub for
// the lifetime of the object, then restoring the previous value.
class ScopedStubFlutterGlfwApi {
public:
// Calls SetTestFlutterStub with |stub|.
ScopedStubFlutterGlfwApi(std::unique_ptr<StubFlutterGlfwApi> stub);
// Restores the previous test stub.
~ScopedStubFlutterGlfwApi();
StubFlutterGlfwApi* stub() { return stub_.get(); }
private:
std::unique_ptr<StubFlutterGlfwApi> stub_;
// The previous stub.
StubFlutterGlfwApi* previous_stub_;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_

View File

@@ -0,0 +1,595 @@
// Copyright 2013 The Flutter 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/shell/platform/glfw/public/flutter_glfw.h"
#include <assert.h>
#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <iostream>
#ifdef __linux__
// Epoxy must be included before any graphics-related code.
#include <epoxy/gl.h>
#endif
#include <GLFW/glfw3.h>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/plugin_registrar.h"
#include "flutter/shell/platform/common/cpp/incoming_message_dispatcher.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/glfw/key_event_handler.h"
#include "flutter/shell/platform/glfw/keyboard_hook_handler.h"
#include "flutter/shell/platform/glfw/text_input_plugin.h"
#ifdef __linux__
// For plugin-compatible event handling (e.g., modal windows).
#include <X11/Xlib.h>
#include <gtk/gtk.h>
#endif
// GLFW_TRUE & GLFW_FALSE are introduced since libglfw-3.3,
// add definitions here to compile under the old versions.
#ifndef GLFW_TRUE
#define GLFW_TRUE 1
#endif
#ifndef GLFW_FALSE
#define GLFW_FALSE 0
#endif
static_assert(FLUTTER_ENGINE_VERSION == 1, "");
static constexpr double kDpPerInch = 160.0;
// Struct for storing state within an instance of the GLFW Window.
struct FlutterDesktopWindowState {
// The GLFW window that owns this state object.
GLFWwindow* window;
// The handle to the Flutter engine instance.
FlutterEngine engine;
// The plugin registrar handle given to API clients.
std::unique_ptr<FlutterDesktopPluginRegistrar> plugin_registrar;
// Message dispatch manager for messages from the Flutter engine.
std::unique_ptr<shell::IncomingMessageDispatcher> message_dispatcher;
// The plugin registrar managing internal plugins.
std::unique_ptr<flutter::PluginRegistrar> internal_plugin_registrar;
// Handlers for keyboard events from GLFW.
std::vector<std::unique_ptr<shell::KeyboardHookHandler>>
keyboard_hook_handlers;
// Whether or not to track mouse movements to send kHover events.
bool hover_tracking_enabled = false;
// Whether or not the pointer has been added (or if tracking is enabled, has
// been added since it was last removed).
bool pointer_currently_added = false;
// The screen coordinates per inch on the primary monitor. Defaults to a sane
// value based on pixel_ratio 1.0.
double monitor_screen_coordinates_per_inch = kDpPerInch;
// The ratio of pixels per screen coordinate for the window.
double window_pixels_per_screen_coordinate = 1.0;
};
// Struct for storing state of a Flutter engine instance.
struct FlutterDesktopEngineState {
// The handle to the Flutter engine instance.
FlutterEngine engine;
};
// State associated with the plugin registrar.
struct FlutterDesktopPluginRegistrar {
// The plugin messenger handle given to API clients.
std::unique_ptr<FlutterDesktopMessenger> messenger;
};
// State associated with the messenger used to communicate with the engine.
struct FlutterDesktopMessenger {
// The Flutter engine this messenger sends outgoing messages to.
FlutterEngine engine;
// The message dispatcher for handling incoming messages.
shell::IncomingMessageDispatcher* dispatcher;
};
static constexpr char kDefaultWindowTitle[] = "Flutter";
// Retrieves state bag for the window in question from the GLFWWindow.
static FlutterDesktopWindowState* GetSavedWindowState(GLFWwindow* window) {
return reinterpret_cast<FlutterDesktopWindowState*>(
glfwGetWindowUserPointer(window));
}
// Converts a FlutterPlatformMessage to an equivalent FlutterDesktopMessage.
static FlutterDesktopMessage ConvertToDesktopMessage(
const FlutterPlatformMessage& engine_message) {
FlutterDesktopMessage message = {};
message.struct_size = sizeof(message);
message.channel = engine_message.channel;
message.message = engine_message.message;
message.message_size = engine_message.message_size;
message.response_handle = engine_message.response_handle;
return message;
}
// Returns the number of screen coordinates per inch for the main monitor.
// If the information is unavailable, returns a default value that assumes
// that a screen coordinate is one dp.
static double GetScreenCoordinatesPerInch() {
auto* primary_monitor = glfwGetPrimaryMonitor();
auto* primary_monitor_mode = glfwGetVideoMode(primary_monitor);
int primary_monitor_width_mm;
glfwGetMonitorPhysicalSize(primary_monitor, &primary_monitor_width_mm,
nullptr);
if (primary_monitor_width_mm == 0) {
return kDpPerInch;
}
return primary_monitor_mode->width / (primary_monitor_width_mm / 25.4);
}
// When GLFW calls back to the window with a framebuffer size change, notify
// FlutterEngine about the new window metrics.
// The Flutter pixel_ratio is defined as DPI/dp.
static void GLFWFramebufferSizeCallback(GLFWwindow* window,
int width_px,
int height_px) {
int width;
glfwGetWindowSize(window, &width, nullptr);
auto state = GetSavedWindowState(window);
state->window_pixels_per_screen_coordinate = width_px / width;
double dpi = state->window_pixels_per_screen_coordinate *
state->monitor_screen_coordinates_per_inch;
// Limit the ratio to 1 to avoid rendering a smaller UI in standard resolution
// monitors.
double pixel_ratio = std::max(dpi / kDpPerInch, 1.0);
FlutterWindowMetricsEvent event = {};
event.struct_size = sizeof(event);
event.width = width_px;
event.height = height_px;
event.pixel_ratio = pixel_ratio;
FlutterEngineSendWindowMetricsEvent(state->engine, &event);
}
// Sends a pointer event to the Flutter engine with the given phase.
static void SendPointerEventWithPhase(GLFWwindow* window,
FlutterPointerPhase phase,
double x,
double y) {
auto state = GetSavedWindowState(window);
// If sending anything other than an add, and the pointer isn't already added,
// synthesize an add to satisfy Flutter's expectations about events.
if (!state->pointer_currently_added && phase != FlutterPointerPhase::kAdd) {
SendPointerEventWithPhase(window, FlutterPointerPhase::kAdd, x, y);
}
// Don't double-add (e.g., if events are delivered out of order, so an add has
// already been synthesized).
if (state->pointer_currently_added && phase == FlutterPointerPhase::kAdd) {
return;
}
FlutterPointerEvent event = {};
event.struct_size = sizeof(event);
event.phase = phase;
event.x = x * state->window_pixels_per_screen_coordinate;
event.y = y * state->window_pixels_per_screen_coordinate;
event.timestamp =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
FlutterEngineSendPointerEvent(state->engine, &event, 1);
if (phase == FlutterPointerPhase::kAdd) {
state->pointer_currently_added = true;
} else if (phase == FlutterPointerPhase::kRemove) {
state->pointer_currently_added = false;
}
}
// Reports the mouse entering or leaving the Flutter view.
static void GLFWCursorEnterCallback(GLFWwindow* window, int entered) {
double x, y;
glfwGetCursorPos(window, &x, &y);
FlutterPointerPhase phase =
entered ? FlutterPointerPhase::kAdd : FlutterPointerPhase::kRemove;
SendPointerEventWithPhase(window, phase, x, y);
}
// Reports mouse movement to the Flutter engine.
static void GLFWCursorPositionCallback(GLFWwindow* window, double x, double y) {
bool button_down =
glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
FlutterPointerPhase phase =
button_down ? FlutterPointerPhase::kMove : FlutterPointerPhase::kHover;
SendPointerEventWithPhase(window, phase, x, y);
}
// Reports mouse button press to the Flutter engine.
static void GLFWMouseButtonCallback(GLFWwindow* window,
int key,
int action,
int mods) {
// Flutter currently doesn't understand other buttons, so ignore anything
// other than left.
if (key != GLFW_MOUSE_BUTTON_LEFT) {
return;
}
double x, y;
glfwGetCursorPos(window, &x, &y);
FlutterPointerPhase phase = (action == GLFW_PRESS)
? FlutterPointerPhase::kDown
: FlutterPointerPhase::kUp;
SendPointerEventWithPhase(window, phase, x, y);
// If mouse tracking isn't already enabled, turn it on for the duration of
// the drag to generate kMove events.
bool hover_enabled = GetSavedWindowState(window)->hover_tracking_enabled;
if (!hover_enabled) {
glfwSetCursorPosCallback(
window, (action == GLFW_PRESS) ? GLFWCursorPositionCallback : nullptr);
}
// Disable enter/exit events while the mouse button is down; GLFW will send
// an exit event when the mouse button is released, and the pointer should
// stay valid until then.
if (hover_enabled) {
glfwSetCursorEnterCallback(
window, (action == GLFW_PRESS) ? nullptr : GLFWCursorEnterCallback);
}
}
// Passes character input events to registered handlers.
static void GLFWCharCallback(GLFWwindow* window, unsigned int code_point) {
for (const auto& handler :
GetSavedWindowState(window)->keyboard_hook_handlers) {
handler->CharHook(window, code_point);
}
}
// Passes raw key events to registered handlers.
static void GLFWKeyCallback(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
for (const auto& handler :
GetSavedWindowState(window)->keyboard_hook_handlers) {
handler->KeyboardHook(window, key, scancode, action, mods);
}
}
// Enables/disables the callbacks related to mouse tracking.
static void SetHoverCallbacksEnabled(GLFWwindow* window, bool enabled) {
glfwSetCursorEnterCallback(window,
enabled ? GLFWCursorEnterCallback : nullptr);
glfwSetCursorPosCallback(window,
enabled ? GLFWCursorPositionCallback : nullptr);
}
// Flushes event queue and then assigns default window callbacks.
static void GLFWAssignEventCallbacks(GLFWwindow* window) {
glfwPollEvents();
glfwSetKeyCallback(window, GLFWKeyCallback);
glfwSetCharCallback(window, GLFWCharCallback);
glfwSetMouseButtonCallback(window, GLFWMouseButtonCallback);
if (GetSavedWindowState(window)->hover_tracking_enabled) {
SetHoverCallbacksEnabled(window, true);
}
}
// Clears default window events.
static void GLFWClearEventCallbacks(GLFWwindow* window) {
glfwSetKeyCallback(window, nullptr);
glfwSetCharCallback(window, nullptr);
glfwSetMouseButtonCallback(window, nullptr);
SetHoverCallbacksEnabled(window, false);
}
// The Flutter Engine calls out to this function when new platform messages are
// available
static void GLFWOnFlutterPlatformMessage(
const FlutterPlatformMessage* engine_message,
void* user_data) {
if (engine_message->struct_size != sizeof(FlutterPlatformMessage)) {
std::cerr << "Invalid message size received. Expected: "
<< sizeof(FlutterPlatformMessage) << " but received "
<< engine_message->struct_size << std::endl;
return;
}
GLFWwindow* window = reinterpret_cast<GLFWwindow*>(user_data);
auto state = GetSavedWindowState(window);
auto message = ConvertToDesktopMessage(*engine_message);
state->message_dispatcher->HandleMessage(
message, [window] { GLFWClearEventCallbacks(window); },
[window] { GLFWAssignEventCallbacks(window); });
}
static bool GLFWMakeContextCurrent(void* user_data) {
GLFWwindow* window = reinterpret_cast<GLFWwindow*>(user_data);
glfwMakeContextCurrent(window);
return true;
}
static bool GLFWClearContext(void* user_data) {
glfwMakeContextCurrent(nullptr);
return true;
}
static bool GLFWPresent(void* user_data) {
GLFWwindow* window = reinterpret_cast<GLFWwindow*>(user_data);
glfwSwapBuffers(window);
return true;
}
static uint32_t GLFWGetActiveFbo(void* user_data) {
return 0;
}
// Clears the GLFW window to Material Blue-Grey.
//
// This function is primarily to fix an issue when the Flutter Engine is
// spinning up, wherein artifacts of existing windows are rendered onto the
// canvas for a few moments.
//
// This function isn't necessary, but makes starting the window much easier on
// the eyes.
static void GLFWClearCanvas(GLFWwindow* window) {
glfwMakeContextCurrent(window);
// This color is Material Blue Grey.
glClearColor(236.0f / 255.0f, 239.0f / 255.0f, 241.0f / 255.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glFlush();
glfwSwapBuffers(window);
glfwMakeContextCurrent(nullptr);
}
// Resolves the address of the specified OpenGL or OpenGL ES
// core or extension function, if it is supported by the current context.
static void* GLFWProcResolver(void* user_data, const char* name) {
return reinterpret_cast<void*>(glfwGetProcAddress(name));
}
static void GLFWErrorCallback(int error_code, const char* description) {
std::cerr << "GLFW error " << error_code << ": " << description << std::endl;
}
// Spins up an instance of the Flutter Engine.
//
// This function launches the Flutter Engine in a background thread, supplying
// the necessary callbacks for rendering within a GLFWwindow (if one is
// provided).
//
// Returns a caller-owned pointer to the engine.
static FlutterEngine RunFlutterEngine(GLFWwindow* window,
const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t arguments_count) {
// FlutterProjectArgs is expecting a full argv, so when processing it for
// flags the first item is treated as the executable and ignored. Add a dummy
// value so that all provided arguments are used.
std::vector<const char*> argv = {"placeholder"};
if (arguments_count > 0) {
argv.insert(argv.end(), &arguments[0], &arguments[arguments_count]);
}
FlutterRendererConfig config = {};
if (window == nullptr) {
config.type = kOpenGL;
config.open_gl.struct_size = sizeof(config.open_gl);
config.open_gl.make_current = [](void* data) -> bool { return false; };
config.open_gl.clear_current = [](void* data) -> bool { return false; };
config.open_gl.present = [](void* data) -> bool { return false; };
config.open_gl.fbo_callback = [](void* data) -> uint32_t { return 0; };
} else {
// Provide the necessary callbacks for rendering within a GLFWwindow.
config.type = kOpenGL;
config.open_gl.struct_size = sizeof(config.open_gl);
config.open_gl.make_current = GLFWMakeContextCurrent;
config.open_gl.clear_current = GLFWClearContext;
config.open_gl.present = GLFWPresent;
config.open_gl.fbo_callback = GLFWGetActiveFbo;
config.open_gl.gl_proc_resolver = GLFWProcResolver;
}
FlutterProjectArgs args = {};
args.struct_size = sizeof(FlutterProjectArgs);
args.assets_path = assets_path;
args.icu_data_path = icu_data_path;
args.command_line_argc = static_cast<int>(argv.size());
args.command_line_argv = &argv[0];
args.platform_message_callback = GLFWOnFlutterPlatformMessage;
FlutterEngine engine = nullptr;
auto result =
FlutterEngineRun(FLUTTER_ENGINE_VERSION, &config, &args, window, &engine);
if (result != kSuccess || engine == nullptr) {
std::cerr << "Failed to start Flutter engine: error " << result
<< std::endl;
return nullptr;
}
return engine;
}
bool FlutterDesktopInit() {
// Before making any GLFW calls, set up a logging error handler.
glfwSetErrorCallback(GLFWErrorCallback);
return glfwInit();
}
void FlutterDesktopTerminate() {
glfwTerminate();
}
FlutterDesktopWindowRef FlutterDesktopCreateWindow(int initial_width,
int initial_height,
const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count) {
#ifdef __linux__
gtk_init(0, nullptr);
#endif
// Create the window.
auto window = glfwCreateWindow(initial_width, initial_height,
kDefaultWindowTitle, NULL, NULL);
if (window == nullptr) {
return nullptr;
}
GLFWClearCanvas(window);
// Start the engine.
auto engine = RunFlutterEngine(window, assets_path, icu_data_path, arguments,
argument_count);
if (engine == nullptr) {
glfwDestroyWindow(window);
return nullptr;
}
// Create a state object attached to the window.
FlutterDesktopWindowState* state = new FlutterDesktopWindowState();
state->window = window;
glfwSetWindowUserPointer(window, state);
state->engine = engine;
// TODO: Restructure the internals to follow the structure of the C++ API, so
// that this isn't a tangle of references.
auto messenger = std::make_unique<FlutterDesktopMessenger>();
state->message_dispatcher =
std::make_unique<shell::IncomingMessageDispatcher>(messenger.get());
messenger->engine = engine;
messenger->dispatcher = state->message_dispatcher.get();
state->plugin_registrar = std::make_unique<FlutterDesktopPluginRegistrar>();
state->plugin_registrar->messenger = std::move(messenger);
state->internal_plugin_registrar =
std::make_unique<flutter::PluginRegistrar>(state->plugin_registrar.get());
// Set up the keyboard handlers.
auto internal_plugin_messenger =
state->internal_plugin_registrar->messenger();
state->keyboard_hook_handlers.push_back(
std::make_unique<shell::KeyEventHandler>(internal_plugin_messenger));
state->keyboard_hook_handlers.push_back(
std::make_unique<shell::TextInputPlugin>(internal_plugin_messenger));
// Trigger an initial size callback to send size information to Flutter.
state->monitor_screen_coordinates_per_inch = GetScreenCoordinatesPerInch();
int width_px, height_px;
glfwGetFramebufferSize(window, &width_px, &height_px);
GLFWFramebufferSizeCallback(window, width_px, height_px);
// Set up GLFW callbacks for the window.
glfwSetFramebufferSizeCallback(window, GLFWFramebufferSizeCallback);
GLFWAssignEventCallbacks(window);
return state;
}
void FlutterDesktopSetHoverEnabled(FlutterDesktopWindowRef flutter_window,
bool enabled) {
flutter_window->hover_tracking_enabled = enabled;
SetHoverCallbacksEnabled(flutter_window->window, enabled);
}
void FlutterDesktopRunWindowLoop(FlutterDesktopWindowRef flutter_window) {
GLFWwindow* window = flutter_window->window;
#ifdef __linux__
// Necessary for GTK thread safety.
XInitThreads();
#endif
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
#ifdef __linux__
if (gtk_events_pending()) {
gtk_main_iteration();
}
#endif
// TODO(awdavies): This will be deprecated soon.
__FlutterEngineFlushPendingTasksNow();
}
FlutterEngineShutdown(flutter_window->engine);
delete flutter_window;
glfwDestroyWindow(window);
}
FlutterDesktopEngineRef FlutterDesktopRunEngine(const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count) {
auto engine = RunFlutterEngine(nullptr, assets_path, icu_data_path, arguments,
argument_count);
if (engine == nullptr) {
return nullptr;
}
auto engine_state = new FlutterDesktopEngineState();
engine_state->engine = engine;
return engine_state;
}
bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine_ref) {
std::cout << "Shutting down flutter engine process." << std::endl;
auto result = FlutterEngineShutdown(engine_ref->engine);
delete engine_ref;
return (result == kSuccess);
}
FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar(
FlutterDesktopWindowRef flutter_window,
const char* plugin_name) {
// Currently, one registrar acts as the registrar for all plugins, so the
// name is ignored. It is part of the API to reduce churn in the future when
// aligning more closely with the Flutter registrar system.
return flutter_window->plugin_registrar.get();
}
void FlutterDesktopRegistrarEnableInputBlocking(
FlutterDesktopPluginRegistrarRef registrar,
const char* channel) {
registrar->messenger->dispatcher->EnableInputBlockingForChannel(channel);
}
FlutterDesktopMessengerRef FlutterDesktopRegistrarGetMessenger(
FlutterDesktopPluginRegistrarRef registrar) {
return registrar->messenger.get();
}
void FlutterDesktopMessengerSend(FlutterDesktopMessengerRef messenger,
const char* channel,
const uint8_t* message,
const size_t message_size) {
FlutterPlatformMessage platform_message = {
sizeof(FlutterPlatformMessage),
channel,
message,
message_size,
};
FlutterEngineSendPlatformMessage(messenger->engine, &platform_message);
}
void FlutterDesktopMessengerSendResponse(
FlutterDesktopMessengerRef messenger,
const FlutterDesktopMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length) {
FlutterEngineSendPlatformMessageResponse(messenger->engine, handle, data,
data_length);
}
void FlutterDesktopMessengerSetCallback(FlutterDesktopMessengerRef messenger,
const char* channel,
FlutterDesktopMessageCallback callback,
void* user_data) {
messenger->dispatcher->SetMessageCallback(channel, callback, user_data);
}

View File

@@ -0,0 +1,60 @@
// Copyright 2013 The Flutter 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/shell/platform/glfw/key_event_handler.h"
#include <iostream>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/json_message_codec.h"
static constexpr char kChannelName[] = "flutter/keyevent";
static constexpr char kKeyCodeKey[] = "keyCode";
static constexpr char kKeyMapKey[] = "keymap";
static constexpr char kTypeKey[] = "type";
static constexpr char kAndroidKeyMap[] = "android";
static constexpr char kKeyUp[] = "keyup";
static constexpr char kKeyDown[] = "keydown";
namespace shell {
KeyEventHandler::KeyEventHandler(flutter::BinaryMessenger* messenger)
: channel_(
std::make_unique<flutter::BasicMessageChannel<rapidjson::Document>>(
messenger,
kChannelName,
&flutter::JsonMessageCodec::GetInstance())) {}
KeyEventHandler::~KeyEventHandler() = default;
void KeyEventHandler::CharHook(GLFWwindow* window, unsigned int code_point) {}
void KeyEventHandler::KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
// TODO: Translate to a cross-platform key code system rather than passing
// the native key code.
rapidjson::Document event(rapidjson::kObjectType);
auto& allocator = event.GetAllocator();
event.AddMember(kKeyCodeKey, key, allocator);
event.AddMember(kKeyMapKey, kAndroidKeyMap, allocator);
switch (action) {
case GLFW_PRESS:
event.AddMember(kTypeKey, kKeyDown, allocator);
break;
case GLFW_RELEASE:
event.AddMember(kTypeKey, kKeyUp, allocator);
break;
default:
std::cerr << "Unknown key event action: " << action << std::endl;
return;
}
channel_->Send(event);
}
} // namespace shell

View File

@@ -0,0 +1,44 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_GLFW_KEY_EVENT_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_KEY_EVENT_HANDLER_H_
#include <memory>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/basic_message_channel.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/binary_messenger.h"
#include "flutter/shell/platform/glfw/keyboard_hook_handler.h"
#include "flutter/shell/platform/glfw/public/flutter_glfw.h"
#include "rapidjson/document.h"
namespace shell {
// Implements a KeyboardHookHandler
//
// Handles key events and forwards them to the Flutter engine.
class KeyEventHandler : public KeyboardHookHandler {
public:
explicit KeyEventHandler(flutter::BinaryMessenger* messenger);
virtual ~KeyEventHandler();
// |shell::KeyboardHookHandler|
void KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) override;
// |shell::KeyboardHookHandler|
void CharHook(GLFWwindow* window, unsigned int code_point) override;
private:
// The Flutter system channel for key event messages.
std::unique_ptr<flutter::BasicMessageChannel<rapidjson::Document>> channel_;
};
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_GLFW_KEY_EVENT_HANDLER_H_

View File

@@ -0,0 +1,32 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_GLFW_KEYBOARD_HOOK_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_KEYBOARD_HOOK_HANDLER_H_
#include <GLFW/glfw3.h>
#include "flutter/shell/platform/glfw/public/flutter_glfw.h"
namespace shell {
// Abstract class for handling keyboard input events.
class KeyboardHookHandler {
public:
virtual ~KeyboardHookHandler() = default;
// A function for hooking into keyboard input.
virtual void KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) = 0;
// A function for hooking into unicode code point input.
virtual void CharHook(GLFWwindow* window, unsigned int code_point) = 0;
};
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_GLFW_KEYBOARD_HOOK_HANDLER_H_

View File

@@ -0,0 +1,109 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_
#include <stddef.h>
#include <stdint.h>
#include "flutter_export.h"
#include "flutter_messenger.h"
#include "flutter_plugin_registrar.h"
#if defined(__cplusplus)
extern "C" {
#endif
// Opaque reference to a Flutter window.
typedef struct FlutterDesktopWindowState* FlutterDesktopWindowRef;
// Opaque reference to a Flutter engine instance.
typedef struct FlutterDesktopEngineState* FlutterDesktopEngineRef;
// Sets up the library's graphic context. Must be called before any other
// methods.
//
// Note: Internally, this library uses GLFW, which does not support multiple
// copies within the same process. Internally this calls glfwInit, which will
// fail if you have called glfwInit elsewhere in the process.
FLUTTER_EXPORT bool FlutterDesktopInit();
// Tears down library state. Must be called before the process terminates.
FLUTTER_EXPORT void FlutterDesktopTerminate();
// Creates a Window running a Flutter Application.
//
// FlutterDesktopInit() must be called prior to this function.
//
// The |assets_path| is the path to the flutter_assets folder for the Flutter
// application to be run. |icu_data_path| is the path to the icudtl.dat file
// for the version of Flutter you are using.
//
// The |arguments| are passed to the Flutter engine. See:
// https://github.com/flutter/engine/blob/master/shell/common/switches.h for
// for details. Not all arguments will apply to desktop.
//
// Returns a null pointer in the event of an error. Otherwise, the pointer is
// valid until FlutterDesktopRunWindowLoop has been called and returned.
// Note that calling FlutterDesktopCreateWindow without later calling
// FlutterDesktopRunWindowLoop on the returned reference is a memory leak.
FLUTTER_EXPORT FlutterDesktopWindowRef
FlutterDesktopCreateWindow(int initial_width,
int initial_height,
const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count);
// Enables or disables hover tracking.
//
// If hover is enabled, mouse movement will send hover events to the Flutter
// engine, rather than only tracking the mouse while the button is pressed.
// Defaults to off.
FLUTTER_EXPORT void FlutterDesktopSetHoverEnabled(
FlutterDesktopWindowRef flutter_window,
bool enabled);
// Loops on Flutter window events until the window is closed.
//
// Once this function returns, FlutterDesktopWindowRef is no longer valid, and
// must not be used again.
FLUTTER_EXPORT void FlutterDesktopRunWindowLoop(
FlutterDesktopWindowRef flutter_window);
// Runs an instance of a headless Flutter engine.
//
// The |assets_path| is the path to the flutter_assets folder for the Flutter
// application to be run. |icu_data_path| is the path to the icudtl.dat file
// for the version of Flutter you are using.
//
// The |arguments| are passed to the Flutter engine. See:
// https://github.com/flutter/engine/blob/master/shell/common/switches.h for
// for details. Not all arguments will apply to desktop.
//
// Returns a null pointer in the event of an error.
FLUTTER_EXPORT FlutterDesktopEngineRef
FlutterDesktopRunEngine(const char* assets_path,
const char* icu_data_path,
const char** arguments,
size_t argument_count);
// Shuts down the given engine instance. Returns true if the shutdown was
// successful. |engine_ref| is no longer valid after this call.
FLUTTER_EXPORT bool FlutterDesktopShutDownEngine(
FlutterDesktopEngineRef engine_ref);
// Returns the plugin registrar handle for the plugin with the given name.
//
// The name must be unique across the application.
FLUTTER_EXPORT FlutterDesktopPluginRegistrarRef
FlutterDesktopGetPluginRegistrar(FlutterDesktopWindowRef flutter_window,
const char* plugin_name);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_SHELL_PLATFORM_GLFW_PUBLIC_FLUTTER_GLFW_H_

View File

@@ -0,0 +1,210 @@
// Copyright 2013 The Flutter 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/shell/platform/glfw/text_input_plugin.h"
#include <cstdint>
#include <iostream>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/json_method_codec.h"
static constexpr char kSetEditingStateMethod[] = "TextInput.setEditingState";
static constexpr char kClearClientMethod[] = "TextInput.clearClient";
static constexpr char kSetClientMethod[] = "TextInput.setClient";
static constexpr char kShowMethod[] = "TextInput.show";
static constexpr char kHideMethod[] = "TextInput.hide";
static constexpr char kMultilineInputType[] = "TextInputType.multiline";
static constexpr char kUpdateEditingStateMethod[] =
"TextInputClient.updateEditingState";
static constexpr char kPerformActionMethod[] = "TextInputClient.performAction";
static constexpr char kSelectionBaseKey[] = "selectionBase";
static constexpr char kSelectionExtentKey[] = "selectionExtent";
static constexpr char kTextKey[] = "text";
static constexpr char kChannelName[] = "flutter/textinput";
static constexpr char kBadArgumentError[] = "Bad Arguments";
static constexpr char kInternalConsistencyError[] =
"Internal Consistency Error";
static constexpr uint32_t kInputModelLimit = 256;
namespace shell {
void TextInputPlugin::CharHook(GLFWwindow* window, unsigned int code_point) {
if (active_model_ == nullptr) {
return;
}
// TODO(awdavies): Actually handle potential unicode characters. Probably
// requires some ICU data or something.
active_model_->AddCharacter(static_cast<char>(code_point));
SendStateUpdate(*active_model_);
}
void TextInputPlugin::KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
if (active_model_ == nullptr) {
return;
}
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
switch (key) {
case GLFW_KEY_LEFT:
if (active_model_->MoveCursorBack()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_RIGHT:
if (active_model_->MoveCursorForward()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_END:
active_model_->MoveCursorToEnd();
SendStateUpdate(*active_model_);
break;
case GLFW_KEY_HOME:
active_model_->MoveCursorToBeginning();
SendStateUpdate(*active_model_);
break;
case GLFW_KEY_BACKSPACE:
if (active_model_->Backspace()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_DELETE:
if (active_model_->Delete()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_ENTER:
EnterPressed(active_model_);
default:
break;
}
}
}
TextInputPlugin::TextInputPlugin(flutter::BinaryMessenger* messenger)
: channel_(std::make_unique<flutter::MethodChannel<rapidjson::Document>>(
messenger,
kChannelName,
&flutter::JsonMethodCodec::GetInstance())),
active_model_(nullptr) {
channel_->SetMethodCallHandler(
[this](
const flutter::MethodCall<rapidjson::Document>& call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) {
HandleMethodCall(call, std::move(result));
});
}
TextInputPlugin::~TextInputPlugin() = default;
void TextInputPlugin::HandleMethodCall(
const flutter::MethodCall<rapidjson::Document>& method_call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) {
const std::string& method = method_call.method_name();
if (method.compare(kShowMethod) == 0 || method.compare(kHideMethod) == 0) {
// These methods are no-ops.
} else if (method.compare(kClearClientMethod) == 0) {
active_model_ = nullptr;
} else {
// Every following method requires args.
if (!method_call.arguments() || method_call.arguments()->IsNull()) {
result->Error(kBadArgumentError, "Method invoked without args");
return;
}
const rapidjson::Document& args = *method_call.arguments();
if (method.compare(kSetClientMethod) == 0) {
// TODO(awdavies): There's quite a wealth of arguments supplied with this
// method, and they should be inspected/used.
const rapidjson::Value& client_id_json = args[0];
const rapidjson::Value& client_config = args[1];
if (client_id_json.IsNull()) {
result->Error(kBadArgumentError, "Could not set client, ID is null.");
return;
}
if (client_config.IsNull()) {
result->Error(kBadArgumentError,
"Could not set client, missing arguments.");
}
int client_id = client_id_json.GetInt();
if (input_models_.find(client_id) == input_models_.end()) {
// Skips out on adding a new input model once over the limit.
if (input_models_.size() > kInputModelLimit) {
result->Error(
kInternalConsistencyError,
"Input models over limit. Aborting creation of new text model.");
return;
}
input_models_.insert(std::make_pair(
client_id,
std::make_unique<TextInputModel>(client_id, client_config)));
}
active_model_ = input_models_[client_id].get();
} else if (method.compare(kSetEditingStateMethod) == 0) {
if (active_model_ == nullptr) {
result->Error(
kInternalConsistencyError,
"Set editing state has been invoked, but no client is set.");
return;
}
auto text = args.FindMember(kTextKey);
if (text == args.MemberEnd() || text->value.IsNull()) {
result->Error(kBadArgumentError,
"Set editing state has been invoked, but without text.");
return;
}
auto selection_base = args.FindMember(kSelectionBaseKey);
auto selection_extent = args.FindMember(kSelectionExtentKey);
if (selection_base == args.MemberEnd() ||
selection_base->value.IsNull() ||
selection_extent == args.MemberEnd() ||
selection_extent->value.IsNull()) {
result->Error(kInternalConsistencyError,
"Selection base/extent values invalid.");
return;
}
active_model_->SetEditingState(selection_base->value.GetInt(),
selection_extent->value.GetInt(),
text->value.GetString());
} else {
// Unhandled method.
result->NotImplemented();
return;
}
}
// All error conditions return early, so if nothing has gone wrong indicate
// success.
result->Success();
}
void TextInputPlugin::SendStateUpdate(const TextInputModel& model) {
channel_->InvokeMethod(kUpdateEditingStateMethod, model.GetState());
}
void TextInputPlugin::EnterPressed(TextInputModel* model) {
if (model->input_type() == kMultilineInputType) {
model->AddCharacter('\n');
SendStateUpdate(*model);
}
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(model->client_id(), allocator);
args->PushBack(rapidjson::Value(model->input_action(), allocator).Move(),
allocator);
channel_->InvokeMethod(kPerformActionMethod, std::move(args));
}
} // namespace shell

View File

@@ -0,0 +1,62 @@
// Copyright 2013 The Flutter 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_SHELL_PLATFORM_GLFW_TEXT_INPUT_PLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_TEXT_INPUT_PLUGIN_H_
#include <map>
#include <memory>
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/binary_messenger.h"
#include "flutter/shell/platform/common/cpp/client_wrapper/include/flutter/method_channel.h"
#include "flutter/shell/platform/common/cpp/text_input_model.h"
#include "flutter/shell/platform/glfw/keyboard_hook_handler.h"
#include "flutter/shell/platform/glfw/public/flutter_glfw.h"
namespace shell {
// Implements a text input plugin.
//
// Specifically handles window events within GLFW.
class TextInputPlugin : public KeyboardHookHandler {
public:
explicit TextInputPlugin(flutter::BinaryMessenger* messenger);
virtual ~TextInputPlugin();
// |shell::KeyboardHookHandler|
void KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) override;
// |shell::KeyboardHookHandler|
void CharHook(GLFWwindow* window, unsigned int code_point) override;
private:
// Sends the current state of the given model to the Flutter engine.
void SendStateUpdate(const TextInputModel& model);
// Sends an action triggered by the Enter key to the Flutter engine.
void EnterPressed(TextInputModel* model);
// Called when a method is called on |channel_|;
void HandleMethodCall(
const flutter::MethodCall<rapidjson::Document>& method_call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result);
// The MethodChannel used for communication with the Flutter engine.
std::unique_ptr<flutter::MethodChannel<rapidjson::Document>> channel_;
// Mapping of client IDs to text input models.
std::map<int, std::unique_ptr<TextInputModel>> input_models_;
// The active model. nullptr if not set.
TextInputModel* active_model_;
};
} // namespace shell
#endif // FLUTTER_SHELL_PLATFORM_GLFW_TEXT_INPUT_PLUGIN_H_

View File

@@ -2,10 +2,21 @@
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
group("linux") {
testonly = true
assert(is_linux)
group("linux") {
deps = [
"$flutter_root/shell/testing",
":flutter_linux",
"$flutter_root/shell/platform/glfw:publish_headers_glfw",
"$flutter_root/shell/platform/common/cpp/client_wrapper:publish_wrapper",
"$flutter_root/shell/platform/glfw/client_wrapper:publish_wrapper_glfw",
]
}
shared_library("flutter_linux") {
deps = [
"$flutter_root/shell/platform/glfw:flutter_glfw",
]
public_configs = [ "$flutter_root:config" ]
}

View File

@@ -0,0 +1,21 @@
# Copyright 2013 The Flutter 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("//build/config/linux/pkg_config.gni")
pkg_config("epoxy") {
packages = [ "epoxy" ]
}
pkg_config("glfw3") {
packages = [ "glfw3" ]
}
pkg_config("gtk3") {
packages = [ "gtk+-3.0" ]
}
pkg_config("x11") {
packages = [ "x11" ]
}