Skip to content

Commit

Permalink
Merge pull request #415 from cunarist/guide-web-headers
Browse files Browse the repository at this point in the history
guide users about flutter web headers
  • Loading branch information
temeddix authored Sep 7, 2024
2 parents 5f9b00c + 84a60af commit c709f9e
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 145 deletions.
2 changes: 1 addition & 1 deletion documentation/docs/messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,6 @@ while let Some(dart_signal) = receiver.recv().await {
`[RINF:RUST-ATTRIBUTE(...)]` writes an attribute above the generated message struct in Rust. This is useful when you want to automatically implement a trait for the message struct in Rust.

```proto title="Protobuf"
// [RINF:RUST-ATTRIBUTE(#[derive(Copy)])]
// [RINF:RUST-ATTRIBUTE(#[derive(Hash)])]
message MyDataInput { ... }
```
40 changes: 28 additions & 12 deletions flutter_ffi_plugin/bin/src/helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -247,18 +247,6 @@ Future<void> buildWebassembly({bool isReleaseMode = false}) async {
print("Skipping ensurement of Rust toolchain for the web.");
}

// Patch Flutter SDK web server's response headers.
try {
await patchServerHeaders();
print("Patched Flutter SDK's web server with CORS HTTP headers.");
} catch (error) {
print("Failed patching Flutter's web server with CORS HTTP headers.");
print("Try using the command below.");
print('flutter run' +
' --web-header=Cross-Origin-Opener-Policy=same-origin' +
' --web-header=Cross-Origin-Embedder-Policy=require-corp');
}

// Prepare the webassembly output path.
final flutterProjectPath = Directory.current;
final subPath = 'web/pkg/';
Expand Down Expand Up @@ -292,5 +280,33 @@ Future<void> buildWebassembly({bool isReleaseMode = false}) async {
}
print("Saved `.wasm` and `.js` files to `$subPath`.");

// Guide the developer how to run Flutter web server with web headers.
print("To run the Flutter web server, use:");
final commandLineDivider = await getCommandLineDivider();
final commandLines = [
'flutter run',
'--web-header=Cross-Origin-Opener-Policy=same-origin',
'--web-header=Cross-Origin-Embedder-Policy=require-corp'
];
print(commandLines.join(" ${commandLineDivider}\n"));

print("🎉 Webassembly module is now ready! 🎉");
}

Future<String> getCommandLineDivider({bool isReleaseMode = false}) async {
if (Platform.isWindows) {
// Windows environment, check further for PowerShell or CMD
if (Platform.environment['SHELL'] == null) {
// Likely PowerShell environment
return "`";
// // Likely Command Prompt (cmd.exe)
// return "^";
} else {
// Bash or some other shell
return "\\";
}
} else {
// Bash or some other shell
return "\\";
}
}
54 changes: 0 additions & 54 deletions flutter_ffi_plugin/bin/src/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -572,60 +572,6 @@ void assignRustSignal(int messageId, Uint8List messageBytes, Uint8List binary) {
}
}

Future<void> patchServerHeaders() async {
// Get the Flutter executable's path.
final Uri rawPath;
if (Platform.isWindows) {
// Windows
final output = await Process.run('where', ['flutter']);
rawPath = Uri.file((output.stdout as String).split('\n').first.trim());
} else {
// macOS and Linux
final output = await Process.run('which', ['flutter']);
rawPath = Uri.file((output.stdout as String).trim());
}
final flutterFilePath = Uri.file(
await File.fromUri(rawPath).resolveSymbolicLinks(),
);
final flutterPath = File.fromUri(flutterFilePath).parent.parent.uri;

// Get the server module file's path.
final serverFile = File.fromUri(
flutterPath.join('packages/flutter_tools/lib/src/isolated/devfs_web.dart'),
);
var serverFileContent = await serverFile.readAsString();

// Check if the server already includes cross-origin HTTP headers.
if (serverFileContent.contains('Cross-Origin-Opener-Policy')) {
return;
}

// Add the HTTP header code to the server file.
final lines = serverFileContent.split('\n');
final serverDeclaredIndex = lines.lastIndexWhere(
(line) => line.contains('httpServer = await'),
);
lines.insert(serverDeclaredIndex + 1, """
httpServer.defaultResponseHeaders.add(
'Cross-Origin-Opener-Policy',
'same-origin',
);
httpServer.defaultResponseHeaders.add(
'Cross-Origin-Embedder-Policy',
'require-corp',
);""");
serverFileContent = lines.join("\n");
await serverFile.writeAsString(serverFileContent);

// Remove the stamp file to make it re-generated.
final flutterToolsStampPath = flutterPath.join(
'bin/cache/flutter_tools.stamp',
);
if (await File.fromUri(flutterToolsStampPath).exists()) {
await File.fromUri(flutterToolsStampPath).delete();
}
}

Future<void> watchAndGenerateMessageCode(
{required RinfConfigMessage messageConfig}) async {
final currentDirectory = Directory.current;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ message SampleOutput {
}
}

// [RINF:RUST-ATTRIBUTE(#[derive(Copy)])]
// [RINF:RUST-ATTRIBUTE(#[derive(Hash)])]
message WithRustAttribute {
bool dummy = 1;
}
4 changes: 2 additions & 2 deletions flutter_ffi_plugin/example/native/hub/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ crate-type = ["lib", "cdylib", "staticlib"]
rinf = "6.15.0"
prost = "0.13.0"
tokio = { version = "1", features = ["rt", "sync", "macros", "time"] }
tokio_with_wasm = { version = "0.6.1", features = [
tokio_with_wasm = { version = "0.6.3", features = [
"rt",
"sync",
"macros",
"time",
] }
wasm-bindgen = "0.2.92"
wasm-bindgen = "0.2.93"
sample_crate = { path = "../sample_crate" }
76 changes: 1 addition & 75 deletions flutter_ffi_plugin/example/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,98 +1,24 @@
name: example_app
description: Demonstrates how to use the rinf plugin.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: "none" # Remove this line if you wish to publish to pub.dev
publish_to: "none"

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 0.1.0

environment:
sdk: ">=3.0.5 <4.0.0"

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter

rinf:
# When depending on this package from a real application you should use:
# rinf: ^x.y.z
# See https://dart.dev/tools/pub/dependencies#version-constraints
# The example app is bundled with the plugin so we use a path dependency on
# the parent directory to use the current plugin's version.
path: ../

# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2

protobuf: ^3.1.0

dev_dependencies:
flutter_test:
sdk: flutter

# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^4.0.0

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true

# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg

# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware

# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages

# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages

0 comments on commit c709f9e

Please sign in to comment.