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