Skip to content
This repository was archived by the owner on Feb 25, 2025. It is now read-only.

Commit 4943475

Browse files
authored
Added an embedder example (#12808)
1 parent 32ca0cc commit 4943475

File tree

5 files changed

+372
-0
lines changed

5 files changed

+372
-0
lines changed

examples/glfw/CMakeLists.txt

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
cmake_minimum_required(VERSION 3.15)
2+
project(FlutterEmbedderGLFW)
3+
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )
4+
5+
add_executable(flutter_glfw FlutterEmbedderGLFW.cc)
6+
7+
############################################################
8+
# GLFW
9+
############################################################
10+
find_path(GLFW_INCLUDE_PATH "glfw3.h"
11+
/usr/local/Cellar/glfw/3.3/include/GLFW/
12+
/usr/local/include/include/GLFW/
13+
/usr/include/GLFW)
14+
include_directories(${GLFW_INCLUDE_PATH})
15+
find_library(GLFW_LIB glfw /usr/local/Cellar/glfw/3.3/lib)
16+
target_link_libraries(flutter_glfw ${GLFW_LIB})
17+
18+
############################################################
19+
# Flutter Engine
20+
############################################################
21+
# This is assuming you've built a local version of the Flutter Engine. If you
22+
# downloaded yours is from the internet you'll have to change this.
23+
include_directories(${CMAKE_SOURCE_DIR}/../../shell/platform/embedder)
24+
find_library(FLUTTER_LIB flutter_engine PATHS ${CMAKE_SOURCE_DIR}/../../../out/host_debug_unopt)
25+
target_link_libraries(flutter_glfw ${FLUTTER_LIB})
26+
27+
# Copy the flutter library here since the shared library
28+
# name is `./libflutter_engine.dylib`.
29+
add_custom_command(
30+
TARGET flutter_glfw POST_BUILD
31+
COMMAND ${CMAKE_COMMAND} -E copy
32+
${FLUTTER_LIB}
33+
${CMAKE_CURRENT_BINARY_DIR})

examples/glfw/FlutterEmbedderGLFW.cc

+164
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
2+
#include <assert.h>
3+
#include <embedder.h>
4+
#include <glfw3.h>
5+
#include <chrono>
6+
#include <iostream>
7+
8+
// This value is calculated after the window is created.
9+
static double g_pixelRatio = 1.0;
10+
static const size_t kInitialWindowWidth = 800;
11+
static const size_t kInitialWindowHeight = 600;
12+
13+
static_assert(FLUTTER_ENGINE_VERSION == 1,
14+
"This Flutter Embedder was authored against the stable Flutter "
15+
"API at version 1. There has been a serious breakage in the "
16+
"API. Please read the ChangeLog and take appropriate action "
17+
"before updating this assertion");
18+
19+
void GLFWcursorPositionCallbackAtPhase(GLFWwindow* window,
20+
FlutterPointerPhase phase,
21+
double x,
22+
double y) {
23+
FlutterPointerEvent event = {};
24+
event.struct_size = sizeof(event);
25+
event.phase = phase;
26+
event.x = x * g_pixelRatio;
27+
event.y = y * g_pixelRatio;
28+
event.timestamp =
29+
std::chrono::duration_cast<std::chrono::microseconds>(
30+
std::chrono::high_resolution_clock::now().time_since_epoch())
31+
.count();
32+
FlutterEngineSendPointerEvent(
33+
reinterpret_cast<FlutterEngine>(glfwGetWindowUserPointer(window)), &event,
34+
1);
35+
}
36+
37+
void GLFWcursorPositionCallback(GLFWwindow* window, double x, double y) {
38+
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kMove, x, y);
39+
}
40+
41+
void GLFWmouseButtonCallback(GLFWwindow* window,
42+
int key,
43+
int action,
44+
int mods) {
45+
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_PRESS) {
46+
double x, y;
47+
glfwGetCursorPos(window, &x, &y);
48+
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kDown, x, y);
49+
glfwSetCursorPosCallback(window, GLFWcursorPositionCallback);
50+
}
51+
52+
if (key == GLFW_MOUSE_BUTTON_1 && action == GLFW_RELEASE) {
53+
double x, y;
54+
glfwGetCursorPos(window, &x, &y);
55+
GLFWcursorPositionCallbackAtPhase(window, FlutterPointerPhase::kUp, x, y);
56+
glfwSetCursorPosCallback(window, nullptr);
57+
}
58+
}
59+
60+
static void GLFWKeyCallback(GLFWwindow* window,
61+
int key,
62+
int scancode,
63+
int action,
64+
int mods) {
65+
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
66+
glfwSetWindowShouldClose(window, GLFW_TRUE);
67+
}
68+
}
69+
70+
void GLFWwindowSizeCallback(GLFWwindow* window, int width, int height) {
71+
FlutterWindowMetricsEvent event = {};
72+
event.struct_size = sizeof(event);
73+
event.width = width * g_pixelRatio;
74+
event.height = height * g_pixelRatio;
75+
event.pixel_ratio = g_pixelRatio;
76+
FlutterEngineSendWindowMetricsEvent(
77+
reinterpret_cast<FlutterEngine>(glfwGetWindowUserPointer(window)),
78+
&event);
79+
}
80+
81+
bool RunFlutter(GLFWwindow* window,
82+
const std::string& project_path,
83+
const std::string& icudtl_path) {
84+
FlutterRendererConfig config = {};
85+
config.type = kOpenGL;
86+
config.open_gl.struct_size = sizeof(config.open_gl);
87+
config.open_gl.make_current = [](void* userdata) -> bool {
88+
glfwMakeContextCurrent((GLFWwindow*)userdata);
89+
return true;
90+
};
91+
config.open_gl.clear_current = [](void*) -> bool {
92+
glfwMakeContextCurrent(nullptr); // is this even a thing?
93+
return true;
94+
};
95+
config.open_gl.present = [](void* userdata) -> bool {
96+
glfwSwapBuffers((GLFWwindow*)userdata);
97+
return true;
98+
};
99+
config.open_gl.fbo_callback = [](void*) -> uint32_t {
100+
return 0; // FBO0
101+
};
102+
103+
// This directory is generated by `flutter build bundle`.
104+
std::string assets_path = project_path + "/build/flutter_assets";
105+
FlutterProjectArgs args = {
106+
.struct_size = sizeof(FlutterProjectArgs),
107+
.assets_path = assets_path.c_str(),
108+
.icu_data_path =
109+
icudtl_path.c_str(), // Find this in your bin/cache directory.
110+
};
111+
FlutterEngine engine = nullptr;
112+
FlutterEngineResult result =
113+
FlutterEngineRun(FLUTTER_ENGINE_VERSION, &config, // renderer
114+
&args, window, &engine);
115+
assert(result == kSuccess && engine != nullptr);
116+
117+
glfwSetWindowUserPointer(window, engine);
118+
GLFWwindowSizeCallback(window, kInitialWindowWidth, kInitialWindowHeight);
119+
120+
return true;
121+
}
122+
123+
void printUsage() {
124+
std::cout << "usage: flutter_glfw <path to project> <path to icudtl.dat>"
125+
<< std::endl;
126+
}
127+
128+
int main(int argc, const char* argv[]) {
129+
if (argc != 3) {
130+
printUsage();
131+
return 1;
132+
}
133+
134+
std::string project_path = argv[1];
135+
std::string icudtl_path = argv[2];
136+
137+
int result = glfwInit();
138+
assert(result == GLFW_TRUE);
139+
140+
GLFWwindow* window = glfwCreateWindow(
141+
kInitialWindowWidth, kInitialWindowHeight, "Flutter", NULL, NULL);
142+
assert(window != nullptr);
143+
144+
int framebuffer_width, framebuffer_height;
145+
glfwGetFramebufferSize(window, &framebuffer_width, &framebuffer_height);
146+
g_pixelRatio = framebuffer_width / kInitialWindowWidth;
147+
148+
bool runResult = RunFlutter(window, project_path, icudtl_path);
149+
assert(runResult);
150+
151+
glfwSetKeyCallback(window, GLFWKeyCallback);
152+
glfwSetWindowSizeCallback(window, GLFWwindowSizeCallback);
153+
glfwSetMouseButtonCallback(window, GLFWmouseButtonCallback);
154+
155+
while (!glfwWindowShouldClose(window)) {
156+
std::cout << "Looping..." << std::endl;
157+
glfwWaitEvents();
158+
}
159+
160+
glfwDestroyWindow(window);
161+
glfwTerminate();
162+
163+
return EXIT_SUCCESS;
164+
}

examples/glfw/README.md

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Flutter Embedder Engine GLFW Example
2+
## Description
3+
This is an example of how to use Flutter Engine Embedder in order to get a
4+
Flutter project rendering in a new host environment. The intended audience is
5+
people who need to support host environment other than the ones already provided
6+
by Flutter. This is an advanced topic and not intended for beginners.
7+
8+
In this example we are demonstrating rendering a Flutter project inside of the GUI
9+
library [GLFW](https://www.glfw.org/). For more information about using the
10+
embedder you can read the wiki article [Custom Flutter Engine Embedders](https://github.com/flutter/flutter/wiki/Custom-Flutter-Engine-Embedders).
11+
12+
## Running Instructions
13+
The following example was tested on MacOSX but with a bit of tweaking should be
14+
able to run on other *nix platforms and Windows.
15+
16+
The example has the following dependencies:
17+
* [GLFW](https://www.glfw.org/) - This can be installed with [Homebrew](https://brew.sh/) - `brew install glfw`
18+
* [CMake](https://cmake.org/) - This can be installed with [Homebrew](https://brew.sh/) - `brew install cmake`
19+
* [Flutter](https://flutter.dev/) - This can be installed from the [Flutter webpage](https://flutter.dev/docs/get-started/install)
20+
* [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.
21+
22+
In order to run the example you should be able to go into this directory and run
23+
`./run.sh`.
24+
25+
## Troubleshooting
26+
There are a few things you might have to tweak in order to get your build working:
27+
* 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.
28+
* 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.
29+
* 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.

examples/glfw/main.dart

+118
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import 'package:flutter/material.dart';
2+
import 'package:flutter/foundation.dart'
3+
show debugDefaultTargetPlatformOverride;
4+
5+
void main() {
6+
// This is a hack to make Flutter think you are running on Google Fuchsia,
7+
// otherwise you will get an error about running from an unsupported platform.
8+
debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
9+
runApp(MyApp());
10+
}
11+
12+
class MyApp extends StatelessWidget {
13+
// This widget is the root of your application.
14+
@override
15+
Widget build(BuildContext context) {
16+
return MaterialApp(
17+
title: 'Flutter Demo',
18+
theme: ThemeData(
19+
// This is the theme of your application.
20+
//
21+
// Try running your application with "flutter run". You'll see the
22+
// application has a blue toolbar. Then, without quitting the app, try
23+
// changing the primarySwatch below to Colors.green and then invoke
24+
// "hot reload" (press "r" in the console where you ran "flutter run",
25+
// or simply save your changes to "hot reload" in a Flutter IDE).
26+
// Notice that the counter didn't reset back to zero; the application
27+
// is not restarted.
28+
primarySwatch: Colors.blue,
29+
),
30+
home: MyHomePage(title: 'Flutter Demo Home Page'),
31+
);
32+
}
33+
}
34+
35+
class MyHomePage extends StatefulWidget {
36+
MyHomePage({Key key, this.title}) : super(key: key);
37+
38+
// This widget is the home page of your application. It is stateful, meaning
39+
// that it has a State object (defined below) that contains fields that affect
40+
// how it looks.
41+
42+
// This class is the configuration for the state. It holds the values (in this
43+
// case the title) provided by the parent (in this case the App widget) and
44+
// used by the build method of the State. Fields in a Widget subclass are
45+
// always marked "final".
46+
47+
final String title;
48+
49+
@override
50+
_MyHomePageState createState() => _MyHomePageState();
51+
}
52+
53+
class _MyHomePageState extends State<MyHomePage> {
54+
int _counter = 0;
55+
56+
void _incrementCounter() {
57+
setState(() {
58+
// This call to setState tells the Flutter framework that something has
59+
// changed in this State, which causes it to rerun the build method below
60+
// so that the display can reflect the updated values. If we changed
61+
// _counter without calling setState(), then the build method would not be
62+
// called again, and so nothing would appear to happen.
63+
_counter++;
64+
});
65+
}
66+
67+
@override
68+
Widget build(BuildContext context) {
69+
// This method is rerun every time setState is called, for instance as done
70+
// by the _incrementCounter method above.
71+
//
72+
// The Flutter framework has been optimized to make rerunning build methods
73+
// fast, so that you can just rebuild anything that needs updating rather
74+
// than having to individually change instances of widgets.
75+
return Scaffold(
76+
appBar: AppBar(
77+
// Here we take the value from the MyHomePage object that was created by
78+
// the App.build method, and use it to set our appbar title.
79+
title: Text(widget.title),
80+
),
81+
body: Center(
82+
// Center is a layout widget. It takes a single child and positions it
83+
// in the middle of the parent.
84+
child: Column(
85+
// Column is also a layout widget. It takes a list of children and
86+
// arranges them vertically. By default, it sizes itself to fit its
87+
// children horizontally, and tries to be as tall as its parent.
88+
//
89+
// Invoke "debug painting" (press "p" in the console, choose the
90+
// "Toggle Debug Paint" action from the Flutter Inspector in Android
91+
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
92+
// to see the wireframe for each widget.
93+
//
94+
// Column has various properties to control how it sizes itself and
95+
// how it positions its children. Here we use mainAxisAlignment to
96+
// center the children vertically; the main axis here is the vertical
97+
// axis because Columns are vertical (the cross axis would be
98+
// horizontal).
99+
mainAxisAlignment: MainAxisAlignment.center,
100+
children: <Widget>[
101+
Text(
102+
'You have pushed the button this many times:',
103+
),
104+
Text(
105+
'$_counter',
106+
style: Theme.of(context).textTheme.display1,
107+
),
108+
],
109+
),
110+
),
111+
floatingActionButton: FloatingActionButton(
112+
onPressed: _incrementCounter,
113+
tooltip: 'Increment',
114+
child: Icon(Icons.add),
115+
), // This trailing comma makes auto-formatting nicer for build methods.
116+
);
117+
}
118+
}

examples/glfw/run.sh

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/bin/bash
2+
set -e # Exit if any program returns an error.
3+
4+
#################################################################
5+
# Make the host C++ project.
6+
#################################################################
7+
if [ ! -d debug ]; then
8+
mkdir debug
9+
fi
10+
cd debug
11+
cmake -DCMAKE_BUILD_TYPE=Debug ..
12+
make
13+
14+
#################################################################
15+
# Make the guest Flutter project.
16+
#################################################################
17+
if [ ! -d myapp ]; then
18+
flutter create myapp
19+
fi
20+
cd myapp
21+
cp ../../main.dart lib/main.dart
22+
flutter build bundle
23+
cd -
24+
25+
#################################################################
26+
# Run the Flutter Engine Embedder
27+
#################################################################
28+
./flutter_glfw ./myapp ../../../../third_party/icu/common/icudtl.dat

0 commit comments

Comments
 (0)