Skip to content

Commit

Permalink
Merge pull request #287 from cunarist/organize-interface
Browse files Browse the repository at this point in the history
Organize interface code
  • Loading branch information
temeddix authored Feb 1, 2024
2 parents f7085a3 + b338b41 commit 310cbb5
Show file tree
Hide file tree
Showing 26 changed files with 341 additions and 337 deletions.
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,7 @@ All the message classes and structs are generated by Rinf. You can simply define
- **Minimal**: This is not a bulky framework that requires you to install so many dependencies and use complicated CLI commands. Just focus on your code using your preferred Flutter and Rust libraries.
- **Scalable**: Creating hundreds or even thousands of message APIs between Dart and Rust feels smooth and clean. Additionally, you have the flexibility to utilize any number of Rust library crates, perhaps including those you might have been working on.
- **High-level interface**: No messing with sensitive build files, no concerns about memory safety. Stay with Dart and Rust that you're familiar with.
- **Low-level control**: Though the hard things are kept beneath the surface, you are free to modify the underlying logic such as concurrency or debugging features. There is no hidden mechanism that prevents your understanding.
- **Well maintained**: Our [automated workflows](https://github.com/cunarist/rinf/actions) including build tests are always kept passing, thanks to the main branch protection rule. Also, the number of external dependencies is kept as low as possible and documentations are thoughtfully organized.
- **Async interaction**: Rust operations will never block Flutter's main thread because they are spawned in a separate thread pool.
- **Convenient debugging**: All the debugging functionalities are provided by default, without the need for dealing with browsers or mobile emulators. Also, the whole Rust logic is automatically restarted on Dart's hot restart.
- **Reliable**: Each component is supported by huge communities, ensuring a strong emphasis on future safety. You can easily assure your team of stability since this framework's underlying concept is fairly simple.

Expand Down
2 changes: 1 addition & 1 deletion documentation/docs/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ Let's listen to this message in Rust. This simple function will add one to each

```rust title="native/hub/src/sample_functions.rs"
...
use crate::debug_print;
use crate::messages;
use rinf::debug_print;
...
pub async fn calculate_precious_data() {
use messages::tutorial_resource::*;
Expand Down
6 changes: 3 additions & 3 deletions documentation/docs/writing-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,15 @@ You might be used to `println!` macro in Rust. However, using that macro isn't a
When writing Rust code in the `hub` crate, you can simply print your debug message with the `debug_print!` macro provided by this framework like below. Once you use this macro, Flutter will take care of the rest.

```rust title="Rust"
use crate::debug_print;
use rinf::debug_print;
debug_print!("My object is {my_object:?}");
```

`debug_print!` is also better than `println!` because it only works in debug mode, resulting in a smaller and cleaner release binary.

## 🌅 Closing the App Gracefully

When the Flutter app is closed, the whole `tokio` runtime on the Rust side will be terminated automatically. However, some error messages can appear in the console if the Rust side sends messages to the Dart side even after the Dart VM has stopped. To prevent this, you can call `Rinf.finalize()` in Dart to terminate all Rust tasks before closing the Flutter app.
When the Flutter app is closed, the whole `tokio` runtime on the Rust side will be terminated automatically. However, some error messages can appear in the console if the Rust side sends messages to the Dart side even after the Dart VM has stopped. To prevent this, you can call `finalizeRust()` in Dart to terminate all Rust tasks before closing the Flutter app.

```dart title="lib/main.dart"
import 'dart:ui';
Expand All @@ -87,7 +87,7 @@ class _MyAppState extends State<MyApp> {
final _appLifecycleListener = AppLifecycleListener(
onExitRequested: () async {
// Terminate Rust tasks before closing the Flutter app.
await Rinf.finalize();
finalizeRust();
return AppExitResponse.exit;
},
);
Expand Down
15 changes: 0 additions & 15 deletions documentation/overrides/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -290,14 +290,6 @@ <h3>High-level interface</h3>
safety. Stay with Dart and Rust that you're familiar with.
</p>
</div>
<div class="repeated-box">
<h3>Low-level control</h3>
<p>
Though the hard things are kept beneath the surface, you are free to
modify the underlying logic such as concurrency or debugging features.
There is no hidden mechanism that prevents your understanding.
</p>
</div>
<div class="repeated-box">
<h3>Well maintained</h3>
<p>
Expand All @@ -307,13 +299,6 @@ <h3>Well maintained</h3>
are thoughtfully organized.
</p>
</div>
<div class="repeated-box">
<h3>Async interaction</h3>
<p>
Rust operations will never block Flutter's main thread because they
are spawned in a separate thread pool.
</p>
</div>
<div class="repeated-box">
<h3>Convenient debugging</h3>
<p>
Expand Down
2 changes: 0 additions & 2 deletions flutter_ffi_plugin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,7 @@ All the message classes and structs are generated by Rinf. You can simply define
- **Minimal**: This is not a bulky framework that requires you to install so many dependencies and use complicated CLI commands. Just focus on your code using your preferred Flutter and Rust libraries.
- **Scalable**: Creating hundreds or even thousands of message APIs between Dart and Rust feels smooth and clean. Additionally, you have the flexibility to utilize any number of Rust library crates, perhaps including those you might have been working on.
- **High-level interface**: No messing with sensitive build files, no concerns about memory safety. Stay with Dart and Rust that you're familiar with.
- **Low-level control**: Though the hard things are kept beneath the surface, you are free to modify the underlying logic such as concurrency or debugging features. There is no hidden mechanism that prevents your understanding.
- **Well maintained**: Our [automated workflows](https://github.com/cunarist/rinf/actions) including build tests are always kept passing, thanks to the main branch protection rule. Also, the number of external dependencies is kept as low as possible and documentations are thoughtfully organized.
- **Async interaction**: Rust operations will never block Flutter's main thread because they are spawned in a separate thread pool.
- **Convenient debugging**: All the debugging functionalities are provided by default, without the need for dealing with browsers or mobile emulators. Also, the whole Rust logic is automatically restarted on Dart's hot restart.
- **Reliable**: Each component is supported by huge communities, ensuring a strong emphasis on future safety. You can easily assure your team of stability since this framework's underlying concept is fairly simple.

Expand Down
13 changes: 3 additions & 10 deletions flutter_ffi_plugin/bin/rinf.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,7 @@ Future<void> main(List<String> args) async {
print(rinfConfig);
break;
case "template":
if (args.contains("--bridge") || args.contains("-b")) {
await applyRustTemplate(
onlyBridge: true,
messageConfig: rinfConfig.message,
);
} else {
await applyRustTemplate(messageConfig: rinfConfig.message);
}
await applyRustTemplate(messageConfig: rinfConfig.message);
break;
case "message":
if (args.contains("--watch") || args.contains("-w")) {
Expand All @@ -47,8 +40,8 @@ Future<void> main(List<String> args) async {
print(" config Shows current Rinf configuration"
"\n resolved from `pubspec.yaml`"
"\n with defaults applied.");
print(" template Applies Rust template to current project.");
print(" -b, --bridge Only applies `bridge` Rust module.");
print(" template Applies Rust template"
"\n to current Flutter project.");
print(" message Generates message code from `.proto` files.");
print(" -w, --watch Continuously watches `.proto` files.");
print(" wasm Builds webassembly module.");
Expand Down
21 changes: 3 additions & 18 deletions flutter_ffi_plugin/bin/src/helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import 'message.dart';

/// Creates new folders and files to an existing Flutter project folder.
Future<void> applyRustTemplate({
bool onlyBridge = false,
required RinfConfigMessage messageConfig,
}) async {
// Get the path of the current project directory
Expand All @@ -30,18 +29,6 @@ Future<void> applyRustTemplate({
return;
}

// Only copy the bridge module inside the `hub crate if wanted.
if (onlyBridge) {
final source = Directory('$packagePath/example/native/hub/src/bridge');
final destination = Directory('$flutterProjectPath/native/hub/src/bridge');
if (await destination.exists()) {
await destination.delete(recursive: true);
}
await copyDirectory(source, destination);
print("🎉 Rust bridge module is now ready! 🎉");
return;
}

// Copy basic folders needed for Rust to work
final templateSource = Directory('$packagePath/example/native');
final templateDestination = Directory('$flutterProjectPath/native');
Expand Down Expand Up @@ -171,16 +158,14 @@ please refer to Rinf's [documentation](https://rinf.cunarist.com).
);
mainText = lines.join("\n");
}
if (mainText.contains('main() {')) {
if (!mainText.contains('initializeRust()')) {
mainText = mainText.replaceFirst(
'main() {',
'main() async {',
'main() { initializeRust();',
);
}
if (!mainText.contains('Rinf.initialize()')) {
mainText = mainText.replaceFirst(
'main() async {',
'main() async { await Rinf.initialize();',
'main() async { initializeRust();',
);
}
await mainFile.writeAsString(mainText);
Expand Down
19 changes: 10 additions & 9 deletions flutter_ffi_plugin/bin/src/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,11 @@ import 'package:rinf/rinf.dart';
'''
#![allow(unused_imports)]
use crate::bridge::*;
use crate::tokio;
use prost::Message;
use rinf::send_rust_signal;
use rinf::DartSignal;
use rinf::SharedCell;
use std::cell::RefCell;
use std::sync::Mutex;
use std::sync::OnceLock;
Expand Down Expand Up @@ -303,8 +305,8 @@ impl ${normalizePascal(messageName)} {
#![allow(unused_imports)]
#![allow(unused_variables)]
use crate::bridge::*;
use prost::Message;
use rinf::DartSignal;
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::Mutex;
Expand Down Expand Up @@ -384,14 +386,13 @@ import 'dart:async';
import 'dart:typed_data';
import 'package:rinf/rinf.dart';
class Rinf {
static Future<void> initialize() async {
await initializeRinf(handleRustSignal);
}
void initializeRust() async {
prepareInterface(handleRustSignal);
startRustLogic();
}
static Future<void> finalize() async {
await finalizeRinf();
}
void finalizeRust() async {
stopRustLogic();
}
final signalHandlers = {
Expand Down
6 changes: 3 additions & 3 deletions flutter_ffi_plugin/example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import 'package:example_app/messages/generated.dart';
import 'package:example_app/messages/counter_number.pb.dart';
import 'package:example_app/messages/fractal_art.pb.dart';

void main() async {
void main() {
// Wait for Rust initialization to be completed first.
await Rinf.initialize();
initializeRust();
runApp(const MyApp());
}

Expand All @@ -21,7 +21,7 @@ class _MyAppState extends State<MyApp> {
final _appLifecycleListener = AppLifecycleListener(
onExitRequested: () async {
// Terminate Rust tasks before closing the Flutter app.
await Rinf.finalize();
finalizeRust();
return AppExitResponse.exit;
},
);
Expand Down
3 changes: 1 addition & 2 deletions flutter_ffi_plugin/example/native/hub/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ crate-type = ["lib", "cdylib", "staticlib"]

[dependencies]
rinf = "6.2.0"
allo-isolate = "0.1.24"
wasm-bindgen = "0.2.90"
prost = "0.12.3"
wasm-bindgen = "0.2.90"
tokio_with_wasm = "0.4.0"
sample_crate = { path = "../sample_crate" }
53 changes: 0 additions & 53 deletions flutter_ffi_plugin/example/native/hub/src/bridge/interface.rs

This file was deleted.

Loading

0 comments on commit 310cbb5

Please sign in to comment.