Repository: ekibun/flutter_qjs Branch: master Commit: 32aac42c194b Files: 141 Total size: 274.5 KB Directory structure: gitextract_pfjni9x0/ ├── .github/ │ └── workflows/ │ └── test.yml ├── .gitignore ├── .gitmodules ├── .metadata ├── .vscode/ │ ├── c_cpp_properties.json │ └── launch.json ├── CHANGELOG.md ├── LICENSE ├── README-CN.md ├── README.md ├── android/ │ ├── .classpath │ ├── .gitignore │ ├── .project │ ├── .settings/ │ │ └── org.eclipse.buildship.core.prefs │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ ├── settings.gradle │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── cxx/ │ │ └── CMakeLists.txt │ └── kotlin/ │ └── soko/ │ └── ekibun/ │ └── flutter_qjs/ │ └── FlutterQjsPlugin.kt ├── coverage/ │ └── lcov.info ├── cxx/ │ ├── ffi.cpp │ ├── ffi.h │ ├── prebuild.sh │ └── quickjs.cmake ├── example/ │ ├── .gitignore │ ├── .metadata │ ├── README.md │ ├── analysis_options.yaml │ ├── android/ │ │ ├── .gitignore │ │ ├── app/ │ │ │ ├── build.gradle │ │ │ └── src/ │ │ │ ├── debug/ │ │ │ │ └── AndroidManifest.xml │ │ │ ├── main/ │ │ │ │ ├── AndroidManifest.xml │ │ │ │ ├── kotlin/ │ │ │ │ │ └── soko/ │ │ │ │ │ └── ekibun/ │ │ │ │ │ └── flutter_qjs_example/ │ │ │ │ │ └── MainActivity.kt │ │ │ │ └── res/ │ │ │ │ ├── drawable/ │ │ │ │ │ └── launch_background.xml │ │ │ │ ├── drawable-v21/ │ │ │ │ │ └── launch_background.xml │ │ │ │ ├── values/ │ │ │ │ │ └── styles.xml │ │ │ │ └── values-night/ │ │ │ │ └── styles.xml │ │ │ └── profile/ │ │ │ └── AndroidManifest.xml │ │ ├── build.gradle │ │ ├── gradle/ │ │ │ └── wrapper/ │ │ │ └── gradle-wrapper.properties │ │ ├── gradle.properties │ │ └── settings.gradle │ ├── ios/ │ │ ├── .gitignore │ │ ├── Flutter/ │ │ │ ├── AppFrameworkInfo.plist │ │ │ ├── Debug.xcconfig │ │ │ └── Release.xcconfig │ │ ├── Podfile │ │ ├── Runner/ │ │ │ ├── AppDelegate.swift │ │ │ ├── Assets.xcassets/ │ │ │ │ ├── AppIcon.appiconset/ │ │ │ │ │ └── Contents.json │ │ │ │ └── LaunchImage.imageset/ │ │ │ │ ├── Contents.json │ │ │ │ └── README.md │ │ │ ├── Base.lproj/ │ │ │ │ ├── LaunchScreen.storyboard │ │ │ │ └── Main.storyboard │ │ │ ├── Info.plist │ │ │ └── Runner-Bridging-Header.h │ │ ├── Runner.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace/ │ │ │ │ ├── contents.xcworkspacedata │ │ │ │ └── xcshareddata/ │ │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ │ └── WorkspaceSettings.xcsettings │ │ │ └── xcshareddata/ │ │ │ └── xcschemes/ │ │ │ └── Runner.xcscheme │ │ └── Runner.xcworkspace/ │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ ├── IDEWorkspaceChecks.plist │ │ └── WorkspaceSettings.xcsettings │ ├── js/ │ │ └── hello.js │ ├── lib/ │ │ ├── highlight.dart │ │ └── main.dart │ ├── linux/ │ │ ├── .gitignore │ │ ├── CMakeLists.txt │ │ ├── flutter/ │ │ │ ├── CMakeLists.txt │ │ │ ├── generated_plugin_registrant.cc │ │ │ ├── generated_plugin_registrant.h │ │ │ └── generated_plugins.cmake │ │ ├── main.cc │ │ ├── my_application.cc │ │ └── my_application.h │ ├── macos/ │ │ ├── .gitignore │ │ ├── Flutter/ │ │ │ ├── Flutter-Debug.xcconfig │ │ │ ├── Flutter-Release.xcconfig │ │ │ └── GeneratedPluginRegistrant.swift │ │ ├── Podfile │ │ ├── Runner/ │ │ │ ├── AppDelegate.swift │ │ │ ├── Assets.xcassets/ │ │ │ │ └── AppIcon.appiconset/ │ │ │ │ └── Contents.json │ │ │ ├── Base.lproj/ │ │ │ │ └── MainMenu.xib │ │ │ ├── Configs/ │ │ │ │ ├── AppInfo.xcconfig │ │ │ │ ├── Debug.xcconfig │ │ │ │ ├── Release.xcconfig │ │ │ │ └── Warnings.xcconfig │ │ │ ├── DebugProfile.entitlements │ │ │ ├── Info.plist │ │ │ ├── MainFlutterWindow.swift │ │ │ └── Release.entitlements │ │ ├── Runner.xcodeproj/ │ │ │ ├── project.pbxproj │ │ │ ├── project.xcworkspace/ │ │ │ │ └── xcshareddata/ │ │ │ │ └── IDEWorkspaceChecks.plist │ │ │ └── xcshareddata/ │ │ │ └── xcschemes/ │ │ │ └── Runner.xcscheme │ │ └── Runner.xcworkspace/ │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata/ │ │ └── IDEWorkspaceChecks.plist │ ├── pubspec.yaml │ └── windows/ │ ├── .gitignore │ ├── CMakeLists.txt │ ├── flutter/ │ │ ├── CMakeLists.txt │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugin_registrant.h │ │ └── generated_plugins.cmake │ └── runner/ │ ├── CMakeLists.txt │ ├── Runner.rc │ ├── flutter_window.cpp │ ├── flutter_window.h │ ├── main.cpp │ ├── resource.h │ ├── runner.exe.manifest │ ├── utils.cpp │ ├── utils.h │ ├── win32_window.cpp │ └── win32_window.h ├── flutter_qjs.iml ├── ios/ │ ├── .gitignore │ ├── Assets/ │ │ └── .gitkeep │ ├── Classes/ │ │ ├── FlutterQjsPlugin.h │ │ ├── FlutterQjsPlugin.m │ │ └── SwiftFlutterQjsPlugin.swift │ └── flutter_qjs.podspec ├── lib/ │ ├── flutter_qjs.dart │ └── src/ │ ├── engine.dart │ ├── ffi.dart │ ├── isolate.dart │ ├── object.dart │ └── wrapper.dart ├── linux/ │ ├── CMakeLists.txt │ ├── flutter_qjs_plugin.cc │ └── include/ │ └── flutter_qjs/ │ └── flutter_qjs_plugin.h ├── macos/ │ ├── Classes/ │ │ └── FlutterQjsPlugin.swift │ └── flutter_qjs.podspec ├── pubspec.yaml ├── test/ │ ├── CMakeLists.txt │ └── flutter_qjs_test.dart └── windows/ ├── .gitignore ├── CMakeLists.txt ├── flutter_qjs_plugin.cpp └── include/ └── flutter_qjs/ └── flutter_qjs_plugin.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/test.yml ================================================ name: Test on: push: branches: - master jobs: test: name: Test on ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [macos-latest, ubuntu-latest, windows-latest] steps: - uses: actions/checkout@v2 - name: Update submodules run: git submodule update --init --recursive - name: Flutter action uses: subosito/flutter-action@v1 with: channel: beta - run: flutter pub get - run: flutter test test/flutter_qjs_test.dart ================================================ FILE: .gitignore ================================================ .DS_Store .dart_tool/ .packages .pub/ build/ .idea/ .vscode/settings.json ios/cxx macos/cxx ================================================ FILE: .gitmodules ================================================ [submodule "cxx/quickjs"] path = cxx/quickjs url = https://github.com/ekibun/quickjs.git ================================================ FILE: .metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: f3b7788f7754a51092ae1d677001767960c21910 channel: master project_type: plugin ================================================ FILE: .vscode/c_cpp_properties.json ================================================ { "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}/windows/**", "${workspaceFolder}/example/windows/**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.18362.0", "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/BuildTools/VC/Tools/MSVC/14.27.29110/bin/Hostx64/x64/cl.exe", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "msvc-x64" }, { "name": "Android", "includePath": [ "C:/Users/ekibun/AppData/Local/Android/Sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/windows-x86_64/sysroot/usr/include" ], "defines": [ "__ANDROID__", "__LINUX__" ], "windowsSdkVersion": "10.0.18362.0", "compilerPath": "C:/Users/ekibun/AppData/Local/Android/Sdk/cmake/3.10.2.4988404/bin/cmake.exe", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "gcc-x64" }, { "name": "Linux", "includePath": [ "${workspaceFolder}/linux/**", "${workspaceFolder}/example/linux/**", "/usr/include/**" ], "defines": [ "__LINUX__" ], "windowsSdkVersion": "10.0.18362.0", "compilerPath": "/usr/bin/clang++", "cStandard": "c11", "cppStandard": "c++17", "intelliSenseMode": "gcc-x64" } ], "version": 4 } ================================================ FILE: .vscode/launch.json ================================================ { // 使用 IntelliSense 了解相关属性。 // 悬停以查看现有属性的描述。 // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Flutter: Run all Tests", "type": "dart", "request": "launch", "program": "./test/" }, { "name": "(Windows) 启动", "type": "cppvsdbg", "request": "launch", "program": "${workspaceFolder}/example/build/windows/runner/Debug/example.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false }, { "name": "Flutter", "program": "example/lib/main.dart", "request": "launch", "type": "dart" } ] } ================================================ FILE: CHANGELOG.md ================================================ ## 0.3.7 * add timeout and memory limit * fixed compiler error in windows release * fixed crash when encoding Error object * updated to latest quickjs ## 0.3.6 * upgrade ffi to 1.0.0. * nullsafety. ## 0.3.5 * downgrade ffi to 0.1.3. ## 0.3.4 * upgrade ffi to 1.0.0. ## 0.3.3 * remove `JSInvokable.call`. * fix crash when throw error. * add reference count and leak detection. ## 0.3.2 * fix Promise reject cannot get Exception string. * wrap JSError. ## 0.3.1 * code clean up. * fix isolate wrap error. ## 0.3.0 * breakdown change to remove `channel`. * convert dart function to js. ## 0.2.7 * fix error in ios build. ## 0.2.6 * fix stack overflow in jsToCString. ## 0.2.5 * remove dart object when jsfree. ## 0.2.4 * wrap dart object to js. * fix stack overflow when use jsCall nesting. ## 0.2.3 * fix compiler error in windows release. ## 0.2.2 * add option to change max stack size. ## 0.2.1 * code cleanup. ## 0.2.0 * breakdown change with new constructor. * fix make release in ios. * fix crash in wrapping js Promise. ## 0.1.4 * fix crash on android x86. ## 0.1.3 * fix randomly crash by stack overflow. ## 0.1.2 * fix qjs memory leak. ## 0.1.1 * run on isolate. ## 0.1.0 * refactor with ffi. ## 0.0.6 * remove handler when destroy. ## 0.0.5 * add js module. ## 0.0.4 * remove C++ std limitation for linux and android. ## 0.0.3 * fix js memory leak. ## 0.0.2 * update example. ## 0.0.1 * initial publish. ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 https://github.com/czy0729 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README-CN.md ================================================ # flutter_qjs ![Pub](https://img.shields.io/pub/v/flutter_qjs.svg) ![Test](https://github.com/ekibun/flutter_qjs/workflows/Test/badge.svg) [English](README.md) | [中文](README-CN.md) 一个为flutter开发的 `quickjs` 引擎。插件基于 `dart:ffi`,支持除Web以外的所有平台! ## 基本使用 首先,创建 `FlutterQjs` 对象。调用 `dispatch` 建立事件循环: ```dart final engine = FlutterQjs( stackSize: 1024 * 1024, // change stack size here. ); engine.dispatch(); ``` 使用 `evaluate` 方法运行js脚本,方法同步执行,使用 `await` 来获得 `Promise` 结果: ```dart try { print(engine.evaluate(code ?? '')); } catch (e) { print(e.toString()); } ``` 使用 `close` 方法销毁 quickjs 实例,其在再次调用 `evaluate` 时将会重建。当不再需要 `FlutterQjs` 对象时,关闭 `port` 参数来结束事件循环。**在 v0.3.3 后增加了引用检查,可能会抛出异常**。 ```dart try { engine.port.close(); // stop dispatch loop engine.close(); // close engine } on JSError catch(e) { print(e); // catch reference leak exception } engine = null; ``` dart 与 js 间数据以如下规则转换: | dart | js | | ---------------------------- | ---------- | | Bool | boolean | | Int | number | | Double | number | | String | string | | Uint8List | ArrayBuffer| | List | Array | | Map | Object | | Function(arg1, arg2, ..., {thisVal})
JSInvokable.invoke(\[arg1, arg2, ...\], thisVal) | function.call(thisVal, arg1, arg2, ...) | | Future | Promise | | JSError | Error | | Object | DartObject | ## 使用模块 插件支持 ES6 模块方法 `import`。使用 `moduleHandler` 来处理模块请求: ```dart final engine = FlutterQjs( moduleHandler: (String module) { if(module == "hello") return "export default (name) => `hello \${name}!`;"; throw Exception("Module Not found"); }, ); ``` 在JavaScript中,`import` 方法用以获取模块: ```javascript import("hello").then(({default: greet}) => greet("world")); ``` **注:** 模块将只被编译一次. 调用 `FlutterQjs.close` 再 `evaluate` 来重置模块缓存。 若要使用异步方法来处理模块请求,请参见 [在 isolate 中运行](#在-isolate-中运行)。 ## 在 isolate 中运行 创建 `IsolateQjs` 对象,设置 `moduleHandler` 来处理模块请求。 现在可以使用异步函数来获得模块字符串,如 `rootBundle.loadString`: ```dart final engine = IsolateQjs( moduleHandler: (String module) async { return await rootBundle.loadString( "js/" + module.replaceFirst(new RegExp(r".js$"), "") + ".js"); }, ); // not need engine.dispatch(); ``` 与在主线程运行一样,使用 `evaluate` 方法运行js脚本。在isolate中,所有结果都将异步返回,使用 `await` 来获取结果: ```dart try { print(await engine.evaluate(code ?? '')); } catch (e) { print(e.toString()); } ``` 使用 `close` 方法销毁 isolate 线程,其在再次调用 `evaluate` 时将会重建。 ## 调用 Dart 函数 Js脚本返回函数将被转换为 `JSInvokable`。 **它不能像 `Function` 一样调用,请使用 `invoke` 方法来调用**: ```dart (func as JSInvokable).invoke([arg1, arg2], thisVal); ``` **注:** 返回 `JSInvokable` 可能造成引用泄漏,需要手动调用 `free` 来释放引用: ```dart (obj as JSRef).free(); // or JSRef.freeRecursive(obj); ``` 传递给 `JSInvokable` 的参数将自动释放. 使用 `dup` 来保持引用: ```dart (obj as JSRef).dup(); // or JSRef.dupRecursive(obj); ``` 自 v0.3.0 起,dart 函数可以作为参数传递给 `JSInvokable`,且 `channel` 函数不再默认内置。可以使用如下方法将 dart 函数赋值给全局,例如,使用 `Dio` 来为 qjs 提供 http 支持: ```dart final setToGlobalObject = await engine.evaluate("(key, val) => { this[key] = val; }"); await setToGlobalObject.invoke(["http", (String url) { return Dio().get(url).then((response) => response.data); }]); setToGlobalObject.free(); ``` 在 isolate 模式下,只有顶层和静态函数能作为参数传给 `JSInvokable`,函数将在 isolate 线程中调用。 使用 `IsolateFunction` 来传递局部函数(将在主线程中调用): ```dart await setToGlobalObject.invoke([ "http", IsolateFunction((String url) { return Dio().get(url).then((response) => response.data); }), ]); ``` ================================================ FILE: README.md ================================================ # flutter_qjs ![Pub](https://img.shields.io/pub/v/flutter_qjs.svg) ![Test](https://github.com/ekibun/flutter_qjs/workflows/Test/badge.svg) [English](README.md) | [中文](README-CN.md) This plugin is a simple js engine for flutter using the `quickjs` project with `dart:ffi`. Plugin currently supports all the platforms except web! ## Getting Started ### Basic usage Firstly, create a `FlutterQjs` object, then call `dispatch` to establish event loop: ```dart final engine = FlutterQjs( stackSize: 1024 * 1024, // change stack size here. ); engine.dispatch(); ``` Use `evaluate` method to run js script, it runs synchronously, you can use await to resolve `Promise`: ```dart try { print(engine.evaluate(code ?? '')); } catch (e) { print(e.toString()); } ``` Method `close` can destroy quickjs runtime that can be recreated again if you call `evaluate`. Parameter `port` should be close to stop `dispatch` loop when you do not need it. **Reference leak exception will be thrown since v0.3.3** ```dart try { engine.port.close(); // stop dispatch loop engine.close(); // close engine } on JSError catch(e) { print(e); // catch reference leak exception } engine = null; ``` Data conversion between dart and js are implemented as follow: | dart | js | | ---------------------------- | ---------- | | Bool | boolean | | Int | number | | Double | number | | String | string | | Uint8List | ArrayBuffer| | List | Array | | Map | Object | | Function(arg1, arg2, ..., {thisVal})
JSInvokable.invoke(\[arg1, arg2, ...\], thisVal) | function.call(thisVal, arg1, arg2, ...) | | Future | Promise | | JSError | Error | | Object | DartObject | ## Use Modules ES6 module with `import` function is supported and can be managed in dart with `moduleHandler`: ```dart final engine = FlutterQjs( moduleHandler: (String module) { if(module == "hello") return "export default (name) => `hello \${name}!`;"; throw Exception("Module Not found"); }, ); ``` then in JavaScript, `import` function is used to get modules: ```javascript import("hello").then(({default: greet}) => greet("world")); ``` **notice:** Module handler should be called only once for each module name. To reset the module cache, call `FlutterQjs.close` then `evaluate` again. To use async function in module handler, try [run on isolate thread](#Run-on-Isolate-Thread) ## Run on Isolate Thread Create a `IsolateQjs` object, pass handlers to resolving modules. Async function such as `rootBundle.loadString` can be used now to get modules: ```dart final engine = IsolateQjs( moduleHandler: (String module) async { return await rootBundle.loadString( "js/" + module.replaceFirst(new RegExp(r".js$"), "") + ".js"); }, ); // not need engine.dispatch(); ``` Same as run on main thread, use `evaluate` to run js script. In isolate, everything returns asynchronously, use `await` to get the result: ```dart try { print(await engine.evaluate(code ?? '')); } catch (e) { print(e.toString()); } ``` Method `close` can destroy isolate thread that will be recreated again if you call `evaluate`. ## Use Dart Function (Breaking change in v0.3.0) Js script returning function will be converted to `JSInvokable`. **It does not extend `Function`, use `invoke` method to invoke it**: ```dart (func as JSInvokable).invoke([arg1, arg2], thisVal); ``` **notice:** evaluation returning `JSInvokable` may cause reference leak. You should manually call `free` to release JS reference. ```dart (obj as JSRef).free(); // or JSRef.freeRecursive(obj); ``` Arguments passed into `JSInvokable` will be freed automatically. Use `dup` to keep the reference. ```dart (obj as JSRef).dup(); // or JSRef.dupRecursive(obj); ``` Since v0.3.0, you can pass a function to `JSInvokable` arguments, and `channel` function is no longer included by default. You can use js function to set dart object globally. For example, use `Dio` to implement http in qjs: ```dart final setToGlobalObject = await engine.evaluate("(key, val) => { this[key] = val; }"); await setToGlobalObject.invoke(["http", (String url) { return Dio().get(url).then((response) => response.data); }]); setToGlobalObject.free(); ``` In isolate, top level function passed in `JSInvokable` will be invoked in isolate thread. Use `IsolateFunction` to pass a instant function: ```dart await setToGlobalObject.invoke([ "http", IsolateFunction((String url) { return Dio().get(url).then((response) => response.data); }), ]); ``` ================================================ FILE: android/.classpath ================================================ ================================================ FILE: android/.gitignore ================================================ *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .DS_Store /build /captures /.cxx ================================================ FILE: android/.project ================================================ flutter_qjs Project android created by Buildship. org.eclipse.jdt.core.javabuilder org.eclipse.buildship.core.gradleprojectbuilder org.eclipse.jdt.core.javanature org.eclipse.buildship.core.gradleprojectnature ================================================ FILE: android/.settings/org.eclipse.buildship.core.prefs ================================================ arguments= auto.sync=false build.scans.enabled=false connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(6.3)) connection.project.dir= eclipse.preferences.version=1 gradle.user.home= java.home=C\:/Program Files/JetBrains/IntelliJ IDEA Community Edition 2019.3.2/jbr jvm.arguments= offline.mode=false override.workspace.settings=true show.console.view=true show.executions.view=true ================================================ FILE: android/build.gradle ================================================ group 'soko.ekibun.flutter_qjs' version '1.0-SNAPSHOT' buildscript { ext.kotlin_version = '1.3.50' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.5.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } rootProject.allprojects { repositories { google() jcenter() maven { url 'https://jitpack.io' } } } apply plugin: 'com.android.library' apply plugin: 'kotlin-android' android { compileSdkVersion 28 sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { minSdkVersion 16 } lintOptions { disable 'InvalidPackage' } kotlinOptions { jvmTarget = "1.8" } externalNativeBuild { cmake { path "src/main/cxx/CMakeLists.txt" version "3.10.2" } } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" // implementation 'com.github.abner.oasis-jsbridge-android:oasis-jsbridge-quickjs:0.11.0' } ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip ================================================ FILE: android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx1536M android.enableR8=true android.useAndroidX=true android.enableJetifier=true ================================================ FILE: android/settings.gradle ================================================ rootProject.name = 'flutter_qjs' ================================================ FILE: android/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/src/main/cxx/CMakeLists.txt ================================================ # For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html # Sets the minimum version of CMake required to build the native library. cmake_minimum_required(VERSION 3.4.1) set(JNI_LIB_NAME qjs) # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. include("${CMAKE_CURRENT_SOURCE_DIR}/../../../../cxx/quickjs.cmake") add_library( # Sets the name of the library. ${JNI_LIB_NAME} # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ${CXX_LIB_DIR}/ffi.cpp ) # Searches for a specified prebuilt library and stores the path as a # variable. Because CMake includes system libraries in the search path by # default, you only need to specify the name of the public NDK library # you want to add. CMake verifies that the library exists before # completing its build. find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log ) # Specifies libraries CMake should link to your target library. You # can link multiple libraries, such as libraries you define in this # build script, prebuilt third-party libraries, or system libraries. target_link_libraries( # Specifies the target library. ${JNI_LIB_NAME} quickjs # Links the target library to the log library # included in the NDK. ${log-lib} ) ================================================ FILE: android/src/main/kotlin/soko/ekibun/flutter_qjs/FlutterQjsPlugin.kt ================================================ package soko.ekibun.flutter_qjs import android.os.Handler import io.flutter.embedding.engine.plugins.FlutterPlugin /** FlutterQjsPlugin */ class FlutterQjsPlugin: FlutterPlugin { /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it /// when the Flutter Engine is detached from the Activity override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { } } ================================================ FILE: coverage/lcov.info ================================================ SF:lib\src\wrapper.dart DA:10,3 DA:11,6 DA:14,3 DA:18,3 DA:22,3 DA:29,3 DA:30,6 DA:31,6 DA:35,3 DA:38,6 DA:39,3 DA:42,3 DA:48,3 DA:49,6 DA:50,6 DA:51,6 DA:52,3 DA:56,3 DA:58,6 DA:59,3 DA:60,3 DA:61,3 DA:62,6 DA:63,3 DA:64,6 DA:65,6 DA:68,12 DA:69,3 DA:70,9 DA:72,12 DA:73,6 DA:74,3 DA:75,3 DA:76,3 DA:77,3 DA:78,3 DA:79,3 DA:80,3 DA:81,3 DA:82,3 DA:83,6 DA:84,6 DA:85,3 DA:86,6 DA:87,6 DA:88,3 DA:89,3 DA:93,3 DA:94,9 DA:95,9 DA:96,9 DA:97,6 DA:98,3 DA:99,0 DA:100,0 DA:101,0 DA:102,0 DA:103,0 DA:106,3 DA:107,9 DA:109,3 DA:110,6 DA:111,3 DA:112,9 DA:113,6 DA:117,3 DA:118,6 DA:119,3 DA:120,6 DA:121,9 DA:126,3 DA:128,15 DA:129,3 DA:130,6 DA:133,6 DA:135,3 DA:136,6 DA:137,3 DA:143,3 DA:145,3 DA:146,6 DA:147,9 DA:148,6 DA:151,3 DA:152,9 DA:153,3 DA:154,6 DA:155,3 DA:156,3 DA:157,3 DA:158,6 DA:159,9 DA:161,3 DA:162,6 DA:163,3 DA:166,6 DA:168,3 DA:169,6 DA:170,0 DA:172,6 DA:173,3 DA:174,3 DA:176,9 DA:177,3 DA:178,9 DA:179,3 DA:180,3 DA:182,12 DA:183,3 DA:184,3 DA:185,9 DA:186,3 DA:188,3 DA:189,3 DA:190,3 DA:191,9 DA:192,3 DA:193,6 DA:194,3 DA:195,3 DA:196,6 DA:198,3 DA:199,3 DA:200,6 DA:203,3 DA:204,3 DA:205,9 DA:206,3 DA:207,0 DA:208,3 DA:209,9 DA:210,3 DA:211,6 DA:212,3 DA:213,3 DA:214,6 DA:215,3 DA:216,6 DA:217,3 DA:223,12 DA:224,0 DA:225,0 DA:228,3 DA:229,3 DA:230,3 DA:231,3 DA:232,6 DA:233,9 DA:234,6 DA:235,6 DA:236,6 DA:237,3 DA:238,3 DA:239,3 DA:240,6 DA:242,9 DA:243,3 LF:157 LH:148 end_of_record SF:lib\src\engine.dart DA:39,3 DA:47,3 DA:48,3 DA:49,6 DA:52,3 DA:53,3 DA:54,9 DA:55,3 DA:56,6 DA:57,6 DA:59,3 DA:60,15 DA:64,3 DA:66,3 DA:68,3 DA:70,3 DA:72,6 DA:74,3 DA:75,3 DA:76,6 DA:77,6 DA:78,3 DA:79,6 DA:80,3 DA:82,3 DA:83,3 DA:84,3 DA:85,3 DA:86,6 DA:88,0 DA:90,3 DA:91,3 DA:92,3 DA:93,9 DA:94,3 DA:96,0 DA:98,0 DA:99,0 DA:100,0 DA:102,0 DA:103,0 DA:104,0 DA:106,0 DA:107,0 DA:108,0 DA:109,0 DA:110,0 DA:111,0 DA:115,6 DA:116,3 DA:117,3 DA:118,3 DA:119,9 DA:120,3 DA:121,6 DA:125,3 DA:126,3 DA:127,3 DA:128,3 DA:129,3 DA:130,6 DA:132,3 DA:134,3 DA:135,3 DA:136,3 DA:140,3 DA:141,3 DA:142,3 DA:145,6 DA:146,3 DA:147,3 DA:154,3 DA:155,9 DA:156,3 DA:161,3 DA:166,3 DA:167,3 DA:168,3 DA:174,9 DA:175,3 DA:176,3 DA:178,3 DA:179,3 LF:83 LH:69 end_of_record SF:lib\src\isolate.dart DA:11,9 DA:20,3 DA:21,3 DA:22,6 DA:23,6 DA:24,0 DA:25,6 DA:26,3 DA:27,3 DA:28,3 DA:29,9 DA:30,9 DA:34,3 DA:35,3 DA:36,3 DA:37,6 DA:38,9 DA:39,6 DA:43,3 DA:44,3 DA:45,6 DA:46,9 DA:47,3 DA:48,6 DA:50,3 DA:51,9 DA:52,3 DA:53,9 DA:56,3 DA:57,3 DA:63,3 DA:64,3 DA:65,6 DA:66,3 DA:67,3 DA:68,3 DA:69,9 DA:70,9 DA:74,3 DA:75,6 DA:76,3 DA:79,3 DA:80,3 DA:81,3 DA:82,6 DA:83,3 DA:84,9 DA:85,9 DA:86,3 DA:87,6 DA:88,9 DA:90,6 DA:93,3 DA:95,3 DA:96,3 DA:97,6 DA:98,9 DA:99,6 DA:106,3 DA:107,3 DA:108,3 DA:109,6 DA:110,3 DA:111,3 DA:112,3 DA:113,3 DA:114,3 DA:115,6 DA:117,3 DA:120,3 DA:122,9 DA:123,6 DA:126,3 DA:128,18 DA:129,3 DA:130,3 DA:131,9 DA:132,3 DA:133,3 DA:137,6 DA:139,3 DA:141,3 DA:142,3 DA:143,6 DA:144,3 DA:145,3 DA:146,3 DA:149,3 DA:151,6 DA:152,3 DA:153,3 DA:157,6 DA:160,0 DA:161,0 DA:165,6 DA:192,3 DA:200,3 DA:201,3 DA:202,3 DA:203,3 DA:205,3 DA:206,3 DA:207,3 DA:208,3 DA:209,3 DA:213,3 DA:214,6 DA:215,6 DA:216,3 DA:219,3 DA:220,3 DA:222,6 DA:223,3 DA:224,6 DA:226,0 DA:229,0 DA:232,3 DA:233,6 DA:235,18 DA:237,0 DA:241,0 DA:242,0 DA:243,0 DA:244,0 DA:246,6 DA:250,3 DA:251,3 DA:252,3 DA:254,6 DA:255,3 DA:256,6 DA:258,3 DA:260,6 DA:261,3 DA:262,3 DA:263,0 DA:264,3 DA:270,3 DA:275,3 DA:276,3 DA:277,6 DA:278,6 DA:283,3 DA:285,6 DA:286,3 DA:287,6 DA:288,0 DA:289,3 LF:148 LH:136 end_of_record SF:lib\src\object.dart DA:14,3 DA:15,3 DA:17,3 DA:18,3 DA:25,3 DA:27,3 DA:31,15 DA:33,9 DA:34,3 DA:35,3 DA:39,0 DA:41,0 DA:44,0 DA:53,3 DA:54,3 DA:55,3 DA:56,6 DA:57,15 DA:60,3 DA:61,18 DA:65,0 DA:67,0 DA:68,0 DA:71,3 DA:73,3 DA:74,3 DA:75,3 DA:76,3 DA:78,15 DA:79,6 DA:87,3 DA:88,3 DA:89,0 DA:90,0 DA:92,6 DA:93,9 DA:97,0 DA:99,0 DA:102,3 DA:103,3 DA:104,9 DA:108,3 DA:110,3 DA:111,3 DA:112,3 DA:124,3 DA:125,3 DA:126,6 DA:127,9 DA:128,9 DA:131,3 DA:133,3 DA:134,3 DA:135,3 DA:136,3 DA:138,6 DA:139,9 DA:140,3 DA:143,3 DA:145,6 DA:146,9 DA:152,6 DA:154,3 DA:156,3 DA:157,3 DA:158,9 DA:160,0 DA:161,0 DA:163,3 DA:164,3 DA:168,3 DA:169,3 DA:170,3 DA:172,0 DA:174,3 DA:175,6 DA:177,3 DA:178,3 DA:179,3 DA:180,3 DA:181,6 DA:182,3 DA:187,3 DA:189,6 DA:198,3 DA:200,3 DA:201,6 DA:203,9 DA:206,6 DA:208,3 DA:210,3 DA:211,6 DA:212,3 DA:214,6 DA:215,12 DA:217,0 DA:218,12 DA:219,3 DA:221,0 DA:223,0 DA:229,3 DA:232,3 DA:233,3 DA:234,3 DA:235,3 DA:236,6 DA:237,3 DA:239,3 DA:241,6 DA:242,6 DA:243,0 DA:244,3 DA:247,3 DA:248,6 DA:249,6 DA:250,3 DA:253,3 DA:255,3 DA:256,6 DA:258,3 DA:259,6 DA:260,9 DA:262,3 DA:263,0 DA:266,6 DA:267,6 DA:268,6 DA:272,3 DA:273,3 DA:274,3 DA:275,6 DA:281,3 DA:282,3 DA:283,3 DA:284,3 DA:285,3 DA:290,3 DA:292,3 DA:293,6 DA:294,6 DA:300,3 DA:302,3 DA:305,3 DA:307,3 DA:310,0 DA:312,0 LF:146 LH:126 end_of_record SF:lib\src\ffi.dart DA:14,3 DA:16,3 DA:17,3 DA:25,3 DA:26,6 DA:29,3 DA:30,6 DA:31,9 DA:36,3 DA:37,9 DA:40,3 DA:41,9 DA:44,3 DA:51,3 DA:52,3 DA:53,3 DA:54,12 DA:56,3 DA:57,3 DA:58,15 DA:60,3 DA:61,3 DA:116,15 DA:117,3 DA:118,3 DA:119,0 DA:120,0 DA:121,0 DA:122,0 DA:123,0 DA:124,0 DA:125,0 DA:126,0 DA:132,0 DA:133,0 DA:142,0 DA:143,0 DA:147,9 DA:148,3 DA:160,9 DA:161,3 DA:174,3 DA:176,6 DA:178,9 DA:180,9 DA:182,3 DA:183,6 DA:187,9 DA:189,3 DA:194,3 DA:195,3 DA:196,6 DA:197,12 DA:200,3 DA:205,6 DA:206,9 DA:214,0 DA:215,0 DA:227,9 DA:228,3 DA:239,9 DA:240,3 DA:247,3 DA:250,3 DA:251,6 DA:254,12 DA:256,3 DA:257,12 DA:259,6 DA:260,6 DA:261,6 DA:262,12 DA:263,3 DA:264,18 DA:265,3 DA:268,6 DA:269,6 DA:270,3 DA:271,3 DA:279,9 DA:280,3 DA:291,9 DA:292,3 DA:299,3 DA:300,6 DA:301,6 DA:302,6 DA:303,0 DA:304,6 DA:311,9 DA:312,3 DA:322,9 DA:323,3 DA:337,9 DA:338,3 DA:349,3 DA:355,3 DA:356,3 DA:357,6 DA:360,3 DA:364,3 DA:365,3 DA:366,21 DA:373,9 DA:374,3 DA:384,9 DA:385,3 DA:395,9 DA:396,3 DA:407,9 DA:408,3 DA:420,9 DA:421,3 DA:433,9 DA:434,3 DA:446,9 DA:447,3 DA:455,3 DA:459,3 DA:460,6 DA:461,3 DA:470,0 DA:471,0 DA:483,9 DA:484,3 DA:494,9 DA:495,3 DA:507,9 DA:508,3 DA:517,3 DA:522,6 DA:530,0 DA:531,0 DA:540,0 DA:545,0 DA:552,9 DA:553,3 DA:565,0 DA:566,0 DA:578,9 DA:579,3 DA:591,9 DA:592,3 DA:604,9 DA:605,3 DA:617,9 DA:618,3 DA:630,9 DA:631,3 DA:639,3 DA:643,6 DA:644,6 DA:645,3 DA:646,6 DA:654,9 DA:655,3 DA:663,3 DA:667,3 DA:668,6 DA:672,3 DA:681,9 DA:682,3 DA:695,9 DA:696,3 DA:709,9 DA:710,3 DA:723,9 DA:724,3 DA:736,9 DA:737,3 DA:749,9 DA:750,3 DA:762,9 DA:763,3 DA:774,9 DA:775,3 DA:788,9 DA:789,3 DA:806,9 DA:807,3 DA:822,9 DA:823,3 DA:835,9 DA:836,3 DA:848,9 DA:849,3 DA:865,9 DA:866,3 DA:881,9 DA:882,3 DA:891,9 DA:892,3 DA:895,12 DA:902,9 DA:903,3 DA:920,9 DA:921,3 DA:932,3 DA:939,15 DA:940,3 DA:941,9 DA:942,3 DA:943,6 DA:945,6 DA:947,9 DA:948,3 DA:949,3 DA:950,21 DA:957,9 DA:958,3 DA:968,9 DA:969,3 DA:979,9 DA:980,3 DA:991,9 DA:992,3 DA:1004,9 DA:1005,3 LF:218 LH:195 end_of_record ================================================ FILE: cxx/ffi.cpp ================================================ /* * @Description: * @Author: ekibun * @Date: 2020-09-06 18:32:45 * @LastEditors: ekibun * @LastEditTime: 2020-12-02 11:11:42 */ #include "ffi.h" #include #include #include extern "C" { DLLEXPORT JSValue *jsThrow(JSContext *ctx, JSValue *obj) { return new JSValue(JS_Throw(ctx, JS_DupValue(ctx, *obj))); } DLLEXPORT JSValue *jsEXCEPTION() { return new JSValue(JS_EXCEPTION); } DLLEXPORT JSValue *jsUNDEFINED() { return new JSValue(JS_UNDEFINED); } DLLEXPORT JSValue *jsNULL() { return new JSValue(JS_NULL); } struct RuntimeOpaque { JSChannel * channel; int64_t timeout; int64_t start; }; JSModuleDef *js_module_loader( JSContext *ctx, const char *module_name, void *opaque) { const char *str = (char *)((RuntimeOpaque *)opaque)->channel(ctx, JSChannelType_MODULE, (void *)module_name); if (str == 0) return NULL; JSValue func_val = JS_Eval(ctx, str, strlen(str), module_name, JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY); if (JS_IsException(func_val)) return NULL; /* the module is already referenced, so we must free it */ JSModuleDef *m = (JSModuleDef *)JS_VALUE_GET_PTR(func_val); JS_FreeValue(ctx, func_val); return m; } JSValue js_channel(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *func_data) { JSRuntime *rt = JS_GetRuntime(ctx); RuntimeOpaque *opaque = (RuntimeOpaque *)JS_GetRuntimeOpaque(rt); void *data[4]; data[0] = &this_val; data[1] = &argc; data[2] = argv; data[3] = func_data; return *(JSValue *)opaque->channel(ctx, JSChannelType_METHON, data); } void js_promise_rejection_tracker(JSContext *ctx, JSValueConst promise, JSValueConst reason, JS_BOOL is_handled, void *opaque) { if (is_handled) return; ((RuntimeOpaque *)opaque)->channel(ctx, JSChannelType_PROMISE_TRACK, &reason); } int js_interrupt_handler(JSRuntime * rt, void * opaque) { RuntimeOpaque *op = (RuntimeOpaque *)opaque; if(op->timeout && op->start && (clock() - op->start) > op->timeout * CLOCKS_PER_SEC / 1000) { op->start = 0; return 1; } return 0; } DLLEXPORT JSRuntime *jsNewRuntime(JSChannel channel, int64_t timeout) { JSRuntime *rt = JS_NewRuntime(); RuntimeOpaque *opaque = new RuntimeOpaque({channel, timeout, 0}); JS_SetRuntimeOpaque(rt, opaque); JS_SetHostPromiseRejectionTracker(rt, js_promise_rejection_tracker, opaque); JS_SetModuleLoaderFunc(rt, nullptr, js_module_loader, opaque); JS_SetInterruptHandler(rt, js_interrupt_handler, opaque); return rt; } DLLEXPORT uint32_t jsNewClass(JSContext *ctx, const char *name) { JSClassID QJSClassId = 0; JS_NewClassID(&QJSClassId); JSRuntime *rt = JS_GetRuntime(ctx); if (!JS_IsRegisteredClass(rt, QJSClassId)) { JSClassDef def{ name, // destructor [](JSRuntime *rt, JSValue obj) noexcept { JSClassID classid = JS_GetClassID(obj); void *opaque = JS_GetOpaque(obj, classid); RuntimeOpaque *runtimeOpaque = (RuntimeOpaque *)JS_GetRuntimeOpaque(rt); if (runtimeOpaque == nullptr) return; runtimeOpaque->channel((JSContext *)rt, JSChannelType_FREE_OBJECT, opaque); }}; int e = JS_NewClass(rt, QJSClassId, &def); if (e < 0) { JS_ThrowInternalError(ctx, "Cant register class %s", name); return 0; } } return QJSClassId; } DLLEXPORT void *jsGetObjectOpaque(JSValue *obj, uint32_t classid) { return JS_GetOpaque(*obj, classid); } DLLEXPORT JSValue *jsNewObjectClass(JSContext *ctx, uint32_t QJSClassId, void *opaque) { auto jsobj = new JSValue(JS_NewObjectClass(ctx, QJSClassId)); if (JS_IsException(*jsobj)) return jsobj; JS_SetOpaque(*jsobj, opaque); return jsobj; } DLLEXPORT void jsSetMaxStackSize(JSRuntime *rt, size_t stack_size) { JS_SetMaxStackSize(rt, stack_size); } DLLEXPORT void jsSetMemoryLimit(JSRuntime *rt, size_t limit) { JS_SetMemoryLimit(rt, limit); } DLLEXPORT void jsFreeRuntime(JSRuntime *rt) { RuntimeOpaque *opauqe = (RuntimeOpaque *)JS_GetRuntimeOpaque(rt); if (opauqe) delete opauqe; JS_SetRuntimeOpaque(rt, nullptr); JS_FreeRuntime(rt); } DLLEXPORT JSValue *jsNewCFunction(JSContext *ctx, JSValue *funcData) { return new JSValue(JS_NewCFunctionData(ctx, js_channel, 0, 0, 1, funcData)); } DLLEXPORT JSContext *jsNewContext(JSRuntime *rt) { JS_UpdateStackTop(rt); JSContext *ctx = JS_NewContext(rt); return ctx; } DLLEXPORT void jsFreeContext(JSContext *ctx) { JS_FreeContext(ctx); } DLLEXPORT JSRuntime *jsGetRuntime(JSContext *ctx) { return JS_GetRuntime(ctx); } void js_begin_call(JSRuntime *rt) { JS_UpdateStackTop(rt); RuntimeOpaque * opaque = (RuntimeOpaque *)JS_GetRuntimeOpaque(rt); if(opaque) opaque->start = clock(); } DLLEXPORT JSValue *jsEval(JSContext *ctx, const char *input, size_t input_len, const char *filename, int32_t eval_flags) { JSRuntime *rt = JS_GetRuntime(ctx); js_begin_call(rt); JSValue *ret = new JSValue(JS_Eval(ctx, input, input_len, filename, eval_flags)); return ret; } DLLEXPORT int32_t jsValueGetTag(JSValue *val) { return JS_VALUE_GET_TAG(*val); } DLLEXPORT void *jsValueGetPtr(JSValue *val) { return JS_VALUE_GET_PTR(*val); } DLLEXPORT int32_t jsTagIsFloat64(int32_t tag) { return JS_TAG_IS_FLOAT64(tag); } DLLEXPORT JSValue *jsNewBool(JSContext *ctx, int32_t val) { return new JSValue(JS_NewBool(ctx, val)); } DLLEXPORT JSValue *jsNewInt64(JSContext *ctx, int64_t val) { return new JSValue(JS_NewInt64(ctx, val)); } DLLEXPORT JSValue *jsNewFloat64(JSContext *ctx, double val) { return new JSValue(JS_NewFloat64(ctx, val)); } DLLEXPORT JSValue *jsNewString(JSContext *ctx, const char *str) { return new JSValue(JS_NewString(ctx, str)); } DLLEXPORT JSValue *jsNewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len) { return new JSValue(JS_NewArrayBufferCopy(ctx, buf, len)); } DLLEXPORT JSValue *jsNewArray(JSContext *ctx) { return new JSValue(JS_NewArray(ctx)); } DLLEXPORT JSValue *jsNewObject(JSContext *ctx) { return new JSValue(JS_NewObject(ctx)); } DLLEXPORT void jsFreeValue(JSContext *ctx, JSValue *v, int32_t free) { JS_FreeValue(ctx, *v); if (free) delete v; } DLLEXPORT void jsFreeValueRT(JSRuntime *rt, JSValue *v, int32_t free) { JS_FreeValueRT(rt, *v); if (free) delete v; } DLLEXPORT JSValue *jsDupValue(JSContext *ctx, JSValueConst *v) { return new JSValue(JS_DupValue(ctx, *v)); } DLLEXPORT JSValue *jsDupValueRT(JSRuntime *rt, JSValue *v) { return new JSValue(JS_DupValueRT(rt, *v)); } DLLEXPORT int32_t jsToBool(JSContext *ctx, JSValueConst *val) { return JS_ToBool(ctx, *val); } DLLEXPORT int64_t jsToInt64(JSContext *ctx, JSValueConst *val) { int64_t p; JS_ToInt64(ctx, &p, *val); return p; } DLLEXPORT double jsToFloat64(JSContext *ctx, JSValueConst *val) { double p; JS_ToFloat64(ctx, &p, *val); return p; } DLLEXPORT const char *jsToCString(JSContext *ctx, JSValueConst *val) { JSRuntime *rt = JS_GetRuntime(ctx); js_begin_call(rt); const char *ret = JS_ToCString(ctx, *val); return ret; } DLLEXPORT void jsFreeCString(JSContext *ctx, const char *ptr) { return JS_FreeCString(ctx, ptr); } DLLEXPORT uint8_t *jsGetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst *obj) { return JS_GetArrayBuffer(ctx, psize, *obj); } DLLEXPORT int32_t jsIsFunction(JSContext *ctx, JSValueConst *val) { return JS_IsFunction(ctx, *val); } DLLEXPORT int32_t jsIsPromise(JSContext *ctx, JSValueConst *val) { return JS_IsPromise(ctx, *val); } DLLEXPORT int32_t jsIsArray(JSContext *ctx, JSValueConst *val) { return JS_IsArray(ctx, *val); } DLLEXPORT int32_t jsIsError(JSContext *ctx, JSValueConst *val) { return JS_IsError(ctx, *val); } DLLEXPORT JSValue *jsNewError(JSContext *ctx) { return new JSValue(JS_NewError(ctx)); } DLLEXPORT JSValue *jsGetProperty(JSContext *ctx, JSValueConst *this_obj, JSAtom prop) { return new JSValue(JS_GetProperty(ctx, *this_obj, prop)); } DLLEXPORT int32_t jsDefinePropertyValue(JSContext *ctx, JSValueConst *this_obj, JSAtom prop, JSValue *val, int32_t flags) { return JS_DefinePropertyValue(ctx, *this_obj, prop, *val, flags); } DLLEXPORT void jsFreeAtom(JSContext *ctx, JSAtom v) { JS_FreeAtom(ctx, v); } DLLEXPORT JSAtom jsValueToAtom(JSContext *ctx, JSValueConst *val) { return JS_ValueToAtom(ctx, *val); } DLLEXPORT JSValue *jsAtomToValue(JSContext *ctx, JSAtom val) { return new JSValue(JS_AtomToValue(ctx, val)); } DLLEXPORT int32_t jsGetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst *obj, int32_t flags) { return JS_GetOwnPropertyNames(ctx, ptab, plen, *obj, flags); } DLLEXPORT JSAtom jsPropertyEnumGetAtom(JSPropertyEnum *ptab, int32_t i) { return ptab[i].atom; } DLLEXPORT uint32_t sizeOfJSValue() { return sizeof(JSValue); } DLLEXPORT void setJSValueList(JSValue *list, uint32_t i, JSValue *val) { list[i] = *val; } DLLEXPORT JSValue *jsCall(JSContext *ctx, JSValueConst *func_obj, JSValueConst *this_obj, int32_t argc, JSValueConst *argv) { JSRuntime *rt = JS_GetRuntime(ctx); js_begin_call(rt); JSValue *ret = new JSValue(JS_Call(ctx, *func_obj, *this_obj, argc, argv)); return ret; } DLLEXPORT int32_t jsIsException(JSValueConst *val) { return JS_IsException(*val); } DLLEXPORT JSValue *jsGetException(JSContext *ctx) { return new JSValue(JS_GetException(ctx)); } DLLEXPORT int32_t jsExecutePendingJob(JSRuntime *rt) { js_begin_call(rt); JSContext *ctx; int ret = JS_ExecutePendingJob(rt, &ctx); return ret; } DLLEXPORT JSValue *jsNewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs) { return new JSValue(JS_NewPromiseCapability(ctx, resolving_funcs)); } DLLEXPORT void jsFree(JSContext *ctx, void *ptab) { js_free(ctx, ptab); } } ================================================ FILE: cxx/ffi.h ================================================ #include "quickjs/quickjs.h" #ifdef _MSC_VER #define DLLEXPORT __declspec(dllexport) #else #define DLLEXPORT __attribute__((visibility("default"))) __attribute__((used)) #endif extern "C" { enum JSChannelType { JSChannelType_METHON = 0, JSChannelType_MODULE = 1, JSChannelType_PROMISE_TRACK = 2, JSChannelType_FREE_OBJECT = 3, }; typedef void *JSChannel(JSContext *ctx, size_t type, void *argv); DLLEXPORT JSValue *jsThrow(JSContext *ctx, JSValue *obj); DLLEXPORT JSValue *jsEXCEPTION(); DLLEXPORT JSValue *jsUNDEFINED(); DLLEXPORT JSValue *jsNULL(); DLLEXPORT JSRuntime *jsNewRuntime(JSChannel channel, int64_t timeout); DLLEXPORT uint32_t jsNewClass(JSContext *ctx, const char *name); DLLEXPORT void *jsGetObjectOpaque(JSValue *obj, uint32_t classid); DLLEXPORT JSValue *jsNewObjectClass(JSContext *ctx, uint32_t QJSClassId, void *opaque); DLLEXPORT void jsSetMaxStackSize(JSRuntime *rt, size_t stack_size); DLLEXPORT void jsSetMemoryLimit(JSRuntime *rt, size_t limit); DLLEXPORT void jsFreeRuntime(JSRuntime *rt); DLLEXPORT JSValue *jsNewCFunction(JSContext *ctx, JSValue *funcData); DLLEXPORT JSValue *jsGetGlobalObject(JSContext *ctx); DLLEXPORT JSContext *jsNewContext(JSRuntime *rt); DLLEXPORT void jsFreeContext(JSContext *ctx); DLLEXPORT JSRuntime *jsGetRuntime(JSContext *ctx); DLLEXPORT JSValue *jsEval(JSContext *ctx, const char *input, size_t input_len, const char *filename, int32_t eval_flags); DLLEXPORT int32_t jsValueGetTag(JSValue *val); DLLEXPORT void *jsValueGetPtr(JSValue *val); DLLEXPORT int32_t jsTagIsFloat64(int32_t tag); DLLEXPORT JSValue *jsNewBool(JSContext *ctx, int32_t val); DLLEXPORT JSValue *jsNewInt64(JSContext *ctx, int64_t val); DLLEXPORT JSValue *jsNewFloat64(JSContext *ctx, double val); DLLEXPORT JSValue *jsNewString(JSContext *ctx, const char *str); DLLEXPORT JSValue *jsNewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len); DLLEXPORT JSValue *jsNewArray(JSContext *ctx); DLLEXPORT JSValue *jsNewObject(JSContext *ctx); DLLEXPORT void jsFreeValue(JSContext *ctx, JSValue *v, int32_t free); DLLEXPORT void jsFreeValueRT(JSRuntime *rt, JSValue *v, int32_t free); DLLEXPORT JSValue *jsDupValue(JSContext *ctx, JSValueConst *v); DLLEXPORT JSValue *jsDupValueRT(JSRuntime *rt, JSValue *v); DLLEXPORT int32_t jsToBool(JSContext *ctx, JSValueConst *val); DLLEXPORT int64_t jsToInt64(JSContext *ctx, JSValueConst *val); DLLEXPORT double jsToFloat64(JSContext *ctx, JSValueConst *val); DLLEXPORT const char *jsToCString(JSContext *ctx, JSValueConst *val); DLLEXPORT void jsFreeCString(JSContext *ctx, const char *ptr); DLLEXPORT uint8_t *jsGetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst *obj); DLLEXPORT int32_t jsIsFunction(JSContext *ctx, JSValueConst *val); DLLEXPORT int32_t jsIsPromise(JSContext *ctx, JSValueConst *val); DLLEXPORT int32_t jsIsArray(JSContext *ctx, JSValueConst *val); DLLEXPORT int32_t jsIsError(JSContext *ctx, JSValueConst *val); DLLEXPORT JSValue *jsNewError(JSContext *ctx); DLLEXPORT JSValue *jsGetProperty(JSContext *ctx, JSValueConst *this_obj, JSAtom prop); DLLEXPORT int32_t jsDefinePropertyValue(JSContext *ctx, JSValueConst *this_obj, JSAtom prop, JSValue *val, int32_t flags); DLLEXPORT void jsFreeAtom(JSContext *ctx, JSAtom v); DLLEXPORT JSAtom jsValueToAtom(JSContext *ctx, JSValueConst *val); DLLEXPORT JSValue *jsAtomToValue(JSContext *ctx, JSAtom val); DLLEXPORT int32_t jsGetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst *obj, int32_t flags); DLLEXPORT JSAtom jsPropertyEnumGetAtom(JSPropertyEnum *ptab, int32_t i); DLLEXPORT uint32_t sizeOfJSValue(); DLLEXPORT void setJSValueList(JSValue *list, uint32_t i, JSValue *val); DLLEXPORT JSValue *jsCall(JSContext *ctx, JSValueConst *func_obj, JSValueConst *this_obj, int32_t argc, JSValueConst *argv); DLLEXPORT int32_t jsIsException(JSValueConst *val); DLLEXPORT JSValue *jsGetException(JSContext *ctx); DLLEXPORT int32_t jsExecutePendingJob(JSRuntime *rt); DLLEXPORT JSValue *jsNewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs); DLLEXPORT void jsFree(JSContext *ctx, void *ptab); } ================================================ FILE: cxx/prebuild.sh ================================================ if [ -d "./cxx/" ];then rm -r ./cxx fi mkdir ./cxx sed 's/\#include \"quickjs\/quickjs.h\"/\#include \"quickjs.h\"/g' ../cxx/ffi.h > ./cxx/ffi.h cp ../cxx/ffi.cpp ./cxx/ffi.cpp cp ../cxx/quickjs/*.h ./cxx/ cp ../cxx/quickjs/cutils.c ./cxx/ cp ../cxx/quickjs/libregexp.c ./cxx/ cp ../cxx/quickjs/libunicode.c ./cxx/ quickjs_version=$(cat ../cxx/quickjs/VERSION) sed '1i\ \#define CONFIG_VERSION \"'$quickjs_version'\"\ \#define DUMP_LEAKS 1\ ' ../cxx/quickjs/quickjs.c > ./cxx/quickjs.c ================================================ FILE: cxx/quickjs.cmake ================================================ cmake_minimum_required(VERSION 3.7 FATAL_ERROR) set(CXX_LIB_DIR ${CMAKE_CURRENT_LIST_DIR}) # quickjs set(QUICK_JS_LIB_DIR ${CXX_LIB_DIR}/quickjs) file (STRINGS "${QUICK_JS_LIB_DIR}/VERSION" QUICKJS_VERSION) add_library(quickjs STATIC ${QUICK_JS_LIB_DIR}/cutils.c ${QUICK_JS_LIB_DIR}/libregexp.c ${QUICK_JS_LIB_DIR}/libunicode.c ${QUICK_JS_LIB_DIR}/quickjs.c ) project(quickjs LANGUAGES C) target_compile_options(quickjs PRIVATE "-DCONFIG_VERSION=\"${QUICKJS_VERSION}\"") target_compile_options(quickjs PRIVATE "-DDUMP_LEAKS") if(MSVC) # https://github.com/ekibun/flutter_qjs/issues/7 target_compile_options(quickjs PRIVATE "/Oi-") endif() ================================================ FILE: example/.gitignore ================================================ # Miscellaneous *.class *.log *.pyc *.swp .DS_Store .atom/ .buildlog/ .history .svn/ # IntelliJ related *.iml *.ipr *.iws .idea/ # The .vscode folder contains launch configuration and tasks you configure in # VS Code which you may wish to be included in version control, so this line # is commented out by default. #.vscode/ # Flutter/Dart/Pub related **/doc/api/ **/ios/Flutter/.last_build_id .dart_tool/ .flutter-plugins .flutter-plugins-dependencies .packages .pub-cache/ .pub/ /build/ # Web related lib/generated_plugin_registrant.dart # Symbolication related app.*.symbols # Obfuscation related app.*.map.json ================================================ FILE: example/.metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: f3b7788f7754a51092ae1d677001767960c21910 channel: master project_type: app ================================================ FILE: example/README.md ================================================ # flutter_qjs_example Demonstrates how to use the flutter_qjs plugin. ================================================ FILE: example/analysis_options.yaml ================================================ # This file configures the analyzer, which statically analyzes Dart code to # check for errors, warnings, and lints. # # The issues identified by the analyzer are surfaced in the UI of Dart-enabled # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be # invoked from the command line by running `flutter analyze`. # The following line activates a set of recommended lints for Flutter apps, # packages, and plugins designed to encourage good coding practices. include: package:flutter_lints/flutter.yaml linter: # The lint rules applied to this project can be customized in the # section below to disable rules from the `package:flutter_lints/flutter.yaml` # included above or to enable additional rules. A list of all available lints # and their documentation is published at # https://dart-lang.github.io/linter/lints/index.html. # # Instead of disabling a lint rule for the entire project in the # section below, it can also be suppressed for a single line of code # or a specific dart file by using the `// ignore: name_of_lint` and # `// ignore_for_file: name_of_lint` syntax on the line or in the file # producing the lint. rules: # avoid_print: false # Uncomment to disable the `avoid_print` rule # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule # Additional information about this file can be found at # https://dart.dev/guides/language/analysis-options ================================================ FILE: example/android/.gitignore ================================================ gradle-wrapper.jar /.gradle /captures/ /gradlew /gradlew.bat /local.properties GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app key.properties **/*.keystore **/*.jks ================================================ FILE: example/android/app/build.gradle ================================================ def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion flutter.compileSdkVersion ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "soko.ekibun.flutter_qjs_example" minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" } ================================================ FILE: example/android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: example/android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: example/android/app/src/main/kotlin/soko/ekibun/flutter_qjs_example/MainActivity.kt ================================================ package soko.ekibun.flutter_qjs_example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { } ================================================ FILE: example/android/app/src/main/res/drawable/launch_background.xml ================================================ ================================================ FILE: example/android/app/src/main/res/drawable-v21/launch_background.xml ================================================ ================================================ FILE: example/android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: example/android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: example/android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: example/android/build.gradle ================================================ buildscript { ext.kotlin_version = '1.6.10' repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:4.1.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } task clean(type: Delete) { delete rootProject.buildDir } ================================================ FILE: example/android/gradle/wrapper/gradle-wrapper.properties ================================================ #Fri Jun 23 08:50:38 CEST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip ================================================ FILE: example/android/gradle.properties ================================================ org.gradle.jvmargs=-Xmx1536M android.useAndroidX=true android.enableJetifier=true ================================================ FILE: example/android/settings.gradle ================================================ include ':app' def localPropertiesFile = new File(rootProject.projectDir, "local.properties") def properties = new Properties() assert localPropertiesFile.exists() localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" ================================================ FILE: example/ios/.gitignore ================================================ *.mode1v3 *.mode2v3 *.moved-aside *.pbxuser *.perspectivev3 **/*sync/ .sconsign.dblite .tags* **/.vagrant/ **/DerivedData/ Icon? **/Pods/ **/.symlinks/ profile xcuserdata **/.generated/ Flutter/App.framework Flutter/Flutter.framework Flutter/Flutter.podspec Flutter/Generated.xcconfig Flutter/app.flx Flutter/app.zip Flutter/flutter_assets/ Flutter/flutter_export_environment.sh ServiceDefinitions.json Runner/GeneratedPluginRegistrant.* # Exceptions to above rules. !default.mode1v3 !default.mode2v3 !default.pbxuser !default.perspectivev3 ================================================ FILE: example/ios/Flutter/AppFrameworkInfo.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable App CFBundleIdentifier io.flutter.flutter.app CFBundleInfoDictionaryVersion 6.0 CFBundleName App CFBundlePackageType FMWK CFBundleShortVersionString 1.0 CFBundleSignature ???? CFBundleVersion 1.0 MinimumOSVersion 9.0 ================================================ FILE: example/ios/Flutter/Debug.xcconfig ================================================ #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "Generated.xcconfig" ================================================ FILE: example/ios/Flutter/Release.xcconfig ================================================ #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "Generated.xcconfig" ================================================ FILE: example/ios/Podfile ================================================ # Uncomment this line to define a global platform for your project # platform :ios, '9.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' project 'Runner', { 'Debug' => :debug, 'Profile' => :release, 'Release' => :release, } def flutter_root generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) unless File.exist?(generated_xcode_build_settings_path) raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" end File.foreach(generated_xcode_build_settings_path) do |line| matches = line.match(/FLUTTER_ROOT\=(.*)/) return matches[1].strip if matches end raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" end require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) flutter_ios_podfile_setup target 'Runner' do use_frameworks! use_modular_headers! flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) end end ================================================ FILE: example/ios/Runner/AppDelegate.swift ================================================ import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) return super.application(application, didFinishLaunchingWithOptions: launchOptions) } } ================================================ FILE: example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "20x20", "idiom" : "iphone", "filename" : "Icon-App-20x20@3x.png", "scale" : "3x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "iphone", "filename" : "Icon-App-29x29@3x.png", "scale" : "3x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "iphone", "filename" : "Icon-App-40x40@3x.png", "scale" : "3x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@2x.png", "scale" : "2x" }, { "size" : "60x60", "idiom" : "iphone", "filename" : "Icon-App-60x60@3x.png", "scale" : "3x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@1x.png", "scale" : "1x" }, { "size" : "20x20", "idiom" : "ipad", "filename" : "Icon-App-20x20@2x.png", "scale" : "2x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@1x.png", "scale" : "1x" }, { "size" : "29x29", "idiom" : "ipad", "filename" : "Icon-App-29x29@2x.png", "scale" : "2x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@1x.png", "scale" : "1x" }, { "size" : "40x40", "idiom" : "ipad", "filename" : "Icon-App-40x40@2x.png", "scale" : "2x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@1x.png", "scale" : "1x" }, { "size" : "76x76", "idiom" : "ipad", "filename" : "Icon-App-76x76@2x.png", "scale" : "2x" }, { "size" : "83.5x83.5", "idiom" : "ipad", "filename" : "Icon-App-83.5x83.5@2x.png", "scale" : "2x" }, { "size" : "1024x1024", "idiom" : "ios-marketing", "filename" : "Icon-App-1024x1024@1x.png", "scale" : "1x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "filename" : "LaunchImage.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "LaunchImage@2x.png", "scale" : "2x" }, { "idiom" : "universal", "filename" : "LaunchImage@3x.png", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md ================================================ # Launch Screen Assets You can customize the launch screen with your own desired assets by replacing the image files in this directory. You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. ================================================ FILE: example/ios/Runner/Base.lproj/LaunchScreen.storyboard ================================================ ================================================ FILE: example/ios/Runner/Base.lproj/Main.storyboard ================================================ ================================================ FILE: example/ios/Runner/Info.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName flutter_qjs_example CFBundlePackageType APPL CFBundleShortVersionString $(FLUTTER_BUILD_NAME) CFBundleSignature ???? CFBundleVersion $(FLUTTER_BUILD_NUMBER) LSRequiresIPhoneOS UILaunchStoryboardName LaunchScreen UIMainStoryboardFile Main UISupportedInterfaceOrientations UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIViewControllerBasedStatusBarAppearance ================================================ FILE: example/ios/Runner/Runner-Bridging-Header.h ================================================ #import "GeneratedPluginRegistrant.h" ================================================ FILE: example/ios/Runner.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 455CDD0A38C60135FAE4BE1E /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FEEA6A3F04CF4DEF054D0962 /* Pods_Runner.framework */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ 9705A1C41CF9048500538489 /* Embed Frameworks */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( ); name = "Embed Frameworks"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; 177559F5E68C1612914EEE0E /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; D8D4D9C385E355627AD72FDC /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; ED4A476CBE8036EFA898796A /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; FEEA6A3F04CF4DEF054D0962 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 97C146EB1CF9000F007C117D /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 455CDD0A38C60135FAE4BE1E /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 96E397AA563FBD7DD2827B3F /* Pods */ = { isa = PBXGroup; children = ( ED4A476CBE8036EFA898796A /* Pods-Runner.debug.xcconfig */, 177559F5E68C1612914EEE0E /* Pods-Runner.release.xcconfig */, D8D4D9C385E355627AD72FDC /* Pods-Runner.profile.xcconfig */, ); name = Pods; path = Pods; sourceTree = ""; }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 9740EEB31CF90195004384FC /* Generated.xcconfig */, ); name = Flutter; sourceTree = ""; }; 97C146E51CF9000F007C117D = { isa = PBXGroup; children = ( 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, 96E397AA563FBD7DD2827B3F /* Pods */, C1B25DCE3059ACFD6A761EB2 /* Frameworks */, ); sourceTree = ""; }; 97C146EF1CF9000F007C117D /* Products */ = { isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, ); name = Products; sourceTree = ""; }; 97C146F01CF9000F007C117D /* Runner */ = { isa = PBXGroup; children = ( 97C146FA1CF9000F007C117D /* Main.storyboard */, 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, ); path = Runner; sourceTree = ""; }; C1B25DCE3059ACFD6A761EB2 /* Frameworks */ = { isa = PBXGroup; children = ( FEEA6A3F04CF4DEF054D0962 /* Pods_Runner.framework */, ); name = Frameworks; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( 9ED59B3EDDF0CCD362B298B6 /* [CP] Check Pods Manifest.lock */, 9740EEB61CF901F6004384FC /* Run Script */, 97C146EA1CF9000F007C117D /* Sources */, 97C146EB1CF9000F007C117D /* Frameworks */, 97C146EC1CF9000F007C117D /* Resources */, 9705A1C41CF9048500538489 /* Embed Frameworks */, 3B06AD1E1E4923F5004D2608 /* Thin Binary */, D88E1FA61D2123552360E924 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = Runner; productName = Runner; productReference = 97C146EE1CF9000F007C117D /* Runner.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 1020; ORGANIZATIONNAME = ""; TargetAttributes = { 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; LastSwiftMigration = 1100; }; }; }; buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 97C146E51CF9000F007C117D; productRefGroup = 97C146EF1CF9000F007C117D /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 97C146EC1CF9000F007C117D /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Thin Binary"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Run Script"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; }; 9ED59B3EDDF0CCD362B298B6 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; D88E1FA61D2123552360E924 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 97C146EA1CF9000F007C117D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ 97C146FA1CF9000F007C117D /* Main.storyboard */ = { isa = PBXVariantGroup; children = ( 97C146FB1CF9000F007C117D /* Base */, ); name = Main.storyboard; sourceTree = ""; }; 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( 97C147001CF9000F007C117D /* Base */, ); name = LaunchScreen.storyboard; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Profile; }; 249021D4217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = soko.ekibun.flutterQjsExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Profile; }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; 97C147041CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; name = Release; }; 97C147061CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = soko.ekibun.flutterQjsExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Debug; }; 97C147071CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; LIBRARY_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter", ); PRODUCT_BUNDLE_IDENTIFIER = soko.ekibun.flutterQjsExample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; VERSIONING_SYSTEM = "apple-generic"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147031CF9000F007C117D /* Debug */, 97C147041CF9000F007C117D /* Release */, 249021D3217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 97C147061CF9000F007C117D /* Debug */, 97C147071CF9000F007C117D /* Release */, 249021D4217E4FDB00AE95B9 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 97C146E61CF9000F007C117D /* Project object */; } ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings ================================================ PreviewsEnabled ================================================ FILE: example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme ================================================ ================================================ FILE: example/ios/Runner.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings ================================================ PreviewsEnabled ================================================ FILE: example/js/hello.js ================================================ /* * @Description: module example * @Author: ekibun * @Date: 2020-10-03 00:29:45 * @LastEditors: ekibun * @LastEditTime: 2020-10-03 00:32:37 */ export default (name) => `hello ${name}!`; ================================================ FILE: example/lib/highlight.dart ================================================ /* * @Description: Code highlight controller * @Author: ekibun * @Date: 2020-08-01 17:42:06 * @LastEditors: ekibun * @LastEditTime: 2020-08-02 12:39:26 */ import 'dart:math'; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_highlight/themes/a11y-light.dart'; import 'package:highlight/highlight.dart'; Map _theme = a11yLightTheme; List _convert(String code) { var nodes = highlight.parse(code, language: 'javascript').nodes; List spans = []; var currentSpans = spans; List> stack = []; _traverse(Node node) { if (node.value != null) { currentSpans.add(node.className == null ? TextSpan(text: node.value) : TextSpan(text: node.value, style: _theme[node.className])); } else if (node.children != null) { List tmp = []; currentSpans.add(TextSpan(children: tmp, style: _theme[node.className])); stack.add(currentSpans); currentSpans = tmp; node.children.forEach((n) { _traverse(n); if (n == node.children.last) { currentSpans = stack.isEmpty ? spans : stack.removeLast(); } }); } } for (var node in nodes) { _traverse(node); } return spans; } class CodeInputController extends TextEditingController { CodeInputController({String text}) : super(text: text); TextSpan oldSpan = TextSpan(); Future spanCall; @override TextSpan buildTextSpan( {@required BuildContext context, TextStyle style, bool withComposing}) { String oldText = oldSpan.toPlainText(); String newText = value.text; if (oldText == newText) return oldSpan; (spanCall?.timeout(Duration.zero) ?? Future.value()) .then((_) => spanCall = compute(_convert, value.text).then((lsSpan) { TextSpan newSpan = TextSpan(style: style, children: lsSpan); if (newSpan.toPlainText() == value.text) oldSpan = newSpan; notifyListeners(); })) .catchError((_) => {}); List beforeSpans = []; int splitAt = value.selection.start; if (splitAt < 0) splitAt = newText.length ~/ 2; int start = 0; InlineSpan leftSpan; oldSpan.children?.indexWhere((element) { String elementText = element.toPlainText(); if (start + elementText.length > splitAt || !newText.startsWith(elementText, start)) { leftSpan = element; return true; } beforeSpans.add(element); start += elementText.length; return false; }); List endSpans = []; int end = 0; InlineSpan rightSpan; oldSpan.children?.sublist(beforeSpans.length)?.lastIndexWhere((element) { String elementText = element.toPlainText(); if (splitAt + end + elementText.length >= newText.length || !newText .substring(start, newText.length - end) .endsWith(elementText)) { rightSpan = element; return true; } endSpans.add(element); end += elementText.length; return false; }); return TextSpan(style: style, children: [ ...beforeSpans, TextSpan( style: leftSpan != null && leftSpan == rightSpan ? leftSpan.style : style, text: newText.substring(start, max(start, newText.length - end))), ...endSpans.reversed ]); } } ================================================ FILE: example/lib/main.dart ================================================ /* * @Description: example * @Author: ekibun * @Date: 2020-08-08 08:16:51 * @LastEditors: ekibun * @LastEditTime: 2020-12-02 11:28:06 */ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_qjs/flutter_qjs.dart'; import 'highlight.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'flutter_qjs', debugShowCheckedModeBanner: false, theme: ThemeData( appBarTheme: AppBarTheme(brightness: Brightness.dark, elevation: 0), backgroundColor: Colors.grey[300], primaryColorBrightness: Brightness.dark, ), routes: { 'home': (BuildContext context) => TestPage(), }, initialRoute: 'home', ); } } class TestPage extends StatefulWidget { @override State createState() => _TestPageState(); } class _TestPageState extends State { String resp; IsolateQjs engine; CodeInputController _controller = CodeInputController( text: 'import("hello").then(({default: greet}) => greet("world"));'); _ensureEngine() async { if (engine != null) return; engine = IsolateQjs( moduleHandler: (String module) async { return await rootBundle.loadString( "js/" + module.replaceFirst(new RegExp(r".js$"), "") + ".js"); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("JS engine test"), ), body: SingleChildScrollView( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: [ TextButton( child: Text("evaluate"), onPressed: () async { await _ensureEngine(); try { resp = (await engine.evaluate(_controller.text ?? '', name: "")) .toString(); } catch (e) { resp = e.toString(); } setState(() {}); }), TextButton( child: Text("reset engine"), onPressed: () async { if (engine == null) return; await engine.close(); engine = null; }), ], ), ), Container( padding: const EdgeInsets.all(12), color: Colors.grey.withOpacity(0.1), constraints: BoxConstraints(minHeight: 200), child: TextField( autofocus: true, controller: _controller, decoration: null, expands: true, maxLines: null), ), SizedBox(height: 16), Text("result:"), SizedBox(height: 16), Container( width: double.infinity, padding: const EdgeInsets.all(12), color: Colors.green.withOpacity(0.05), constraints: BoxConstraints(minHeight: 100), child: Text(resp ?? ''), ), ], ), ), ); } } ================================================ FILE: example/linux/.gitignore ================================================ flutter/ephemeral ================================================ FILE: example/linux/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) set(BINARY_NAME "example") set(APPLICATION_ID "soko.ekibun.example") cmake_policy(SET CMP0063 NEW) set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") # Configure build options. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() # Compilation settings that should be applied to most targets. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") endfunction() set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") # Flutter library and tool build rules. add_subdirectory(${FLUTTER_MANAGED_DIR}) # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Application build add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) apply_standard_settings(${BINARY_NAME}) target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) add_dependencies(${BINARY_NAME} flutter_assemble) # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ================================================ FILE: example/linux/flutter/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.10) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. # Serves the same purpose as list(TRANSFORM ... PREPEND ...), # which isn't available in 3.10. function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() # === Flutter Library === # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) pkg_check_modules(BLKID REQUIRED IMPORTED_TARGET blkid) set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO PkgConfig::BLKID ) add_dependencies(flutter flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" linux-x64 ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ================================================ FILE: example/linux/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // #include "generated_plugin_registrant.h" #include void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) flutter_qjs_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterQjsPlugin"); flutter_qjs_plugin_register_with_registrar(flutter_qjs_registrar); } ================================================ FILE: example/linux/flutter/generated_plugin_registrant.h ================================================ // // Generated file. Do not edit. // #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include // Registers Flutter plugins. void fl_register_plugins(FlPluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ ================================================ FILE: example/linux/flutter/generated_plugins.cmake ================================================ # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST flutter_qjs ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) ================================================ FILE: example/linux/main.cc ================================================ #include "my_application.h" int main(int argc, char** argv) { // Only X11 is currently supported. // Wayland support is being developed: https://github.com/flutter/flutter/issues/57932. gdk_set_allowed_backends("x11"); g_autoptr(MyApplication) app = my_application_new(); return g_application_run(G_APPLICATION(app), argc, argv); } ================================================ FILE: example/linux/my_application.cc ================================================ #include "my_application.h" #include #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); gtk_window_set_title(window, "example"); gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, nullptr)); } ================================================ FILE: example/linux/my_application.h ================================================ #ifndef FLUTTER_MY_APPLICATION_H_ #define FLUTTER_MY_APPLICATION_H_ #include G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, GtkApplication) /** * my_application_new: * * Creates a new Flutter-based application. * * Returns: a new #MyApplication. */ MyApplication* my_application_new(); #endif // FLUTTER_MY_APPLICATION_H_ ================================================ FILE: example/macos/.gitignore ================================================ # Flutter-related **/Flutter/ephemeral/ **/Pods/ # Xcode-related **/xcuserdata/ ================================================ FILE: example/macos/Flutter/Flutter-Debug.xcconfig ================================================ #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" ================================================ FILE: example/macos/Flutter/Flutter-Release.xcconfig ================================================ #include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" #include "ephemeral/Flutter-Generated.xcconfig" ================================================ FILE: example/macos/Flutter/GeneratedPluginRegistrant.swift ================================================ // // Generated file. Do not edit. // import FlutterMacOS import Foundation import flutter_qjs func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FlutterQjsPlugin.register(with: registry.registrar(forPlugin: "FlutterQjsPlugin")) } ================================================ FILE: example/macos/Podfile ================================================ platform :osx, '10.11' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' project 'Runner', { 'Debug' => :debug, 'Profile' => :release, 'Release' => :release, } def parse_KV_file(file, separator='=') file_abs_path = File.expand_path(file) if !File.exists? file_abs_path return []; end pods_ary = [] skip_line_start_symbols = ["#", "/"] File.foreach(file_abs_path) { |line| next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } plugin = line.split(pattern=separator) if plugin.length == 2 podname = plugin[0].strip() path = plugin[1].strip() podpath = File.expand_path("#{path}", file_abs_path) pods_ary.push({:name => podname, :path => podpath}); else puts "Invalid plugin specification: #{line}" end } return pods_ary end def pubspec_supports_macos(file) file_abs_path = File.expand_path(file) if !File.exists? file_abs_path return false; end File.foreach(file_abs_path) { |line| return true if line =~ /^\s*macos:/ } return false end target 'Runner' do use_frameworks! use_modular_headers! # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock # referring to absolute paths on developers' machines. ephemeral_dir = File.join('Flutter', 'ephemeral') symlink_dir = File.join(ephemeral_dir, '.symlinks') symlink_plugins_dir = File.join(symlink_dir, 'plugins') system("rm -rf #{symlink_dir}") system("mkdir -p #{symlink_plugins_dir}") # Flutter Pods generated_xcconfig = parse_KV_file(File.join(ephemeral_dir, 'Flutter-Generated.xcconfig')) if generated_xcconfig.empty? puts "Flutter-Generated.xcconfig must exist. If you're running pod install manually, make sure flutter packages get is executed first." end generated_xcconfig.map { |p| if p[:name] == 'FLUTTER_FRAMEWORK_DIR' symlink = File.join(symlink_dir, 'flutter') File.symlink(File.dirname(p[:path]), symlink) pod 'FlutterMacOS', :path => File.join(symlink, File.basename(p[:path])) end } # Plugin Pods plugin_pods = parse_KV_file('../.flutter-plugins') plugin_pods.map { |p| symlink = File.join(symlink_plugins_dir, p[:name]) File.symlink(p[:path], symlink) if pubspec_supports_macos(File.join(symlink, 'pubspec.yaml')) pod p[:name], :path => File.join(symlink, 'macos') end } end # Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. install! 'cocoapods', :disable_input_output_paths => true ================================================ FILE: example/macos/Runner/AppDelegate.swift ================================================ import Cocoa import FlutterMacOS @NSApplicationMain class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } } ================================================ FILE: example/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "size" : "16x16", "idiom" : "mac", "filename" : "app_icon_16.png", "scale" : "1x" }, { "size" : "16x16", "idiom" : "mac", "filename" : "app_icon_32.png", "scale" : "2x" }, { "size" : "32x32", "idiom" : "mac", "filename" : "app_icon_32.png", "scale" : "1x" }, { "size" : "32x32", "idiom" : "mac", "filename" : "app_icon_64.png", "scale" : "2x" }, { "size" : "128x128", "idiom" : "mac", "filename" : "app_icon_128.png", "scale" : "1x" }, { "size" : "128x128", "idiom" : "mac", "filename" : "app_icon_256.png", "scale" : "2x" }, { "size" : "256x256", "idiom" : "mac", "filename" : "app_icon_256.png", "scale" : "1x" }, { "size" : "256x256", "idiom" : "mac", "filename" : "app_icon_512.png", "scale" : "2x" }, { "size" : "512x512", "idiom" : "mac", "filename" : "app_icon_512.png", "scale" : "1x" }, { "size" : "512x512", "idiom" : "mac", "filename" : "app_icon_1024.png", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: example/macos/Runner/Base.lproj/MainMenu.xib ================================================ ================================================ FILE: example/macos/Runner/Configs/AppInfo.xcconfig ================================================ // Application-level settings for the Runner target. // // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the // future. If not, the values below would default to using the project name when this becomes a // 'flutter create' template. // The application's name. By default this is also the title of the Flutter window. PRODUCT_NAME = flutter_qjs_example // The application's bundle identifier PRODUCT_BUNDLE_IDENTIFIER = soko.ekibun.flutterQjsExample // The copyright displayed in application information PRODUCT_COPYRIGHT = Copyright © 2020 soko.ekibun. All rights reserved. ================================================ FILE: example/macos/Runner/Configs/Debug.xcconfig ================================================ #include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig" ================================================ FILE: example/macos/Runner/Configs/Release.xcconfig ================================================ #include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig" ================================================ FILE: example/macos/Runner/Configs/Warnings.xcconfig ================================================ WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings GCC_WARN_UNDECLARED_SELECTOR = YES CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE CLANG_WARN__DUPLICATE_METHOD_MATCH = YES CLANG_WARN_PRAGMA_PACK = YES CLANG_WARN_STRICT_PROTOTYPES = YES CLANG_WARN_COMMA = YES GCC_WARN_STRICT_SELECTOR_MATCH = YES CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES GCC_WARN_SHADOW = YES CLANG_WARN_UNREACHABLE_CODE = YES ================================================ FILE: example/macos/Runner/DebugProfile.entitlements ================================================ com.apple.security.app-sandbox com.apple.security.cs.allow-jit com.apple.security.network.server ================================================ FILE: example/macos/Runner/Info.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIconFile CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString $(FLUTTER_BUILD_NAME) CFBundleVersion $(FLUTTER_BUILD_NUMBER) LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright $(PRODUCT_COPYRIGHT) NSMainNibFile MainMenu NSPrincipalClass NSApplication ================================================ FILE: example/macos/Runner/MainFlutterWindow.swift ================================================ import Cocoa import FlutterMacOS class MainFlutterWindow: NSWindow { override func awakeFromNib() { let flutterViewController = FlutterViewController.init() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) RegisterGeneratedPlugins(registry: flutterViewController) super.awakeFromNib() } } ================================================ FILE: example/macos/Runner/Release.entitlements ================================================ com.apple.security.app-sandbox ================================================ FILE: example/macos/Runner.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 51; objects = { /* Begin PBXAggregateTarget section */ 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { isa = PBXAggregateTarget; buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; buildPhases = ( 33CC111E2044C6BF0003C045 /* ShellScript */, ); dependencies = ( ); name = "Flutter Assemble"; productName = FLX; }; /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; 8A0E1E523547DDE6AEEAA187 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E845184DF4416AE932BDD596 /* Pods_Runner.framework */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 33CC10E52044A3C60003C045 /* Project object */; proxyType = 1; remoteGlobalIDString = 33CC111A2044C6BA0003C045; remoteInfo = FLX; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ 33CC110E2044A8840003C045 /* Bundle Framework */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( ); name = "Bundle Framework"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33CC10ED2044A3C60003C045 /* flutter_qjs_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = flutter_qjs_example.app; sourceTree = BUILT_PRODUCTS_DIR; }; 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; 64B57AD34D7E83EE511DDCCF /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 7E8A42D81EE399E35D3B1C49 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; E845184DF4416AE932BDD596 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; ED16B55A7814C4FA5051DC2C /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 33CC10EA2044A3C60003C045 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 8A0E1E523547DDE6AEEAA187 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 33BA886A226E78AF003329D5 /* Configs */ = { isa = PBXGroup; children = ( 33E5194F232828860026EE4D /* AppInfo.xcconfig */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, ); path = Configs; sourceTree = ""; }; 33CC10E42044A3C60003C045 = { isa = PBXGroup; children = ( 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, F7F2688E6097307B6E7FBB0A /* Pods */, ); sourceTree = ""; }; 33CC10EE2044A3C60003C045 /* Products */ = { isa = PBXGroup; children = ( 33CC10ED2044A3C60003C045 /* flutter_qjs_example.app */, ); name = Products; sourceTree = ""; }; 33CC11242044D66E0003C045 /* Resources */ = { isa = PBXGroup; children = ( 33CC10F22044A3C60003C045 /* Assets.xcassets */, 33CC10F42044A3C60003C045 /* MainMenu.xib */, 33CC10F72044A3C60003C045 /* Info.plist */, ); name = Resources; path = ..; sourceTree = ""; }; 33CEB47122A05771004F2AC0 /* Flutter */ = { isa = PBXGroup; children = ( 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, ); path = Flutter; sourceTree = ""; }; 33FAB671232836740065AC1E /* Runner */ = { isa = PBXGroup; children = ( 33CC10F02044A3C60003C045 /* AppDelegate.swift */, 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, 33E51913231747F40026EE4D /* DebugProfile.entitlements */, 33E51914231749380026EE4D /* Release.entitlements */, 33CC11242044D66E0003C045 /* Resources */, 33BA886A226E78AF003329D5 /* Configs */, ); path = Runner; sourceTree = ""; }; D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( E845184DF4416AE932BDD596 /* Pods_Runner.framework */, ); name = Frameworks; sourceTree = ""; }; F7F2688E6097307B6E7FBB0A /* Pods */ = { isa = PBXGroup; children = ( 7E8A42D81EE399E35D3B1C49 /* Pods-Runner.debug.xcconfig */, 64B57AD34D7E83EE511DDCCF /* Pods-Runner.release.xcconfig */, ED16B55A7814C4FA5051DC2C /* Pods-Runner.profile.xcconfig */, ); name = Pods; path = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 33CC10EC2044A3C60003C045 /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( 1BC6EABFB22C790B61CFD12A /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, E193D3629E4189A7A2FB86DD /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( 33CC11202044C79F0003C045 /* PBXTargetDependency */, ); name = Runner; productName = Runner; productReference = 33CC10ED2044A3C60003C045 /* flutter_qjs_example.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 33CC10E52044A3C60003C045 /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0920; LastUpgradeCheck = 0930; ORGANIZATIONNAME = "The Flutter Authors"; TargetAttributes = { 33CC10EC2044A3C60003C045 = { CreatedOnToolsVersion = 9.2; LastSwiftMigration = 1100; ProvisioningStyle = Automatic; SystemCapabilities = { com.apple.Sandbox = { enabled = 1; }; }; }; 33CC111A2044C6BA0003C045 = { CreatedOnToolsVersion = 9.2; ProvisioningStyle = Manual; }; }; }; buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; compatibilityVersion = "Xcode 8.0"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 33CC10E42044A3C60003C045; productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 33CC10EC2044A3C60003C045 /* Runner */, 33CC111A2044C6BA0003C045 /* Flutter Assemble */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 33CC10EB2044A3C60003C045 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 1BC6EABFB22C790B61CFD12A /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( ); outputFileListPaths = ( ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; }; 33CC111E2044C6BF0003C045 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( Flutter/ephemeral/FlutterInputs.xcfilelist, ); inputPaths = ( Flutter/ephemeral/tripwire, ); outputFileListPaths = ( Flutter/ephemeral/FlutterOutputs.xcfilelist, ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; E193D3629E4189A7A2FB86DD /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 33CC10E92044A3C60003C045 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { isa = PBXVariantGroup; children = ( 33CC10F52044A3C60003C045 /* Base */, ); name = MainMenu.xib; path = Runner; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 338D0CE9231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Profile; }; 338D0CEA231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter/ephemeral", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_VERSION = 5.0; }; name = Profile; }; 338D0CEB231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Manual; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Profile; }; 33CC10F92044A3C60003C045 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; 33CC10FA2044A3C60003C045 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; 33CC10FC2044A3C60003C045 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter/ephemeral", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; }; name = Debug; }; 33CC10FD2044A3C60003C045 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(PROJECT_DIR)/Flutter/ephemeral", ); INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_VERSION = 5.0; }; name = Release; }; 33CC111C2044C6BA0003C045 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Manual; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 33CC111D2044C6BA0003C045 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC10F92044A3C60003C045 /* Debug */, 33CC10FA2044A3C60003C045 /* Release */, 338D0CE9231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC10FC2044A3C60003C045 /* Debug */, 33CC10FD2044A3C60003C045 /* Release */, 338D0CEA231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC111C2044C6BA0003C045 /* Debug */, 33CC111D2044C6BA0003C045 /* Release */, 338D0CEB231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 33CC10E52044A3C60003C045 /* Project object */; } ================================================ FILE: example/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme ================================================ ================================================ FILE: example/macos/Runner.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: example/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: example/pubspec.yaml ================================================ name: flutter_qjs_example description: Demonstrates how to use the flutter_qjs plugin. # The following line prevents the package from being accidentally published to # pub.dev using `pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev environment: sdk: ">=2.7.0 <3.0.0" dependencies: flutter: sdk: flutter flutter_qjs: # When depending on this package from a real application you should use: # flutter_qjs: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ highlight: 0.6.0 flutter_highlight: 0.6.0 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter. flutter: # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: assets: - js/ # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.dev/custom-fonts/#from-packages ================================================ FILE: example/windows/.gitignore ================================================ flutter/ephemeral/ # Visual Studio user-specific files. *.suo *.user *.userosscache *.sln.docstates # Visual Studio build-related files. x64/ x86/ # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ ================================================ FILE: example/windows/CMakeLists.txt ================================================ # Project-level configuration. cmake_minimum_required(VERSION 3.14) project(example LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "example") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(SET CMP0063 NEW) # Define build configuration option. get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() # Define settings for the Profile build mode. set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") # Use Unicode for all projects. add_definitions(-DUNICODE -D_UNICODE) # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # Application build; see runner/CMakeLists.txt. add_subdirectory("runner") # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # Support files are copied into place next to the executable, so that it can # run in place. This is done instead of making a separate bundle (as on Linux) # so that building and running from within Visual Studio will work. set(BUILD_BUNDLE_DIR "$") # Make the "install" step default, as it's required to run. set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ================================================ FILE: example/windows/flutter/CMakeLists.txt ================================================ # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) # === Wrapper === list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") # Wrapper sources needed for a plugin. add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) # Wrapper sources needed for the runner. add_library(flutter_wrapper_app STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_APP} ) apply_standard_settings(flutter_wrapper_app) target_link_libraries(flutter_wrapper_app PUBLIC flutter) target_include_directories(flutter_wrapper_app PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_app flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" windows-x64 $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ================================================ FILE: example/windows/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include void RegisterPlugins(flutter::PluginRegistry* registry) { FlutterQjsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("FlutterQjsPlugin")); } ================================================ FILE: example/windows/flutter/generated_plugin_registrant.h ================================================ // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include // Registers Flutter plugins. void RegisterPlugins(flutter::PluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ ================================================ FILE: example/windows/flutter/generated_plugins.cmake ================================================ # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST flutter_qjs ) list(APPEND FLUTTER_FFI_PLUGIN_LIST ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin) ================================================ FILE: example/windows/runner/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Disable Windows macros that collide with C++ standard library functions. target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) ================================================ FILE: example/windows/runner/Runner.rc ================================================ // Microsoft Visual C++ generated resource script. // #pragma code_page(65001) #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""winres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_APP_ICON ICON "resources\\app_icon.ico" ///////////////////////////////////////////////////////////////////////////// // // Version // #ifdef FLUTTER_BUILD_NUMBER #define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER #else #define VERSION_AS_NUMBER 1,0,0 #endif #ifdef FLUTTER_BUILD_NAME #define VERSION_AS_STRING #FLUTTER_BUILD_NAME #else #define VERSION_AS_STRING "1.0.0" #endif VS_VERSION_INFO VERSIONINFO FILEVERSION VERSION_AS_NUMBER PRODUCTVERSION VERSION_AS_NUMBER FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0x0L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_APP FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904e4" BEGIN VALUE "CompanyName", "com.example" "\0" VALUE "FileDescription", "example" "\0" VALUE "FileVersion", VERSION_AS_STRING "\0" VALUE "InternalName", "example" "\0" VALUE "LegalCopyright", "Copyright (C) 2022 com.example. All rights reserved." "\0" VALUE "OriginalFilename", "example.exe" "\0" VALUE "ProductName", "example" "\0" VALUE "ProductVersion", VERSION_AS_STRING "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END #endif // English (United States) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ================================================ FILE: example/windows/runner/flutter_window.cpp ================================================ #include "flutter_window.h" #include #include "flutter/generated_plugin_registrant.h" FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} FlutterWindow::~FlutterWindow() {} bool FlutterWindow::OnCreate() { if (!Win32Window::OnCreate()) { return false; } RECT frame = GetClientArea(); // The size here must match the window dimensions to avoid unnecessary surface // creation / destruction in the startup path. flutter_controller_ = std::make_unique( frame.right - frame.left, frame.bottom - frame.top, project_); // Ensure that basic setup of the controller was successful. if (!flutter_controller_->engine() || !flutter_controller_->view()) { return false; } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); return true; } void FlutterWindow::OnDestroy() { if (flutter_controller_) { flutter_controller_ = nullptr; } Win32Window::OnDestroy(); } LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { // Give Flutter, including plugins, an opportunity to handle window messages. if (flutter_controller_) { std::optional result = flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, lparam); if (result) { return *result; } } switch (message) { case WM_FONTCHANGE: flutter_controller_->engine()->ReloadSystemFonts(); break; } return Win32Window::MessageHandler(hwnd, message, wparam, lparam); } ================================================ FILE: example/windows/runner/flutter_window.h ================================================ #ifndef RUNNER_FLUTTER_WINDOW_H_ #define RUNNER_FLUTTER_WINDOW_H_ #include #include #include #include "win32_window.h" // A window that does nothing but host a Flutter view. class FlutterWindow : public Win32Window { public: // Creates a new FlutterWindow hosting a Flutter view running |project|. explicit FlutterWindow(const flutter::DartProject& project); virtual ~FlutterWindow(); protected: // Win32Window: bool OnCreate() override; void OnDestroy() override; LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; private: // The project to run. flutter::DartProject project_; // The Flutter instance hosted by this window. std::unique_ptr flutter_controller_; }; #endif // RUNNER_FLUTTER_WINDOW_H_ ================================================ FILE: example/windows/runner/main.cpp ================================================ #include #include #include #include "flutter_window.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); flutter::DartProject project(L"data"); std::vector command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); FlutterWindow window(project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.CreateAndShow(L"example", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); ::MSG msg; while (::GetMessage(&msg, nullptr, 0, 0)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::CoUninitialize(); return EXIT_SUCCESS; } ================================================ FILE: example/windows/runner/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Runner.rc // #define IDI_APP_ICON 101 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 102 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: example/windows/runner/runner.exe.manifest ================================================ PerMonitorV2 ================================================ FILE: example/windows/runner/utils.cpp ================================================ #include "utils.h" #include #include #include #include #include void CreateAndAttachConsole() { if (::AllocConsole()) { FILE *unused; if (freopen_s(&unused, "CONOUT$", "w", stdout)) { _dup2(_fileno(stdout), 1); } if (freopen_s(&unused, "CONOUT$", "w", stderr)) { _dup2(_fileno(stdout), 2); } std::ios::sync_with_stdio(); FlutterDesktopResyncOutputStreams(); } } std::vector GetCommandLineArguments() { // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. int argc; wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); if (argv == nullptr) { return std::vector(); } std::vector command_line_arguments; // Skip the first argument as it's the binary name. for (int i = 1; i < argc; i++) { command_line_arguments.push_back(Utf8FromUtf16(argv[i])); } ::LocalFree(argv); return command_line_arguments; } std::string Utf8FromUtf16(const wchar_t* utf16_string) { if (utf16_string == nullptr) { return std::string(); } int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, nullptr, 0, nullptr, nullptr); if (target_length == 0) { return std::string(); } std::string utf8_string; utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); } return utf8_string; } ================================================ FILE: example/windows/runner/utils.h ================================================ #ifndef RUNNER_UTILS_H_ #define RUNNER_UTILS_H_ #include #include // Creates a console for the process, and redirects stdout and stderr to // it for both the runner and the Flutter library. void CreateAndAttachConsole(); // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string // encoded in UTF-8. Returns an empty std::string on failure. std::string Utf8FromUtf16(const wchar_t* utf16_string); // Gets the command line arguments passed in as a std::vector, // encoded in UTF-8. Returns an empty std::vector on failure. std::vector GetCommandLineArguments(); #endif // RUNNER_UTILS_H_ ================================================ FILE: example/windows/runner/win32_window.cpp ================================================ #include "win32_window.h" #include #include "resource.h" namespace { constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; // The number of Win32Window objects that currently exist. static int g_active_window_count = 0; using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); // Scale helper to convert logical scaler values to physical using passed in // scale factor int Scale(int source, double scale_factor) { return static_cast(source * scale_factor); } // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. // This API is only needed for PerMonitor V1 awareness mode. void EnableFullDpiSupportIfAvailable(HWND hwnd) { HMODULE user32_module = LoadLibraryA("User32.dll"); if (!user32_module) { return; } auto enable_non_client_dpi_scaling = reinterpret_cast( GetProcAddress(user32_module, "EnableNonClientDpiScaling")); if (enable_non_client_dpi_scaling != nullptr) { enable_non_client_dpi_scaling(hwnd); FreeLibrary(user32_module); } } } // namespace // Manages the Win32Window's window class registration. class WindowClassRegistrar { public: ~WindowClassRegistrar() = default; // Returns the singleton registar instance. static WindowClassRegistrar* GetInstance() { if (!instance_) { instance_ = new WindowClassRegistrar(); } return instance_; } // Returns the name of the window class, registering the class if it hasn't // previously been registered. const wchar_t* GetWindowClass(); // Unregisters the window class. Should only be called if there are no // instances of the window. void UnregisterWindowClass(); private: WindowClassRegistrar() = default; static WindowClassRegistrar* instance_; bool class_registered_ = false; }; WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; const wchar_t* WindowClassRegistrar::GetWindowClass() { if (!class_registered_) { WNDCLASS window_class{}; window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); window_class.lpszClassName = kWindowClassName; window_class.style = CS_HREDRAW | CS_VREDRAW; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = GetModuleHandle(nullptr); window_class.hIcon = LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); window_class.hbrBackground = 0; window_class.lpszMenuName = nullptr; window_class.lpfnWndProc = Win32Window::WndProc; RegisterClass(&window_class); class_registered_ = true; } return kWindowClassName; } void WindowClassRegistrar::UnregisterWindowClass() { UnregisterClass(kWindowClassName, nullptr); class_registered_ = false; } Win32Window::Win32Window() { ++g_active_window_count; } Win32Window::~Win32Window() { --g_active_window_count; Destroy(); } bool Win32Window::CreateAndShow(const std::wstring& title, const Point& origin, const Size& size) { Destroy(); const wchar_t* window_class = WindowClassRegistrar::GetInstance()->GetWindowClass(); const POINT target_point = {static_cast(origin.x), static_cast(origin.y)}; HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); double scale_factor = dpi / 96.0; HWND window = CreateWindow( window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), Scale(size.width, scale_factor), Scale(size.height, scale_factor), nullptr, nullptr, GetModuleHandle(nullptr), this); if (!window) { return false; } return OnCreate(); } // static LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (message == WM_NCCREATE) { auto window_struct = reinterpret_cast(lparam); SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast(window_struct->lpCreateParams)); auto that = static_cast(window_struct->lpCreateParams); EnableFullDpiSupportIfAvailable(window); that->window_handle_ = window; } else if (Win32Window* that = GetThisFromHandle(window)) { return that->MessageHandler(window, message, wparam, lparam); } return DefWindowProc(window, message, wparam, lparam); } LRESULT Win32Window::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { switch (message) { case WM_DESTROY: window_handle_ = nullptr; Destroy(); if (quit_on_close_) { PostQuitMessage(0); } return 0; case WM_DPICHANGED: { auto newRectSize = reinterpret_cast(lparam); LONG newWidth = newRectSize->right - newRectSize->left; LONG newHeight = newRectSize->bottom - newRectSize->top; SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, newHeight, SWP_NOZORDER | SWP_NOACTIVATE); return 0; } case WM_SIZE: { RECT rect = GetClientArea(); if (child_content_ != nullptr) { // Size and position the child window. MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE); } return 0; } case WM_ACTIVATE: if (child_content_ != nullptr) { SetFocus(child_content_); } return 0; } return DefWindowProc(window_handle_, message, wparam, lparam); } void Win32Window::Destroy() { OnDestroy(); if (window_handle_) { DestroyWindow(window_handle_); window_handle_ = nullptr; } if (g_active_window_count == 0) { WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); } } Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { return reinterpret_cast( GetWindowLongPtr(window, GWLP_USERDATA)); } void Win32Window::SetChildContent(HWND content) { child_content_ = content; SetParent(content, window_handle_); RECT frame = GetClientArea(); MoveWindow(content, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, true); SetFocus(child_content_); } RECT Win32Window::GetClientArea() { RECT frame; GetClientRect(window_handle_, &frame); return frame; } HWND Win32Window::GetHandle() { return window_handle_; } void Win32Window::SetQuitOnClose(bool quit_on_close) { quit_on_close_ = quit_on_close; } bool Win32Window::OnCreate() { // No-op; provided for subclasses. return true; } void Win32Window::OnDestroy() { // No-op; provided for subclasses. } ================================================ FILE: example/windows/runner/win32_window.h ================================================ #ifndef RUNNER_WIN32_WINDOW_H_ #define RUNNER_WIN32_WINDOW_H_ #include #include #include #include // A class abstraction for a high DPI-aware Win32 Window. Intended to be // inherited from by classes that wish to specialize with custom // rendering and input handling class Win32Window { public: struct Point { unsigned int x; unsigned int y; Point(unsigned int x, unsigned int y) : x(x), y(y) {} }; struct Size { unsigned int width; unsigned int height; Size(unsigned int width, unsigned int height) : width(width), height(height) {} }; Win32Window(); virtual ~Win32Window(); // Creates and shows a win32 window with |title| and position and size using // |origin| and |size|. New windows are created on the default monitor. Window // sizes are specified to the OS in physical pixels, hence to ensure a // consistent size to will treat the width height passed in to this function // as logical pixels and scale to appropriate for the default monitor. Returns // true if the window was created successfully. bool CreateAndShow(const std::wstring& title, const Point& origin, const Size& size); // Release OS resources associated with window. void Destroy(); // Inserts |content| into the window tree. void SetChildContent(HWND content); // Returns the backing Window handle to enable clients to set icon and other // window properties. Returns nullptr if the window has been destroyed. HWND GetHandle(); // If true, closing this window will quit the application. void SetQuitOnClose(bool quit_on_close); // Return a RECT representing the bounds of the current client area. RECT GetClientArea(); protected: // Processes and route salient window messages for mouse handling, // size change and DPI. Delegates handling of these to member overloads that // inheriting classes can handle. virtual LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // Called when CreateAndShow is called, allowing subclass window-related // setup. Subclasses should return false if setup fails. virtual bool OnCreate(); // Called when Destroy is called. virtual void OnDestroy(); private: friend class WindowClassRegistrar; // OS callback called by message pump. Handles the WM_NCCREATE message which // is passed when the non-client area is being created and enables automatic // non-client DPI scaling so that the non-client area automatically // responsponds to changes in DPI. All other messages are handled by // MessageHandler. static LRESULT CALLBACK WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // Retrieves a class instance pointer for |window| static Win32Window* GetThisFromHandle(HWND const window) noexcept; bool quit_on_close_ = false; // window handle for top level window. HWND window_handle_ = nullptr; // window handle for hosted content. HWND child_content_ = nullptr; }; #endif // RUNNER_WIN32_WINDOW_H_ ================================================ FILE: flutter_qjs.iml ================================================ ================================================ FILE: ios/.gitignore ================================================ .idea/ .vagrant/ .sconsign.dblite .svn/ .DS_Store *.swp profile DerivedData/ build/ GeneratedPluginRegistrant.h GeneratedPluginRegistrant.m .generated/ *.pbxuser *.mode1v3 *.mode2v3 *.perspectivev3 !default.pbxuser !default.mode1v3 !default.mode2v3 !default.perspectivev3 xcuserdata *.moved-aside *.pyc *sync/ Icon? .tags* /Flutter/Generated.xcconfig /Flutter/flutter_export_environment.sh ================================================ FILE: ios/Assets/.gitkeep ================================================ ================================================ FILE: ios/Classes/FlutterQjsPlugin.h ================================================ #import @interface FlutterQjsPlugin : NSObject @end ================================================ FILE: ios/Classes/FlutterQjsPlugin.m ================================================ #import "FlutterQjsPlugin.h" #if __has_include() #import #else // Support project import fallback if the generated compatibility header // is not copied when this plugin is created as a library. // https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816 #import "flutter_qjs-Swift.h" #endif @implementation FlutterQjsPlugin + (void)registerWithRegistrar:(NSObject*)registrar { [SwiftFlutterQjsPlugin registerWithRegistrar:registrar]; } @end ================================================ FILE: ios/Classes/SwiftFlutterQjsPlugin.swift ================================================ import Flutter import UIKit public class SwiftFlutterQjsPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flutter_qjs", binaryMessenger: registrar.messenger()) let instance = SwiftFlutterQjsPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { result("iOS " + UIDevice.current.systemVersion) } } ================================================ FILE: ios/flutter_qjs.podspec ================================================ # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint flutter_qjs.podspec' to validate before publishing. # Pod::Spec.new do |s| s.name = 'flutter_qjs' s.version = '0.0.1' s.summary = 'A quickjs engine for flutter.' s.description = <<-DESC This plugin is a simple js engine for flutter using the `quickjs` project. Plugin currently supports all the platforms except web! DESC s.homepage = 'https://github.com/ekibun/flutter_qjs' s.license = { :file => '../LICENSE' } s.author = { 'ekibun' => 'soekibun@gmail.com' } s.source = { :path => '.' } s.compiler_flags = '-DDUMP_LEAKS' s.source_files = ['Classes/**/*', 'cxx/*.{c,cpp}'] s.dependency 'Flutter' s.platform = :ios, '8.0' # Flutter.framework does not contain a i386 slice. s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } s.prepare_command = 'sh ../cxx/prebuild.sh' s.swift_version = '5.0' end ================================================ FILE: lib/flutter_qjs.dart ================================================ import 'dart:async'; import 'dart:ffi'; import 'dart:io'; import 'dart:isolate'; import 'dart:typed_data'; import 'package:ffi/ffi.dart'; import 'src/ffi.dart'; export 'src/ffi.dart' show JSEvalFlag, JSRef; part 'src/engine.dart'; part 'src/isolate.dart'; part 'src/wrapper.dart'; part 'src/object.dart'; ================================================ FILE: lib/src/engine.dart ================================================ /* * @Description: quickjs engine * @Author: ekibun * @Date: 2020-08-08 08:29:09 * @LastEditors: ekibun * @LastEditTime: 2020-10-06 23:47:13 */ part of '../flutter_qjs.dart'; /// Handler function to manage js module. typedef _JsModuleHandler = String Function(String name); /// Handler to manage unhandled promise rejection. typedef _JsHostPromiseRejectionHandler = void Function(dynamic reason); /// Quickjs engine for flutter. class FlutterQjs { Pointer? _rt; Pointer? _ctx; /// Max stack size for quickjs. final int? stackSize; /// Max stack size for quickjs. final int? timeout; /// Max memory for quickjs. final int? memoryLimit; /// Message Port for event loop. Close it to stop dispatching event loop. ReceivePort port = ReceivePort(); /// Handler function to manage js module. final _JsModuleHandler? moduleHandler; /// Handler function to manage js module. final _JsHostPromiseRejectionHandler? hostPromiseRejectionHandler; FlutterQjs({ this.moduleHandler, this.stackSize, this.timeout, this.memoryLimit, this.hostPromiseRejectionHandler, }); _ensureEngine() { if (_rt != null) return; final rt = jsNewRuntime((ctx, type, ptr) { try { switch (type) { case JSChannelType.METHON: final pdata = ptr.cast>(); final argc = pdata.elementAt(1).value.cast().value; final pargs = []; for (var i = 0; i < argc; ++i) { pargs.add(_jsToDart( ctx, Pointer.fromAddress( pdata.elementAt(2).value.address + sizeOfJSValue * i, ), )); } final JSInvokable func = _jsToDart( ctx, pdata.elementAt(3).value, ); return _dartToJs( ctx, func.invoke( pargs, _jsToDart(ctx, pdata.elementAt(0).value), )); case JSChannelType.MODULE: if (moduleHandler == null) throw JSError('No ModuleHandler'); final ret = moduleHandler!( ptr.cast().toDartString(), ).toNativeUtf8(); Future.microtask(() { malloc.free(ret); }); return ret.cast(); case JSChannelType.PROMISE_TRACK: final err = _parseJSException(ctx, ptr); if (hostPromiseRejectionHandler != null) { hostPromiseRejectionHandler!(err); } else { print('unhandled promise rejection: $err'); } return nullptr; case JSChannelType.FREE_OBJECT: final rt = ctx.cast(); _DartObject.fromAddress(rt, ptr.address)?.free(); return nullptr; } throw JSError('call channel with wrong type'); } catch (e) { if (type == JSChannelType.FREE_OBJECT) { print('DartObject release error: $e'); return nullptr; } if (type == JSChannelType.MODULE) { print('host Promise Rejection Handler error: $e'); return nullptr; } final throwObj = _dartToJs(ctx, e); final err = jsThrow(ctx, throwObj); jsFreeValue(ctx, throwObj); if (type == JSChannelType.MODULE) { jsFreeValue(ctx, err); return nullptr; } return err; } }, timeout ?? 0, port); final stackSize = this.stackSize ?? 0; if (stackSize > 0) jsSetMaxStackSize(rt, stackSize); final memoryLimit = this.memoryLimit ?? 0; if (memoryLimit > 0) jsSetMemoryLimit(rt, memoryLimit); _rt = rt; _ctx = jsNewContext(rt); } /// Free Runtime and Context which can be recreate when evaluate again. close() { final rt = _rt; final ctx = _ctx; _rt = null; _ctx = null; if (ctx != null) jsFreeContext(ctx); if (rt == null) return; _executePendingJob(); try { jsFreeRuntime(rt); } on String catch (e) { throw JSError(e); } } void _executePendingJob() { final rt = _rt; final ctx = _ctx; if (rt == null || ctx == null) return; while (true) { int err = jsExecutePendingJob(rt); if (err <= 0) { if (err < 0) print(_parseJSException(ctx)); break; } } } /// Dispatch JavaScript Event loop. Future dispatch() async { await for (final _ in port) { _executePendingJob(); } } /// Evaluate js script. dynamic evaluate( String command, { String? name, int? evalFlags, }) { _ensureEngine(); final ctx = _ctx!; final jsval = jsEval( ctx, command, name ?? '', evalFlags ?? JSEvalFlag.GLOBAL, ); if (jsIsException(jsval) != 0) { jsFreeValue(ctx, jsval); throw _parseJSException(ctx); } final result = _jsToDart(ctx, jsval); jsFreeValue(ctx, jsval); return result; } } ================================================ FILE: lib/src/ffi.dart ================================================ /* * @Description: ffi * @Author: ekibun * @Date: 2020-09-19 10:29:04 * @LastEditors: ekibun * @LastEditTime: 2020-12-02 11:14:35 */ import 'dart:ffi'; import 'dart:io'; import 'dart:isolate'; import 'package:ffi/ffi.dart'; extension ListFirstWhere on Iterable { T? firstWhereOrNull(bool Function(T) test) { try { return firstWhere(test); } on StateError { return null; } } } abstract class JSRef { int _refCount = 0; void dup() { _refCount++; } void free() { _refCount--; if (_refCount < 0) destroy(); } void destroy(); static void freeRecursive(dynamic obj) { _callRecursive(obj, (ref) => ref.free()); } static void dupRecursive(dynamic obj) { _callRecursive(obj, (ref) => ref.dup()); } static void _callRecursive( dynamic obj, void Function(JSRef) cb, [ Set? cache, ]) { if (obj == null) return; if (cache == null) cache = Set(); if (cache.contains(obj)) return; if (obj is List) { cache.add(obj); List.from(obj).forEach((e) => _callRecursive(e, cb, cache)); } if (obj is Map) { cache.add(obj); obj.values.toList().forEach((e) => _callRecursive(e, cb, cache)); } if (obj is JSRef) { cb(obj); } } } abstract class JSRefLeakable {} class JSEvalFlag { static const GLOBAL = 0 << 0; static const MODULE = 1 << 0; } class JSChannelType { static const METHON = 0; static const MODULE = 1; static const PROMISE_TRACK = 2; static const FREE_OBJECT = 3; } class JSProp { static const CONFIGURABLE = (1 << 0); static const WRITABLE = (1 << 1); static const ENUMERABLE = (1 << 2); static const C_W_E = (CONFIGURABLE | WRITABLE | ENUMERABLE); } class JSTag { static const FIRST = -11; /* first negative tag */ static const BIG_DECIMAL = -11; static const BIG_INT = -10; static const BIG_FLOAT = -9; static const SYMBOL = -8; static const STRING = -7; static const MODULE = -3; /* used internally */ static const FUNCTION_BYTECODE = -2; /* used internally */ static const OBJECT = -1; static const INT = 0; static const BOOL = 1; static const NULL = 2; static const UNDEFINED = 3; static const UNINITIALIZED = 4; static const CATCH_OFFSET = 5; static const EXCEPTION = 6; static const FLOAT64 = 7; } abstract class JSValue extends Opaque {} abstract class JSContext extends Opaque {} abstract class JSRuntime extends Opaque {} abstract class JSPropertyEnum extends Opaque {} final DynamicLibrary _qjsLib = Platform.environment['FLUTTER_TEST'] == 'true' ? (Platform.isWindows ? DynamicLibrary.open('test/build/Debug/ffiquickjs.dll') : Platform.isMacOS ? DynamicLibrary.open('test/build/libffiquickjs.dylib') : DynamicLibrary.open('test/build/libffiquickjs.so')) : (Platform.isWindows ? DynamicLibrary.open('flutter_qjs_plugin.dll') : Platform.isAndroid ? DynamicLibrary.open('libqjs.so') : DynamicLibrary.process()); /// DLLEXPORT JSValue *jsThrow(JSContext *ctx, JSValue *obj) final Pointer Function( Pointer ctx, Pointer obj, ) jsThrow = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, )>>('jsThrow') .asFunction(); /// JSValue *jsEXCEPTION() final Pointer Function() jsEXCEPTION = _qjsLib .lookup Function()>>('jsEXCEPTION') .asFunction(); /// JSValue *jsUNDEFINED() final Pointer Function() jsUNDEFINED = _qjsLib .lookup Function()>>('jsUNDEFINED') .asFunction(); typedef _JSChannel = Pointer Function( Pointer ctx, int method, Pointer argv); typedef _JSChannelNative = Pointer Function( Pointer ctx, IntPtr method, Pointer argv); /// JSRuntime *jsNewRuntime(JSChannel channel) final Pointer Function( Pointer>, int, ) _jsNewRuntime = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer>, Int64, )>>('jsNewRuntime') .asFunction(); class _RuntimeOpaque { final _JSChannel _channel; List _ref = []; final ReceivePort _port; int? _dartObjectClassId; _RuntimeOpaque(this._channel, this._port); int? get dartObjectClassId => _dartObjectClassId; void addRef(JSRef ref) => _ref.add(ref); bool removeRef(JSRef ref) => _ref.remove(ref); JSRef? getRef(bool Function(JSRef ref) test) { return _ref.firstWhereOrNull(test); } } final Map, _RuntimeOpaque> runtimeOpaques = Map(); Pointer? channelDispacher( Pointer ctx, int type, Pointer argv, ) { final rt = type == JSChannelType.FREE_OBJECT ? ctx.cast() : jsGetRuntime(ctx); return runtimeOpaques[rt]?._channel(ctx, type, argv); } Pointer jsNewRuntime( _JSChannel callback, int timeout, ReceivePort port, ) { final rt = _jsNewRuntime(Pointer.fromFunction(channelDispacher), timeout); runtimeOpaques[rt] = _RuntimeOpaque(callback, port); return rt; } /// DLLEXPORT void jsSetMaxStackSize(JSRuntime *rt, size_t stack_size) final void Function( Pointer, int, ) jsSetMaxStackSize = _qjsLib .lookup< NativeFunction< Void Function( Pointer, IntPtr, )>>('jsSetMaxStackSize') .asFunction(); /// DLLEXPORT void jsSetMemoryLimit(JSRuntime *rt, size_t limit); final void Function( Pointer, int, ) jsSetMemoryLimit = _qjsLib .lookup< NativeFunction< Void Function( Pointer, IntPtr, )>>('jsSetMemoryLimit') .asFunction(); /// void jsFreeRuntime(JSRuntime *rt) final void Function( Pointer, ) _jsFreeRuntime = _qjsLib .lookup< NativeFunction< Void Function( Pointer, )>>('jsFreeRuntime') .asFunction(); void jsFreeRuntime( Pointer rt, ) { final referenceleak = []; final opaque = runtimeOpaques[rt]; if (opaque != null) { while (true) { final ref = opaque._ref.firstWhereOrNull((ref) => ref is JSRefLeakable); if (ref == null) break; ref.destroy(); runtimeOpaques[rt]?._ref.remove(ref); } while (opaque._ref.isNotEmpty) { final ref = opaque._ref.first; final objStrs = ref.toString().split('\n'); final objStr = objStrs.length > 0 ? objStrs[0] + " ..." : objStrs[0]; referenceleak.add( " ${identityHashCode(ref)}\t${ref._refCount + 1}\t${ref.runtimeType.toString()}\t$objStr"); ref.destroy(); } } _jsFreeRuntime(rt); if (referenceleak.length > 0) { throw ('reference leak:\n ADDR\tREF\tTYPE\tPROP\n' + referenceleak.join('\n')); } } /// JSValue *jsNewCFunction(JSContext *ctx, JSValue *funcData) final Pointer Function( Pointer ctx, Pointer funcData, ) jsNewCFunction = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, )>>('jsNewCFunction') .asFunction(); /// JSContext *jsNewContext(JSRuntime *rt) final Pointer Function( Pointer rt, ) _jsNewContext = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, )>>('jsNewContext') .asFunction(); Pointer jsNewContext(Pointer rt) { final ctx = _jsNewContext(rt); if (ctx.address == 0) throw Exception('Context create failed!'); final runtimeOpaque = runtimeOpaques[rt]; if (runtimeOpaque == null) throw Exception('Runtime has been released!'); runtimeOpaque._dartObjectClassId = jsNewClass(ctx, 'DartObject'); return ctx; } /// void jsFreeContext(JSContext *ctx) final void Function( Pointer, ) jsFreeContext = _qjsLib .lookup< NativeFunction< Void Function( Pointer, )>>('jsFreeContext') .asFunction(); /// JSRuntime *jsGetRuntime(JSContext *ctx) final Pointer Function( Pointer, ) jsGetRuntime = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, )>>('jsGetRuntime') .asFunction(); /// JSValue *jsEval(JSContext *ctx, const char *input, size_t input_len, const char *filename, int eval_flags) final Pointer Function( Pointer ctx, Pointer input, int inputLen, Pointer filename, int evalFlags, ) _jsEval = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, IntPtr, Pointer, Int32, )>>('jsEval') .asFunction(); Pointer jsEval( Pointer ctx, String input, String filename, int evalFlags, ) { final utf8input = input.toNativeUtf8(); final utf8filename = filename.toNativeUtf8(); final val = _jsEval( ctx, utf8input, utf8input.length, utf8filename, evalFlags, ); malloc.free(utf8input); malloc.free(utf8filename); runtimeOpaques[jsGetRuntime(ctx)]?._port.sendPort.send(#eval); return val; } /// DLLEXPORT int32_t jsValueGetTag(JSValue *val) final int Function( Pointer val, ) jsValueGetTag = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, )>>('jsValueGetTag') .asFunction(); /// void *jsValueGetPtr(JSValue *val) final int Function( Pointer val, ) jsValueGetPtr = _qjsLib .lookup< NativeFunction< IntPtr Function( Pointer, )>>('jsValueGetPtr') .asFunction(); /// DLLEXPORT bool jsTagIsFloat64(int32_t tag) final int Function( int val, ) jsTagIsFloat64 = _qjsLib .lookup< NativeFunction< Int32 Function( Int32, )>>('jsTagIsFloat64') .asFunction(); /// JSValue *jsNewBool(JSContext *ctx, int val) final Pointer Function( Pointer ctx, int val, ) jsNewBool = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Int32, )>>('jsNewBool') .asFunction(); /// JSValue *jsNewInt64(JSContext *ctx, int64_t val) final Pointer Function( Pointer ctx, int val, ) jsNewInt64 = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Int64, )>>('jsNewInt64') .asFunction(); /// JSValue *jsNewFloat64(JSContext *ctx, double val) final Pointer Function( Pointer ctx, double val, ) jsNewFloat64 = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Double, )>>('jsNewFloat64') .asFunction(); /// JSValue *jsNewString(JSContext *ctx, const char *str) final Pointer Function( Pointer ctx, Pointer str, ) _jsNewString = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, )>>('jsNewString') .asFunction(); Pointer jsNewString( Pointer ctx, String str, ) { final utf8str = str.toNativeUtf8(); final jsStr = _jsNewString(ctx, utf8str); malloc.free(utf8str); return jsStr; } /// JSValue *jsNewArrayBufferCopy(JSContext *ctx, const uint8_t *buf, size_t len) final Pointer Function( Pointer ctx, Pointer buf, int len, ) jsNewArrayBufferCopy = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, IntPtr, )>>('jsNewArrayBufferCopy') .asFunction(); /// JSValue *jsNewArray(JSContext *ctx) final Pointer Function( Pointer ctx, ) jsNewArray = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, )>>('jsNewArray') .asFunction(); /// JSValue *jsNewObject(JSContext *ctx) final Pointer Function( Pointer ctx, ) jsNewObject = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, )>>('jsNewObject') .asFunction(); /// void jsFreeValue(JSContext *ctx, JSValue *val, int32_t free) final void Function( Pointer ctx, Pointer val, int free, ) _jsFreeValue = _qjsLib .lookup< NativeFunction< Void Function( Pointer, Pointer, Int32, )>>('jsFreeValue') .asFunction(); void jsFreeValue( Pointer ctx, Pointer val, { bool free = true, }) { _jsFreeValue(ctx, val, free ? 1 : 0); } /// void jsFreeValue(JSRuntime *rt, JSValue *val, int32_t free) final void Function( Pointer rt, Pointer val, int free, ) _jsFreeValueRT = _qjsLib .lookup< NativeFunction< Void Function( Pointer, Pointer, Int32, )>>('jsFreeValueRT') .asFunction(); void jsFreeValueRT( Pointer rt, Pointer val, { bool free = true, }) { _jsFreeValueRT(rt, val, free ? 1 : 0); } /// JSValue *jsDupValue(JSContext *ctx, JSValueConst *v) final Pointer Function( Pointer ctx, Pointer val, ) jsDupValue = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, )>>('jsDupValue') .asFunction(); /// JSValue *jsDupValueRT(JSRuntime *rt, JSValue *v) final Pointer Function( Pointer rt, Pointer val, ) jsDupValueRT = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, )>>('jsDupValueRT') .asFunction(); /// int32_t jsToBool(JSContext *ctx, JSValueConst *val) final int Function( Pointer ctx, Pointer val, ) jsToBool = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, Pointer, )>>('jsToBool') .asFunction(); /// int64_t jsToFloat64(JSContext *ctx, JSValueConst *val) final int Function( Pointer ctx, Pointer val, ) jsToInt64 = _qjsLib .lookup< NativeFunction< Int64 Function( Pointer, Pointer, )>>('jsToInt64') .asFunction(); /// double jsToFloat64(JSContext *ctx, JSValueConst *val) final double Function( Pointer ctx, Pointer val, ) jsToFloat64 = _qjsLib .lookup< NativeFunction< Double Function( Pointer, Pointer, )>>('jsToFloat64') .asFunction(); /// const char *jsToCString(JSContext *ctx, JSValue *val) final Pointer Function( Pointer ctx, Pointer val, ) _jsToCString = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, )>>('jsToCString') .asFunction(); /// void jsFreeCString(JSContext *ctx, const char *ptr) final void Function( Pointer ctx, Pointer val, ) jsFreeCString = _qjsLib .lookup< NativeFunction< Void Function( Pointer, Pointer, )>>('jsFreeCString') .asFunction(); String jsToCString( Pointer ctx, Pointer val, ) { final ptr = _jsToCString(ctx, val); if (ptr.address == 0) throw Exception('JSValue cannot convert to string'); final str = ptr.toDartString(); jsFreeCString(ctx, ptr); return str; } /// DLLEXPORT uint32_t jsNewClass(JSContext *ctx, const char *name) final int Function( Pointer ctx, Pointer name, ) _jsNewClass = _qjsLib .lookup< NativeFunction< Uint32 Function( Pointer, Pointer, )>>('jsNewClass') .asFunction(); int jsNewClass( Pointer ctx, String name, ) { final utf8name = name.toNativeUtf8(); final val = _jsNewClass( ctx, utf8name, ); malloc.free(utf8name); return val; } /// DLLEXPORT JSValue *jsNewObjectClass(JSContext *ctx, uint32_t QJSClassId, void *opaque) final Pointer Function( Pointer ctx, int classId, int opaque, ) jsNewObjectClass = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Uint32, IntPtr, )>>('jsNewObjectClass') .asFunction(); /// DLLEXPORT void *jsGetObjectOpaque(JSValue *obj, uint32_t classid) final int Function( Pointer obj, int classid, ) jsGetObjectOpaque = _qjsLib .lookup< NativeFunction< IntPtr Function( Pointer, Uint32, )>>('jsGetObjectOpaque') .asFunction(); /// uint8_t *jsGetArrayBuffer(JSContext *ctx, size_t *psize, JSValueConst *obj) final Pointer Function( Pointer ctx, Pointer psize, Pointer val, ) jsGetArrayBuffer = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, Pointer, )>>('jsGetArrayBuffer') .asFunction(); /// int32_t jsIsFunction(JSContext *ctx, JSValueConst *val) final int Function( Pointer ctx, Pointer val, ) jsIsFunction = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, Pointer, )>>('jsIsFunction') .asFunction(); /// int32_t jsIsPromise(JSContext *ctx, JSValueConst *val) final int Function( Pointer ctx, Pointer val, ) jsIsPromise = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, Pointer, )>>('jsIsPromise') .asFunction(); /// int32_t jsIsArray(JSContext *ctx, JSValueConst *val) final int Function( Pointer ctx, Pointer val, ) jsIsArray = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, Pointer, )>>('jsIsArray') .asFunction(); /// DLLEXPORT int32_t jsIsError(JSContext *ctx, JSValueConst *val); final int Function( Pointer ctx, Pointer val, ) jsIsError = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, Pointer, )>>('jsIsError') .asFunction(); /// DLLEXPORT JSValue *jsNewError(JSContext *ctx); final Pointer Function( Pointer ctx, ) jsNewError = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, )>>('jsNewError') .asFunction(); /// JSValue *jsGetProperty(JSContext *ctx, JSValueConst *this_obj, /// JSAtom prop) final Pointer Function( Pointer ctx, Pointer thisObj, int prop, ) jsGetProperty = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, Uint32, )>>('jsGetProperty') .asFunction(); /// int jsDefinePropertyValue(JSContext *ctx, JSValueConst *this_obj, /// JSAtom prop, JSValue *val, int flags) final int Function( Pointer ctx, Pointer thisObj, int prop, Pointer val, int flag, ) jsDefinePropertyValue = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, Pointer, Uint32, Pointer, Int32, )>>('jsDefinePropertyValue') .asFunction(); /// void jsFreeAtom(JSContext *ctx, JSAtom v) final void Function( Pointer ctx, int v, ) jsFreeAtom = _qjsLib .lookup< NativeFunction< Void Function( Pointer, Uint32, )>>('jsFreeAtom') .asFunction(); /// JSAtom jsValueToAtom(JSContext *ctx, JSValueConst *val) final int Function( Pointer ctx, Pointer val, ) jsValueToAtom = _qjsLib .lookup< NativeFunction< Uint32 Function( Pointer, Pointer, )>>('jsValueToAtom') .asFunction(); /// JSValue *jsAtomToValue(JSContext *ctx, JSAtom val) final Pointer Function( Pointer ctx, int val, ) jsAtomToValue = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Uint32, )>>('jsAtomToValue') .asFunction(); /// int jsGetOwnPropertyNames(JSContext *ctx, JSPropertyEnum **ptab, /// uint32_t *plen, JSValueConst *obj, int flags) final int Function( Pointer ctx, Pointer> ptab, Pointer plen, Pointer obj, int flags, ) jsGetOwnPropertyNames = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, Pointer>, Pointer, Pointer, Int32, )>>('jsGetOwnPropertyNames') .asFunction(); /// JSAtom jsPropertyEnumGetAtom(JSPropertyEnum *ptab, int i) final int Function( Pointer ptab, int i, ) jsPropertyEnumGetAtom = _qjsLib .lookup< NativeFunction< Uint32 Function( Pointer, Int32, )>>('jsPropertyEnumGetAtom') .asFunction(); /// uint32_t sizeOfJSValue() final int Function() _sizeOfJSValue = _qjsLib .lookup>('sizeOfJSValue') .asFunction(); final sizeOfJSValue = _sizeOfJSValue(); /// void setJSValueList(JSValue *list, int i, JSValue *val) final void Function( Pointer list, int i, Pointer val, ) setJSValueList = _qjsLib .lookup< NativeFunction< Void Function( Pointer, Uint32, Pointer, )>>('setJSValueList') .asFunction(); /// JSValue *jsCall(JSContext *ctx, JSValueConst *func_obj, JSValueConst *this_obj, /// int argc, JSValueConst *argv) final Pointer Function( Pointer ctx, Pointer funcObj, Pointer thisObj, int argc, Pointer argv, ) _jsCall = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, Pointer, Int32, Pointer, )>>('jsCall') .asFunction(); Pointer jsCall( Pointer ctx, Pointer funcObj, Pointer thisObj, List> argv, ) { final jsArgs = calloc( argv.length > 0 ? sizeOfJSValue * argv.length : 1, ).cast(); for (int i = 0; i < argv.length; ++i) { Pointer jsArg = argv[i]; setJSValueList(jsArgs, i, jsArg); } final func1 = jsDupValue(ctx, funcObj); final _thisObj = thisObj; final jsRet = _jsCall(ctx, funcObj, _thisObj, argv.length, jsArgs); jsFreeValue(ctx, func1); malloc.free(jsArgs); runtimeOpaques[jsGetRuntime(ctx)]?._port.sendPort.send(#call); return jsRet; } /// int jsIsException(JSValueConst *val) final int Function( Pointer val, ) jsIsException = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, )>>('jsIsException') .asFunction(); /// JSValue *jsGetException(JSContext *ctx) final Pointer Function( Pointer ctx, ) jsGetException = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, )>>('jsGetException') .asFunction(); /// int jsExecutePendingJob(JSRuntime *rt) final int Function( Pointer ctx, ) jsExecutePendingJob = _qjsLib .lookup< NativeFunction< Int32 Function( Pointer, )>>('jsExecutePendingJob') .asFunction(); /// JSValue *jsNewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs) final Pointer Function( Pointer ctx, Pointer resolvingFuncs, ) jsNewPromiseCapability = _qjsLib .lookup< NativeFunction< Pointer Function( Pointer, Pointer, )>>('jsNewPromiseCapability') .asFunction(); /// void jsFree(JSContext *ctx, void *ptab) final void Function( Pointer ctx, Pointer ptab, ) jsFree = _qjsLib .lookup< NativeFunction< Void Function( Pointer, Pointer, )>>('jsFree') .asFunction(); ================================================ FILE: lib/src/isolate.dart ================================================ /* * @Description: isolate * @Author: ekibun * @Date: 2020-10-02 13:49:03 * @LastEditors: ekibun * @LastEditTime: 2020-10-03 22:21:31 */ part of '../flutter_qjs.dart'; typedef dynamic _Decode(Map obj); List<_Decode> _decoders = [ JSError._decode, IsolateFunction._decode, ]; abstract class _IsolateEncodable { Map _encode(); } dynamic _encodeData(dynamic data, {Map? cache}) { if (cache == null) cache = Map(); if (cache.containsKey(data)) return cache[data]; if (data is Error || data is Exception) return _encodeData(JSError(data), cache: cache); if (data is _IsolateEncodable) return data._encode(); if (data is List) { final ret = []; cache[data] = ret; for (int i = 0; i < data.length; ++i) { ret.add(_encodeData(data[i], cache: cache)); } return ret; } if (data is Map) { final ret = {}; cache[data] = ret; for (final entry in data.entries) { ret[_encodeData(entry.key, cache: cache)] = _encodeData(entry.value, cache: cache); } return ret; } if (data is Future) { final futurePort = ReceivePort(); data.then((value) { futurePort.first.then((port) { futurePort.close(); (port as SendPort).send(_encodeData(value)); }); }, onError: (e) { futurePort.first.then((port) { futurePort.close(); (port as SendPort).send({#error: _encodeData(e)}); }); }); return { #jsFuturePort: futurePort.sendPort, }; } return data; } dynamic _decodeData(dynamic data, {Map? cache}) { if (cache == null) cache = Map(); if (cache.containsKey(data)) return cache[data]; if (data is List) { final ret = []; cache[data] = ret; for (int i = 0; i < data.length; ++i) { ret.add(_decodeData(data[i], cache: cache)); } return ret; } if (data is Map) { for (final decoder in _decoders) { final decodeObj = decoder(data); if (decodeObj != null) return decodeObj; } if (data.containsKey(#jsFuturePort)) { SendPort port = data[#jsFuturePort]; final futurePort = ReceivePort(); port.send(futurePort.sendPort); final futureCompleter = Completer(); futureCompleter.future.catchError((e) {}); futurePort.first.then((value) { futurePort.close(); if (value is Map && value.containsKey(#error)) { futureCompleter.completeError(_decodeData(value[#error])); } else { futureCompleter.complete(_decodeData(value)); } }); return futureCompleter.future; } final ret = {}; cache[data] = ret; for (final entry in data.entries) { ret[_decodeData(entry.key, cache: cache)] = _decodeData(entry.value, cache: cache); } return ret; } return data; } void _runJsIsolate(Map spawnMessage) async { SendPort sendPort = spawnMessage[#port]; ReceivePort port = ReceivePort(); sendPort.send(port.sendPort); final qjs = FlutterQjs( stackSize: spawnMessage[#stackSize], timeout: spawnMessage[#timeout], memoryLimit: spawnMessage[#memoryLimit], hostPromiseRejectionHandler: (reason) { sendPort.send({ #type: #hostPromiseRejection, #reason: _encodeData(reason), }); }, moduleHandler: (name) { final ptr = calloc>(); ptr.value = Pointer.fromAddress(ptr.address); sendPort.send({ #type: #module, #name: name, #ptr: ptr.address, }); while (ptr.value.address == ptr.address) sleep(Duration(microseconds: 1)); final ret = ptr.value; malloc.free(ptr); if (ret.address == -1) throw JSError('Module Not found'); final retString = ret.toDartString(); malloc.free(ret); return retString; }, ); port.listen((msg) async { var data; SendPort? msgPort = msg[#port]; try { switch (msg[#type]) { case #evaluate: data = await qjs.evaluate( msg[#command], name: msg[#name], evalFlags: msg[#flag], ); break; case #close: data = false; qjs.port.close(); qjs.close(); port.close(); data = true; break; } if (msgPort != null) msgPort.send(_encodeData(data)); } catch (e) { if (msgPort != null) msgPort.send({ #error: _encodeData(e), }); } }); await qjs.dispatch(); } typedef _JsAsyncModuleHandler = Future Function(String name); class IsolateQjs { Future? _sendPort; /// Max stack size for quickjs. final int? stackSize; /// Max stack size for quickjs. final int? timeout; /// Max memory for quickjs. final int? memoryLimit; /// Asynchronously handler to manage js module. final _JsAsyncModuleHandler? moduleHandler; /// Handler function to manage js module. final _JsHostPromiseRejectionHandler? hostPromiseRejectionHandler; /// Quickjs engine runing on isolate thread. /// /// Pass handlers to implement js-dart interaction and resolving modules. The `methodHandler` is /// used in isolate, so **the handler function must be a top-level function or a static method**. IsolateQjs({ this.moduleHandler, this.stackSize, this.timeout, this.memoryLimit, this.hostPromiseRejectionHandler, }); _ensureEngine() { if (_sendPort != null) return; ReceivePort port = ReceivePort(); Isolate.spawn( _runJsIsolate, { #port: port.sendPort, #stackSize: stackSize, #timeout: timeout, #memoryLimit: memoryLimit, }, errorsAreFatal: true, ); final completer = Completer(); port.listen((msg) async { if (msg is SendPort && !completer.isCompleted) { completer.complete(msg); return; } switch (msg[#type]) { case #hostPromiseRejection: try { final err = _decodeData(msg[#reason]); if (hostPromiseRejectionHandler != null) { hostPromiseRejectionHandler!(err); } else { print('unhandled promise rejection: $err'); } } catch (e) { print('host Promise Rejection Handler error: $e'); } break; case #module: final ptr = Pointer.fromAddress(msg[#ptr]); try { ptr.value = (await moduleHandler!(msg[#name])).toNativeUtf8(); } catch (e) { ptr.value = Pointer.fromAddress(-1); } break; } }, onDone: () { close(); if (!completer.isCompleted) completer.completeError(JSError('isolate close')); }); _sendPort = completer.future; } /// Free Runtime and close isolate thread that can be recreate when evaluate again. close() { final sendPort = _sendPort; _sendPort = null; if (sendPort == null) return; final ret = sendPort.then((sendPort) async { final closePort = ReceivePort(); sendPort.send({ #type: #close, #port: closePort.sendPort, }); final result = await closePort.first; closePort.close(); if (result is Map && result.containsKey(#error)) throw _decodeData(result[#error]); return _decodeData(result); }); return ret; } /// Evaluate js script. Future evaluate( String command, { String? name, int? evalFlags, }) async { _ensureEngine(); final evaluatePort = ReceivePort(); final sendPort = await _sendPort!; sendPort.send({ #type: #evaluate, #command: command, #name: name, #flag: evalFlags, #port: evaluatePort.sendPort, }); final result = await evaluatePort.first; evaluatePort.close(); if (result is Map && result.containsKey(#error)) throw _decodeData(result[#error]); return _decodeData(result); } } ================================================ FILE: lib/src/object.dart ================================================ /* * @Description: wrap object * @Author: ekibun * @Date: 2020-10-02 13:49:03 * @LastEditors: ekibun * @LastEditTime: 2020-10-03 22:21:31 */ part of '../flutter_qjs.dart'; /// js invokable abstract class JSInvokable extends JSRef { dynamic invoke(List args, [dynamic thisVal]); static dynamic _wrap(dynamic func) { return func is JSInvokable ? func : func is Function ? _DartFunction(func) : func; } } class _DartFunction extends JSInvokable { final Function _func; _DartFunction(this._func); @override invoke(List args, [thisVal]) { /// wrap this into function final passThis = RegExp('{.*thisVal.*}').hasMatch(_func.runtimeType.toString()); final ret = Function.apply(_func, args, passThis ? {#thisVal: thisVal} : null); JSRef.freeRecursive(args); JSRef.freeRecursive(thisVal); return ret; } @override String toString() { return _func.toString(); } @override destroy() {} } /// implement this to capture js object release. class _DartObject extends JSRef implements JSRefLeakable { Object? _obj; Pointer? _ctx; _DartObject(Pointer ctx, dynamic obj) { _ctx = ctx; _obj = obj; if (obj is JSRef) obj.dup(); runtimeOpaques[jsGetRuntime(ctx)]?.addRef(this); } static _DartObject? fromAddress(Pointer rt, int val) { return runtimeOpaques[rt]?.getRef((e) => identityHashCode(e) == val) as _DartObject?; } @override String toString() { if (_ctx == null) return "DartObject(released)"; return _obj.toString(); } @override void destroy() { final ctx = _ctx; final obj = _obj; _ctx = null; _obj = null; if (ctx == null) return; runtimeOpaques[jsGetRuntime(ctx)]?.removeRef(this); if (obj is JSRef) obj.free(); } } /// JS Error wrapper class JSError extends _IsolateEncodable { late String message; late String stack; JSError(message, [stack]) { if (message is JSError) { this.message = message.message; this.stack = message.stack; } else { this.message = message.toString(); this.stack = (stack ?? StackTrace.current).toString(); } } @override String toString() { return stack.isEmpty ? message.toString() : "$message\n$stack"; } static JSError? _decode(Map obj) { if (obj.containsKey(#jsError)) return JSError(obj[#jsError], obj[#jsErrorStack]); return null; } @override Map _encode() { return { #jsError: message, #jsErrorStack: stack, }; } } /// JS Object reference /// call [release] to release js object. class _JSObject extends JSRef { Pointer? _val; Pointer? _ctx; /// Create _JSObject(Pointer ctx, Pointer val) { this._ctx = ctx; final rt = jsGetRuntime(ctx); this._val = jsDupValue(ctx, val); runtimeOpaques[rt]?.addRef(this); } @override void destroy() { final ctx = _ctx; final val = _val; _val = null; _ctx = null; if (ctx == null || val == null) return; final rt = jsGetRuntime(ctx); runtimeOpaques[rt]?.removeRef(this); jsFreeValue(ctx, val); } @override String toString() { if (_ctx == null || _val == null) return "JSObject(released)"; return jsToCString(_ctx!, _val!); } } /// JS function wrapper class _JSFunction extends _JSObject implements JSInvokable, _IsolateEncodable { _JSFunction(Pointer ctx, Pointer val) : super(ctx, val); @override invoke(List arguments, [dynamic thisVal]) { final jsRet = _invoke(arguments, thisVal); final ctx = _ctx!; bool isException = jsIsException(jsRet) != 0; if (isException) { jsFreeValue(ctx, jsRet); throw _parseJSException(ctx); } final ret = _jsToDart(ctx, jsRet); jsFreeValue(ctx, jsRet); return ret; } Pointer _invoke(List arguments, [dynamic thisVal]) { final ctx = _ctx; final val = _val; if (ctx == null || val == null) throw JSError("InternalError: JSValue released"); final args = arguments .map( (e) => _dartToJs(ctx, e), ) .toList(); final jsThis = _dartToJs(ctx, thisVal); final jsRet = jsCall(ctx, val, jsThis, args); jsFreeValue(ctx, jsThis); for (final jsArg in args) { jsFreeValue(ctx, jsArg); } return jsRet; } @override Map _encode() { return IsolateFunction._new(this)._encode(); } } /// Dart function wrapper for isolate class IsolateFunction extends JSInvokable implements _IsolateEncodable { int? _isolateId; SendPort? _port; JSInvokable? _invokable; IsolateFunction._fromId(this._isolateId, this._port); IsolateFunction._new(this._invokable) { _handlers.add(this); } IsolateFunction(Function func) : this._new(_DartFunction(func)); static ReceivePort? _invokeHandler; static Set _handlers = Set(); static get _handlePort { if (_invokeHandler == null) { _invokeHandler = ReceivePort(); _invokeHandler!.listen((msg) async { final msgPort = msg[#port]; try { final handler = _handlers.firstWhereOrNull( (v) => identityHashCode(v) == msg[#handler], ); if (handler == null) throw JSError('handler released'); final ret = _encodeData(await handler._handle(msg[#msg])); if (msgPort != null) msgPort.send(ret); } catch (e) { final err = _encodeData(e); if (msgPort != null) msgPort.send({ #error: err, }); } }); } return _invokeHandler!.sendPort; } _send(msg) async { final port = _port; if (port == null) return _handle(msg); final evaluatePort = ReceivePort(); port.send({ #handler: _isolateId, #msg: msg, #port: evaluatePort.sendPort, }); final result = await evaluatePort.first; if (result is Map && result.containsKey(#error)) throw _decodeData(result[#error]); return _decodeData(result); } _destroy() { _handlers.remove(this); _invokable?.free(); _invokable = null; } _handle(msg) async { switch (msg) { case #dup: _refCount++; return null; case #free: _refCount--; if (_refCount < 0) _destroy(); return null; case #destroy: _destroy(); return null; } final List args = _decodeData(msg[#args]); final thisVal = _decodeData(msg[#thisVal]); return _invokable?.invoke(args, thisVal); } @override Future invoke(List positionalArguments, [thisVal]) async { final List dArgs = _encodeData(positionalArguments); final dThisVal = _encodeData(thisVal); return _send({ #args: dArgs, #thisVal: dThisVal, }); } static IsolateFunction? _decode(Map obj) { if (obj.containsKey(#jsFunctionPort)) return IsolateFunction._fromId( obj[#jsFunctionId], obj[#jsFunctionPort], ); return null; } @override Map _encode() { return { #jsFunctionId: _isolateId ?? identityHashCode(this), #jsFunctionPort: _port ?? IsolateFunction._handlePort, }; } int _refCount = 0; @override dup() { _send(#dup); } @override free() { _send(#free); } @override void destroy() { _send(#destroy); } } ================================================ FILE: lib/src/wrapper.dart ================================================ /* * @Description: wrapper * @Author: ekibun * @Date: 2020-09-19 22:07:47 * @LastEditors: ekibun * @LastEditTime: 2020-12-02 11:14:03 */ part of '../flutter_qjs.dart'; dynamic _parseJSException(Pointer ctx, [Pointer? perr]) { final e = perr ?? jsGetException(ctx); var err; try { err = _jsToDart(ctx, e); } catch (exception) { err = exception; } if (perr == null) jsFreeValue(ctx, e); return err; } void _definePropertyValue( Pointer ctx, Pointer obj, dynamic key, dynamic val, { Map>? cache, }) { final jsAtomVal = _dartToJs(ctx, key, cache: cache); final jsAtom = jsValueToAtom(ctx, jsAtomVal); jsDefinePropertyValue( ctx, obj, jsAtom, _dartToJs(ctx, val, cache: cache), JSProp.C_W_E, ); jsFreeAtom(ctx, jsAtom); jsFreeValue(ctx, jsAtomVal); } Pointer _jsGetPropertyValue( Pointer ctx, Pointer obj, dynamic key, { Map>? cache, }) { final jsAtomVal = _dartToJs(ctx, key, cache: cache); final jsAtom = jsValueToAtom(ctx, jsAtomVal); final jsProp = jsGetProperty(ctx, obj, jsAtom); jsFreeAtom(ctx, jsAtom); jsFreeValue(ctx, jsAtomVal); return jsProp; } Pointer _dartToJs(Pointer ctx, dynamic val, {Map>? cache}) { if (val == null) return jsUNDEFINED(); if (val is Error) return _dartToJs(ctx, JSError(val, val.stackTrace)); if (val is Exception) return _dartToJs(ctx, JSError(val)); if (val is JSError) { final ret = jsNewError(ctx); _definePropertyValue(ctx, ret, "name", ""); _definePropertyValue(ctx, ret, "message", val.message); _definePropertyValue(ctx, ret, "stack", val.stack); return ret; } if (val is _JSObject) return jsDupValue(ctx, val._val!); if (val is Future) { final resolvingFunc = malloc(sizeOfJSValue * 2).cast(); final resolvingFunc2 = Pointer.fromAddress(resolvingFunc.address + sizeOfJSValue); final ret = jsNewPromiseCapability(ctx, resolvingFunc); final _JSFunction res = _jsToDart(ctx, resolvingFunc); final _JSFunction rej = _jsToDart(ctx, resolvingFunc2); jsFreeValue(ctx, resolvingFunc, free: false); jsFreeValue(ctx, resolvingFunc2, free: false); malloc.free(resolvingFunc); final refRes = _DartObject(ctx, res); final refRej = _DartObject(ctx, rej); res.free(); rej.free(); val.then((value) { res.invoke([value]); }, onError: (e) { rej.invoke([e]); }).whenComplete(() { refRes.free(); refRej.free(); }); return ret; } if (cache == null) cache = Map(); if (val is bool) return jsNewBool(ctx, val ? 1 : 0); if (val is int) return jsNewInt64(ctx, val); if (val is double) return jsNewFloat64(ctx, val); if (val is String) return jsNewString(ctx, val); if (val is Uint8List) { final ptr = malloc(val.length); final byteList = ptr.asTypedList(val.length); byteList.setAll(0, val); final ret = jsNewArrayBufferCopy(ctx, ptr, val.length); malloc.free(ptr); return ret; } if (cache.containsKey(val)) { return jsDupValue(ctx, cache[val]!); } if (val is List) { final ret = jsNewArray(ctx); cache[val] = ret; for (int i = 0; i < val.length; ++i) { _definePropertyValue(ctx, ret, i, val[i], cache: cache); } return ret; } if (val is Map) { final ret = jsNewObject(ctx); cache[val] = ret; for (MapEntry entry in val.entries) { _definePropertyValue(ctx, ret, entry.key, entry.value, cache: cache); } return ret; } // wrap Function to JSInvokable final valWrap = JSInvokable._wrap(val); final dartObjectClassId = runtimeOpaques[jsGetRuntime(ctx)]?.dartObjectClassId ?? 0; if (dartObjectClassId == 0) return jsUNDEFINED(); final dartObject = jsNewObjectClass( ctx, dartObjectClassId, identityHashCode(_DartObject(ctx, valWrap)), ); if (valWrap is JSInvokable) { final ret = jsNewCFunction(ctx, dartObject); jsFreeValue(ctx, dartObject); return ret; } return dartObject; } dynamic _jsToDart(Pointer ctx, Pointer val, {Map? cache}) { if (cache == null) cache = Map(); final tag = jsValueGetTag(val); if (jsTagIsFloat64(tag) != 0) { return jsToFloat64(ctx, val); } switch (tag) { case JSTag.BOOL: return jsToBool(ctx, val) != 0; case JSTag.INT: return jsToInt64(ctx, val); case JSTag.STRING: return jsToCString(ctx, val); case JSTag.OBJECT: final rt = jsGetRuntime(ctx); final dartObjectClassId = runtimeOpaques[rt]?.dartObjectClassId; if (dartObjectClassId != null) { final dartObject = _DartObject.fromAddress( rt, jsGetObjectOpaque(val, dartObjectClassId)); if (dartObject != null) return dartObject._obj; } final psize = malloc(); final buf = jsGetArrayBuffer(ctx, psize, val); final size = psize.value; malloc.free(psize); if (buf.address != 0) { return Uint8List.fromList(buf.asTypedList(size)); } final valptr = jsValueGetPtr(val); if (cache.containsKey(valptr)) { return cache[valptr]; } if (jsIsFunction(ctx, val) != 0) { return _JSFunction(ctx, val); } else if (jsIsError(ctx, val) != 0) { final err = jsToCString(ctx, val); final pstack = _jsGetPropertyValue(ctx, val, 'stack'); final stack = jsToBool(ctx, pstack) != 0 ? jsToCString(ctx, pstack) : null; jsFreeValue(ctx, pstack); return JSError(err, stack); } else if (jsIsPromise(ctx, val) != 0) { final jsPromiseThen = _jsGetPropertyValue(ctx, val, 'then'); final _JSFunction promiseThen = _jsToDart(ctx, jsPromiseThen, cache: cache); jsFreeValue(ctx, jsPromiseThen); final completer = Completer(); completer.future.catchError((e) {}); final jsPromise = _JSObject(ctx, val); final jsRet = promiseThen._invoke([ (v) { JSRef.dupRecursive(v); if (!completer.isCompleted) completer.complete(v); }, (e) { JSRef.dupRecursive(e); if (!completer.isCompleted) completer.completeError(e); }, ], jsPromise); jsPromise.free(); promiseThen.free(); final isException = jsIsException(jsRet) != 0; jsFreeValue(ctx, jsRet); if (isException) throw _parseJSException(ctx); return completer.future; } else if (jsIsArray(ctx, val) != 0) { final jslength = _jsGetPropertyValue(ctx, val, 'length'); final length = jsToInt64(ctx, jslength); final ret = []; cache[valptr] = ret; for (var i = 0; i < length; ++i) { final jsProp = _jsGetPropertyValue(ctx, val, i); ret.add(_jsToDart(ctx, jsProp, cache: cache)); jsFreeValue(ctx, jsProp); } return ret; } else { final ptab = malloc>(); final plen = malloc(); if (jsGetOwnPropertyNames(ctx, ptab, plen, val, -1) != 0) { malloc.free(plen); malloc.free(ptab); return null; } final len = plen.value; malloc.free(plen); final ret = Map(); cache[valptr] = ret; for (var i = 0; i < len; ++i) { final jsAtom = jsPropertyEnumGetAtom(ptab.value, i); final jsAtomValue = jsAtomToValue(ctx, jsAtom); final jsProp = jsGetProperty(ctx, val, jsAtom); ret[_jsToDart(ctx, jsAtomValue, cache: cache)] = _jsToDart(ctx, jsProp, cache: cache); jsFreeValue(ctx, jsAtomValue); jsFreeValue(ctx, jsProp); jsFreeAtom(ctx, jsAtom); } jsFree(ctx, ptab.value); malloc.free(ptab); return ret; } default: } return null; } ================================================ FILE: linux/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.10) include("${CMAKE_CURRENT_SOURCE_DIR}/../cxx/quickjs.cmake") target_compile_options(quickjs PRIVATE "-fPIC") set(PROJECT_NAME "flutter_qjs") project(${PROJECT_NAME} LANGUAGES CXX) set(PLUGIN_NAME "${PROJECT_NAME}_plugin") add_library(${PLUGIN_NAME} SHARED "${PLUGIN_NAME}.cc" "${CXX_LIB_DIR}/ffi.cpp" ) apply_standard_settings(${PLUGIN_NAME}) target_compile_features(${PLUGIN_NAME} PUBLIC cxx_std_17) set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) target_link_libraries(${PLUGIN_NAME} PRIVATE quickjs) target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) # List of absolute paths to libraries that should be bundled with the plugin set(flutter_qjs_bundled_libraries "" PARENT_SCOPE ) ================================================ FILE: linux/flutter_qjs_plugin.cc ================================================ /* * @Description: * @Author: ekibun * @Date: 2020-08-17 21:37:11 * @LastEditors: ekibun * @LastEditTime: 2020-09-21 18:28:35 */ #include "include/flutter_qjs/flutter_qjs_plugin.h" #include #include #define FLUTTER_QJS_PLUGIN(obj) \ (G_TYPE_CHECK_INSTANCE_CAST((obj), flutter_qjs_plugin_get_type(), \ FlutterQjsPlugin)) struct _FlutterQjsPlugin { GObject parent_instance; }; G_DEFINE_TYPE(FlutterQjsPlugin, flutter_qjs_plugin, g_object_get_type()) static void flutter_qjs_plugin_dispose(GObject *object) { G_OBJECT_CLASS(flutter_qjs_plugin_parent_class)->dispose(object); } static void flutter_qjs_plugin_class_init(FlutterQjsPluginClass *klass) { G_OBJECT_CLASS(klass)->dispose = flutter_qjs_plugin_dispose; } static void flutter_qjs_plugin_init(FlutterQjsPlugin *self) {} void flutter_qjs_plugin_register_with_registrar(FlPluginRegistrar *registrar) { } ================================================ FILE: linux/include/flutter_qjs/flutter_qjs_plugin.h ================================================ #ifndef FLUTTER_PLUGIN_FLUTTER_QJS_PLUGIN_H_ #define FLUTTER_PLUGIN_FLUTTER_QJS_PLUGIN_H_ #include G_BEGIN_DECLS #ifdef FLUTTER_PLUGIN_IMPL #define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) #else #define FLUTTER_PLUGIN_EXPORT #endif typedef struct _FlutterQjsPlugin FlutterQjsPlugin; typedef struct { GObjectClass parent_class; } FlutterQjsPluginClass; FLUTTER_PLUGIN_EXPORT GType flutter_qjs_plugin_get_type(); FLUTTER_PLUGIN_EXPORT void flutter_qjs_plugin_register_with_registrar( FlPluginRegistrar* registrar); G_END_DECLS #endif // FLUTTER_PLUGIN_FLUTTER_QJS_PLUGIN_H_ ================================================ FILE: macos/Classes/FlutterQjsPlugin.swift ================================================ import Cocoa import FlutterMacOS public class FlutterQjsPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "flutter_qjs", binaryMessenger: registrar.messenger) let instance = FlutterQjsPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { switch call.method { case "getPlatformVersion": result("macOS " + ProcessInfo.processInfo.operatingSystemVersionString) default: result(FlutterMethodNotImplemented) } } } ================================================ FILE: macos/flutter_qjs.podspec ================================================ # # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html. # Run `pod lib lint flutter_qjs.podspec' to validate before publishing. # Pod::Spec.new do |s| s.name = 'flutter_qjs' s.version = '0.0.1' s.summary = 'A quickjs engine for flutter.' s.description = <<-DESC This plugin is a simple js engine for flutter using the `quickjs` project. Plugin currently supports all the platforms except web! DESC s.homepage = 'https://github.com/ekibun/flutter_qjs' s.license = { :file => '../LICENSE' } s.author = { 'ekibun' => 'soekibun@gmail.com' } s.source = { :path => '.' } s.compiler_flags = '-DDUMP_LEAKS' s.source_files = ['Classes/**/*', 'cxx/*.{c,cpp}'] s.dependency 'FlutterMacOS' s.platform = :osx, '10.11' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.vendored_libraries = 'build/Debug/libffiquickjs.dylib' s.prepare_command = 'sh ../cxx/prebuild.sh' s.swift_version = '5.0' end ================================================ FILE: pubspec.yaml ================================================ name: flutter_qjs description: This plugin is a simple js engine for flutter using the `quickjs` project. Plugin currently supports all the platforms except web! version: 0.3.7 homepage: https://github.com/ekibun/flutter_qjs environment: sdk: ">=2.12.0-0 <3.0.0" flutter: ">=1.20.0" dependencies: flutter: sdk: flutter ffi: ^1.0.0 dev_dependencies: flutter_test: sdk: flutter flutter_tools: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter. flutter: # This section identifies this Flutter project as a plugin project. # The 'pluginClass' and Android 'package' identifiers should not ordinarily # be modified. They are used by the tooling to maintain consistency when # adding or updating assets for this project. plugin: implements: flutter_qjs platforms: # This plugin project was generated without specifying any # platforms with the `--platform` argument. If you see the `fake_platform` map below, remove it and # then add platforms following the instruction here: # https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms # ------------------- windows: pluginClass: FlutterQjsPlugin linux: pluginClass: FlutterQjsPlugin android: pluginClass: FlutterQjsPlugin package: soko.ekibun.flutter_qjs macos: pluginClass: FlutterQjsPlugin ios: pluginClass: FlutterQjsPlugin # ------------------- # To add assets to your plugin package, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # # For details regarding assets in packages, see # https://flutter.dev/assets-and-images/#from-packages # # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # To add custom fonts to your plugin package, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts in packages, see # https://flutter.dev/custom-fonts/#from-packages ================================================ FILE: test/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.7 FATAL_ERROR) project(ffiquickjs LANGUAGES CXX) include("${CMAKE_CURRENT_SOURCE_DIR}/../cxx/quickjs.cmake") IF (CMAKE_SYSTEM_NAME MATCHES "Linux") target_compile_options(quickjs PRIVATE "-fPIC") ENDIF () add_library(ffiquickjs SHARED ${CXX_LIB_DIR}/ffi.cpp) target_compile_features(ffiquickjs PUBLIC cxx_std_17) target_link_libraries(ffiquickjs PRIVATE quickjs) ================================================ FILE: test/flutter_qjs_test.dart ================================================ /* * @Description: unit test * @Author: ekibun * @Date: 2020-09-06 13:02:46 * @LastEditors: ekibun * @LastEditTime: 2020-10-07 00:11:27 */ import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter_qjs/flutter_qjs.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/terminal.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/windows/visual_studio.dart'; import 'package:file/local.dart'; import 'package:process/process.dart'; dynamic myFunction(String args, {thisVal}) { return [thisVal, args]; } Future testEvaluate(qjs) async { dynamic wrapFunction = await qjs.evaluate( 'async (a) => a', name: '', ); dynamic testWrap = await wrapFunction.invoke([wrapFunction]); await wrapFunction.free(); final wrapNull = await testWrap.invoke([null]); expect(wrapNull, null, reason: 'wrap null'); final primities = [0, 1, 0.1, true, false, 'str']; final wrapPrimities = await testWrap.invoke([primities]); for (int i = 0; i < primities.length; i++) { expect(wrapPrimities[i], primities[i], reason: 'wrap primities'); } final jsError = JSError('test Error'); final wrapJsError = await testWrap.invoke([jsError]); expect(jsError.message, (wrapJsError as JSError).message, reason: 'wrap JSError'); expect(wrapNull, null, reason: 'wrap null'); final a = {}; a['a'] = a; final wrapA = await testWrap.invoke([a]); expect(wrapA['a'], wrapA, reason: 'recursive object'); dynamic testThis = await qjs.evaluate( '(function (func, arg) { return func.call(this, arg) })', name: '', ); final funcRet = await testThis.invoke([myFunction, 'arg'], {'name': 'this'}); testThis.free(); expect(funcRet[0]['name'], 'this', reason: 'js function this'); expect(funcRet[1], 'arg', reason: 'js function argument'); List promises = await testWrap.invoke([ await qjs.evaluate( '[Promise.reject("reject"), Promise.resolve("resolve"), new Promise(() => {})]', name: '', ) ]); await testWrap.free(); for (final promise in promises) expect(promise, isInstanceOf(), reason: 'promise object'); try { await promises[0]; throw 'Future not reject'; } catch (e) { expect(e, 'reject', reason: 'promise object reject'); } expect(await promises[1], 'resolve', reason: 'promise object resolve'); } void main() async { test('make', () async { const platform = LocalPlatform(); final utf8Encoding = Encoding.getByName('utf-8'); String cmakePath = 'cmake'; if (platform.isWindows) { final stdio = Stdio(); final vs = VisualStudio( fileSystem: const LocalFileSystem(), processManager: const LocalProcessManager(), platform: platform, logger: StdoutLogger( terminal: AnsiTerminal( stdio: stdio, platform: platform, ), stdio: stdio, outputPreferences: OutputPreferences( wrapText: stdio.hasTerminal, showColor: platform.stdoutSupportsAnsi, stdio: stdio, ), )); cmakePath = vs.cmakePath!; } final buildDir = './build'; var result = Process.runSync( cmakePath, ['-S', './', '-B', buildDir], workingDirectory: 'test', stdoutEncoding: utf8Encoding, stderrEncoding: utf8Encoding, ); stdout.write(result.stdout); stderr.write(result.stderr); expect(result.exitCode, 0); result = Process.runSync( cmakePath, ['--build', buildDir, '--verbose'], workingDirectory: 'test', stdoutEncoding: utf8Encoding, stderrEncoding: utf8Encoding, ); stdout.write(result.stdout); stderr.write(result.stderr); expect(result.exitCode, 0); }); test('infinite loop', () async { final qjs = FlutterQjs( timeout: 1000, ); qjs.dispatch(); var result = await qjs.evaluate('1'); expect(result, 1, reason: 'eval module'); try { await qjs.evaluate('while(true) {}'); throw 'Error not throw'; } on JSError catch (e) { expect(e.message, startsWith('InternalError: interrupted'), reason: 'throw interrupted'); } await qjs.close(); }); test('memory leak', () async { final qjs = FlutterQjs( memoryLimit: 1000000, ); qjs.dispatch(); try { await qjs.evaluate('new Array(1000000).fill(0)'); throw 'Error not throw'; } on JSError catch (e) { expect(e.message, startsWith('InternalError: out of memory'), reason: 'throw interrupted'); } await qjs.close(); }); test('module', () async { final qjs = IsolateQjs( moduleHandler: (name) async { return 'export default "test module"'; }, ); await qjs.evaluate(''' import handlerData from 'test'; export default { data: handlerData }; ''', name: 'evalModule', evalFlags: JSEvalFlag.MODULE); var result = await qjs.evaluate('import("evalModule")'); expect(result['default']['data'], 'test module', reason: 'eval module'); await qjs.close(); }); test('data conversion', () async { final qjs = FlutterQjs( hostPromiseRejectionHandler: (_) {}, ); qjs.dispatch(); await testEvaluate(qjs); await qjs.close(); }); test('isolate conversion', () async { final qjs = IsolateQjs( hostPromiseRejectionHandler: (_) {}, ); await testEvaluate(qjs); await qjs.close(); }); test('isolate bind this', () async { final qjs = IsolateQjs(); JSInvokable? localVar; JSInvokable setToGlobal = await qjs .evaluate('(name, func)=>{ this[name] = func }', name: ''); final func = IsolateFunction((args) { localVar = args..dup(); return args.invoke([]); }); await setToGlobal.invoke(["test", func..dup()]); func.free(); setToGlobal.free(); final testFuncRet = await qjs.evaluate('test(()=>"ret")', name: ''); expect(await localVar?.invoke([]), 'ret', reason: 'bind function'); localVar?.free(); expect(testFuncRet, 'ret', reason: 'bind function args return'); await qjs.close(); }); test('reference leak', () async { final qjs = FlutterQjs(); await qjs.evaluate('()=>{}', name: ''); try { qjs.close(); throw 'Error not throw'; } on JSError catch (e) { expect(e.message, startsWith('reference leak:'), reason: 'throw reference leak'); } }); test('stack overflow', () async { final qjs = FlutterQjs(); try { qjs.evaluate('a=()=>a();a();', name: ''); throw 'Error not throw'; } on JSError catch (e) { expect(e.message, 'InternalError: stack overflow', reason: 'throw stack overflow'); } qjs.close(); }); test('host promise rejection', () async { final completer = Completer(); final qjs = FlutterQjs( hostPromiseRejectionHandler: (reason) { completer.complete(reason); }, ); qjs.dispatch(); qjs.evaluate( '(() => { Promise.resolve().then(() => { throw "unhandle" }) })()', name: ''); Future.delayed(Duration(seconds: 10)).then((value) { if (!completer.isCompleted) completer.completeError('not host reject'); }); expect(await completer.future, 'unhandle', reason: 'host promise rejection'); qjs.close(); }); } ================================================ FILE: windows/.gitignore ================================================ flutter/ # Visual Studio user-specific files. *.suo *.user *.userosscache *.sln.docstates # Visual Studio build-related files. x64/ x86/ # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ ================================================ FILE: windows/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.15) include("${CMAKE_CURRENT_SOURCE_DIR}/../cxx/quickjs.cmake") set(PROJECT_NAME "flutter_qjs") project(${PROJECT_NAME} LANGUAGES CXX) add_compile_options("$<$:/utf-8>") set(PLUGIN_NAME "${PROJECT_NAME}_plugin") add_library(${PLUGIN_NAME} SHARED "${PLUGIN_NAME}.cpp" "${CXX_LIB_DIR}/ffi.cpp" ) apply_standard_settings(${PLUGIN_NAME}) set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin quickjs) # List of absolute paths to libraries that should be bundled with the plugin set(flutter_qjs_bundled_libraries "" PARENT_SCOPE ) ================================================ FILE: windows/flutter_qjs_plugin.cpp ================================================ /* * @Description: empty plugin * @Author: ekibun * @Date: 2020-08-25 21:09:20 * @LastEditors: ekibun * @LastEditTime: 2020-09-20 16:00:15 */ #include "include/flutter_qjs/flutter_qjs_plugin.h" // This must be included before many other Windows headers. #include #include namespace { class FlutterQjsPlugin : public flutter::Plugin { public: static void RegisterWithRegistrar(flutter::PluginRegistrarWindows *registrar); FlutterQjsPlugin(); virtual ~FlutterQjsPlugin(); }; // static void FlutterQjsPlugin::RegisterWithRegistrar( flutter::PluginRegistrarWindows *registrar) {} FlutterQjsPlugin::FlutterQjsPlugin() {} FlutterQjsPlugin::~FlutterQjsPlugin() {} } // namespace void FlutterQjsPluginRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { FlutterQjsPlugin::RegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar)); } ================================================ FILE: windows/include/flutter_qjs/flutter_qjs_plugin.h ================================================ #ifndef FLUTTER_PLUGIN_FLUTTER_QJS_PLUGIN_H_ #define FLUTTER_PLUGIN_FLUTTER_QJS_PLUGIN_H_ #include #ifdef FLUTTER_PLUGIN_IMPL #define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) #else #define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) #endif #if defined(__cplusplus) extern "C" { #endif FLUTTER_PLUGIN_EXPORT void FlutterQjsPluginRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar); #if defined(__cplusplus) } // extern "C" #endif #endif // FLUTTER_PLUGIN_FLUTTER_QJS_PLUGIN_H_