未验证 提交 4943475c 编写于 作者: G gaaclarke 提交者: GitHub

Added an embedder example (#12808)

上级 32ca0cc7
cmake_minimum_required(VERSION 3.15)
project(FlutterEmbedderGLFW)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )
add_executable(flutter_glfw FlutterEmbedderGLFW.cc)
############################################################
# GLFW
############################################################
find_path(GLFW_INCLUDE_PATH "glfw3.h"
/usr/local/Cellar/glfw/3.3/include/GLFW/
/usr/local/include/include/GLFW/
/usr/include/GLFW)
include_directories(${GLFW_INCLUDE_PATH})
find_library(GLFW_LIB glfw /usr/local/Cellar/glfw/3.3/lib)
target_link_libraries(flutter_glfw ${GLFW_LIB})
############################################################
# Flutter Engine
############################################################
# This is assuming you've built a local version of the Flutter Engine. If you
# downloaded yours is from the internet you'll have to change this.
include_directories(${CMAKE_SOURCE_DIR}/../../shell/platform/embedder)
find_library(FLUTTER_LIB flutter_engine PATHS ${CMAKE_SOURCE_DIR}/../../../out/host_debug_unopt)
target_link_libraries(flutter_glfw ${FLUTTER_LIB})
# Copy the flutter library here since the shared library
# name is `./libflutter_engine.dylib`.
add_custom_command(
TARGET flutter_glfw POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
${FLUTTER_LIB}
${CMAKE_CURRENT_BINARY_DIR})
#include <assert.h>
#include <embedder.h>
#include <glfw3.h>
#include <chrono>
#include <iostream>
// This value is calculated after the window is created.
static double g_pixelRatio = 1.0;
static const size_t kInitialWindowWidth = 800;
static const size_t kInitialWindowHeight = 600;
static_assert(FLUTTER_ENGINE_VERSION == 1,
"This Flutter Embedder was authored against the stable Flutter "
"API at version 1. There has been a serious breakage in the "
"API. Please read the ChangeLog and take appropriate action "
"before updating this assertion");
void GLFWcursorPositionCallbackAtPhase(GLFWwindow* window,
FlutterPointerPhase phase,
double x,
double y) {
FlutterPointerEvent event = {};
event.struct_size = sizeof(event);
event.phase = phase;
event.x = x * g_pixelRatio;
event.y = y * g_pixelRatio;
event.timestamp =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
FlutterEngineSendPointerEvent(
reinterpret_cast<FlutterEngine>(glfwGetWindowUserPointer(window)), &event,
1);
}
void GLFWcursorPositionCallback(GLFWwindow* window, double x, double y) {
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kMove, x, y);
}
void GLFWmouseButtonCallback(GLFWwindow* window,
int key,
int action,
int mods) {
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_PRESS) {
double x, y;
glfwGetCursorPos(window, &x, &y);
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kDown, x, y);
glfwSetCursorPosCallback(window, GLFWcursorPositionCallback);
}
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_RELEASE) {
double x, y;
glfwGetCursorPos(window, &x, &y);
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kUp, x, y);
glfwSetCursorPosCallback(window, nullptr);
}
}
static void GLFWKeyCallback(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
}
void GLFWwindowSizeCallback(GLFWwindow* window, int width, int height) {
FlutterWindowMetricsEvent event = {};
event.struct_size = sizeof(event);
event.width = width * g_pixelRatio;
event.height = height * g_pixelRatio;
event.pixel_ratio = g_pixelRatio;
FlutterEngineSendWindowMetricsEvent(
reinterpret_cast<FlutterEngine>(glfwGetWindowUserPointer(window)),
&event);
}
bool RunFlutter(GLFWwindow* window,
const std::string& project_path,
const std::string& icudtl_path) {
FlutterRendererConfig config = {};
config.type = kOpenGL;
config.open_gl.struct_size = sizeof(config.open_gl);
config.open_gl.make_current = [](void* userdata) -> bool {
glfwMakeContextCurrent((GLFWwindow*)userdata);
return true;
};
config.open_gl.clear_current = [](void*) -> bool {
glfwMakeContextCurrent(nullptr); // is this even a thing?
return true;
};
config.open_gl.present = [](void* userdata) -> bool {
glfwSwapBuffers((GLFWwindow*)userdata);
return true;
};
config.open_gl.fbo_callback = [](void*) -> uint32_t {
return 0; // FBO0
};
// This directory is generated by `flutter build bundle`.
std::string assets_path = project_path + "/build/flutter_assets";
FlutterProjectArgs args = {
.struct_size = sizeof(FlutterProjectArgs),
.assets_path = assets_path.c_str(),
.icu_data_path =
icudtl_path.c_str(), // Find this in your bin/cache directory.
};
FlutterEngine engine = nullptr;
FlutterEngineResult result =
FlutterEngineRun(FLUTTER_ENGINE_VERSION, &config, // renderer
&args, window, &engine);
assert(result == kSuccess && engine != nullptr);
glfwSetWindowUserPointer(window, engine);
GLFWwindowSizeCallback(window, kInitialWindowWidth, kInitialWindowHeight);
return true;
}
void printUsage() {
std::cout << "usage: flutter_glfw <path to project> <path to icudtl.dat>"
<< std::endl;
}
int main(int argc, const char* argv[]) {
if (argc != 3) {
printUsage();
return 1;
}
std::string project_path = argv[1];
std::string icudtl_path = argv[2];
int result = glfwInit();
assert(result == GLFW_TRUE);
GLFWwindow* window = glfwCreateWindow(
kInitialWindowWidth, kInitialWindowHeight, "Flutter", NULL, NULL);
assert(window != nullptr);
int framebuffer_width, framebuffer_height;
glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height);
g_pixelRatio = framebuffer_width / kInitialWindowWidth;
bool runResult = RunFlutter(window, project_path, icudtl_path);
assert(runResult);
glfwSetKeyCallback(window, GLFWKeyCallback);
glfwSetWindowSizeCallback(window, GLFWwindowSizeCallback);
glfwSetMouseButtonCallback(window, GLFWmouseButtonCallback);
while (!glfwWindowShouldClose(window)) {
std::cout << "Looping..." << std::endl;
glfwWaitEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return EXIT_SUCCESS;
}
# Flutter Embedder Engine GLFW Example
## Description
This is an example of how to use Flutter Engine Embedder in order to get a
Flutter project rendering in a new host environment. The intended audience is
people who need to support host environment other than the ones already provided
by Flutter. This is an advanced topic and not intended for beginners.
In this example we are demonstrating rendering a Flutter project inside of the GUI
library [GLFW](https://www.glfw.org/). For more information about using the
embedder you can read the wiki article [Custom Flutter Engine Embedders](https://github.com/flutter/flutter/wiki/Custom-Flutter-Engine-Embedders).
## Running Instructions
The following example was tested on MacOSX but with a bit of tweaking should be
able to run on other *nix platforms and Windows.
The example has the following dependencies:
* [GLFW](https://www.glfw.org/) - This can be installed with [Homebrew](https://brew.sh/) - `brew install glfw`
* [CMake](https://cmake.org/) - This can be installed with [Homebrew](https://brew.sh/) - `brew install cmake`
* [Flutter](https://flutter.dev/) - This can be installed from the [Flutter webpage](https://flutter.dev/docs/get-started/install)
* [Flutter Engine](https://flutter.dev) - This can be built or downloaded, see [Custom Flutter Engine Embedders](https://github.com/flutter/flutter/wiki/Custom-Flutter-Engine-Embedders) for more information.
In order to run the example you should be able to go into this directory and run
`./run.sh`.
## Troubleshooting
There are a few things you might have to tweak in order to get your build working:
* Flutter Engine Location - Inside the `CMakeList.txt` file you will see that it is setup to search for the header and library for the Flutter Engine in specific locations, those might not be the location of your Flutter Engine.
* Pixel Ratio - If the project runs but is drawing at the wrong scale you may have to tweak the `kPixelRatio` variable in `FlutterEmbedderGLFW.cc` file.
* GLFW Location - Inside the `CMakeLists.txt` we are searching for the GLFW library, if CMake can't find it you may have to edit that.
\ No newline at end of file
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart'
show debugDefaultTargetPlatformOverride;
void main() {
// This is a hack to make Flutter think you are running on Google Fuchsia,
// otherwise you will get an error about running from an unsupported platform.
debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
#!/bin/bash
set -e # Exit if any program returns an error.
#################################################################
# Make the host C++ project.
#################################################################
if [ ! -d debug ]; then
mkdir debug
fi
cd debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make
#################################################################
# Make the guest Flutter project.
#################################################################
if [ ! -d myapp ]; then
flutter create myapp
fi
cd myapp
cp ../../main.dart lib/main.dart
flutter build bundle
cd -
#################################################################
# Run the Flutter Engine Embedder
#################################################################
./flutter_glfw ./myapp ../../../../third_party/icu/common/icudtl.dat
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册