Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply various improvements #431

Merged
merged 8 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions automate/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,6 @@ def replace_text_in_file(filepath: str, change_from: str, change_to: str):
os.remove("Cargo.toml")

# Enable the web target, since it's not enabled by default.
replace_text_in_file(
"native/hub/src/lib.rs",
"use tokio;",
"// use tokio;",
)
replace_text_in_file(
"native/hub/src/lib.rs",
"// use tokio_with_wasm::alias as tokio;",
Expand Down Expand Up @@ -102,11 +97,6 @@ def replace_text_in_file(filepath: str, change_from: str, change_to: str):
os.remove("Cargo.toml")

# Enable the web target, since it's not enabled by default.
replace_text_in_file(
"native/hub/src/lib.rs",
"use tokio;",
"// use tokio;",
)
replace_text_in_file(
"native/hub/src/lib.rs",
"// use tokio_with_wasm::alias as tokio;",
Expand Down
10 changes: 5 additions & 5 deletions documentation/docs/frequently-asked-questions.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ message MyUniqueOutput {

```dart title="lib/main.dart"
import 'dart:async';
import 'package:example_app/messages/tutorial_resource.pb.dart';
import 'package:example_app/messages/exports.dart';

var currentInteractionId = 0;
final myUniqueOutputs = Map<int, Completer<MyUniqueOutput>>();
Expand All @@ -218,7 +218,7 @@ void main() async {

```dart title="lib/main.dart"
import 'dart:async';
import 'package:example_app/messages/tutorial_resource.pb.dart';
import 'package:example_app/messages/exports.dart';

onPressed: () async {
final completer = Completer<MyUniqueOutput>();
Expand All @@ -233,9 +233,9 @@ onPressed: () async {
```

```rust title="native/hub/src/sample_functions.rs"
pub async fn respond() {
use messages::tutorial_resource::*;
use crate::messages::*;

pub async fn respond() {
let receiver = MyUniqueInput::get_dart_signal_receiver();
while let Some(dart_signal) = receiver.recv().await {
let my_unique_input = dart_signal.message;
Expand Down Expand Up @@ -312,7 +312,7 @@ Failed to load dynamic library 'libhub.so': libhub.so: cannot open shared object
In this case, you can specify a path that points to the compiled Rust library. Simply provide a string path to your dynamic library file.

```dart title="lib/main.dart"
import './messages/generated.dart';
import './messages/exports.dart';

async void main() {
await initializeRust(compiledLibPath: "/path/to/library/libhub.so");
Expand Down
19 changes: 7 additions & 12 deletions documentation/docs/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ rinf message
Create a button widget in Dart that accepts the user input.

```dart title="lib/main.dart"
import 'package:test_app/messages/tutorial_messages.pb.dart';
import 'package:test_app/messages/exports.dart';

child: Column(
mainAxisAlignment: MainAxisAlignment.center,
Expand All @@ -59,12 +59,10 @@ Let's listen to this message in Rust. This simple function will add one to each

```rust title="native/hub/src/tutorial_functions.rs"
use crate::common::*;
use crate::messages;
use crate::messages::*;
use rinf::debug_print;

pub async fn calculate_precious_data() {
use messages::tutorial_messages::*;

let receiver = MyPreciousData::get_dart_signal_receiver(); // GENERATED
while let Some(dart_signal) = receiver.recv().await {
let my_precious_data = dart_signal.message;
Expand Down Expand Up @@ -124,12 +122,10 @@ tokio = { version = "1", features = ["sync", "rt", "time"] }
```

```rust title="native/hub/src/tutorial_functions.rs"
use crate::messages;
use crate::messages::*;
use std::time::Duration;

pub async fn stream_amazing_number() {
use messages::tutorial_messages::*;

let mut current_number: i32 = 1;
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
Expand All @@ -150,7 +146,8 @@ async fn main() {
Finally, receive the signals in Dart with `StreamBuilder` and rebuild the widget accordingly.

```dart title="lib/main.dart"
import 'package:test_app/messages/tutorial_messages.pb.dart';
import 'package:test_app/messages/exports.dart';

children: [
StreamBuilder(
stream: MyAmazingNumber.rustSignalStream, // GENERATED
Expand Down Expand Up @@ -187,7 +184,7 @@ rinf message
```

```dart title="lib/main.dart"
import 'package:test_app/messages/tutorial_messages.pb.dart';
import 'package:test_app/messages/exports.dart';

children: [
StreamBuilder(
Expand All @@ -213,11 +210,9 @@ children: [

```rust title="native/hub/src/tutorial_functions.rs"
use crate::common::*;
use crate::messages;
use crate::messages::*;

pub async fn tell_treasure() {
use messages::tutorial_messages::*;

let mut current_value: i32 = 1;

let receiver = MyTreasureInput::get_dart_signal_receiver(); // GENERATED
Expand Down
4 changes: 2 additions & 2 deletions flutter_package/bin/src/helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ please refer to Rinf's [documentation](https://rinf.cunarist.com).
if (await mainFile.exists()) {
await Process.run('dart', ['format', './lib/main.dart']);
var mainText = await mainFile.readAsString();
if (!mainText.contains('messages/generated.dart')) {
if (!mainText.contains('messages/exports.dart')) {
final lines = mainText.split("\n");
final lastImportIndex = lines.lastIndexWhere(
(line) => line.startsWith('import '),
Expand All @@ -159,7 +159,7 @@ please refer to Rinf's [documentation](https://rinf.cunarist.com).
);
lines.insert(
lastImportIndex + 2,
"import './messages/generated.dart';",
"import './messages/exports.dart';",
);
mainText = lines.join("\n");
}
Expand Down
51 changes: 36 additions & 15 deletions flutter_package/bin/src/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,11 @@ Future<void> generateMessageCode({
for (final entry in resourcesInFolders.entries) {
final subPath = entry.key;
final resourceNames = entry.value;
final modRsLines = resourceNames.map((resourceName) {
return 'pub mod $resourceName;';
}).toList();
final modRsLines = <String>[];
for (final resourceName in resourceNames) {
modRsLines.add('pub mod $resourceName;');
modRsLines.add('pub use $resourceName::*;');
}
for (final otherSubPath in resourcesInFolders.keys) {
if (otherSubPath != subPath && otherSubPath.contains(subPath)) {
final subPathSplitted = subPath
Expand Down Expand Up @@ -173,10 +175,12 @@ Future<void> generateMessageCode({
}
final childName = otherSubPathSplitted.last;
modRsLines.add('pub mod $childName;');
modRsLines.add('pub use $childName::*;');
}
}
if (subPath == "/") {
modRsLines.add("pub mod generated;");
modRsLines.add("pub use generated::*;");
}
final modRsContent = modRsLines.join('\n');
await File.fromUri(rustOutputPath.join(subPath).join('mod.rs'))
Expand Down Expand Up @@ -232,6 +236,23 @@ Future<void> generateMessageCode({
}
}

// Generate `exports.dart` for `messages` module in Dart.
final exportsDartLines = <String>[];
exportsDartLines.add("export './generated.dart';");
for (final entry in resourcesInFolders.entries) {
var subPath = entry.key;
if (subPath == "/") {
subPath = "";
}
final resourceNames = entry.value;
for (final resourceName in resourceNames) {
exportsDartLines.add("export './$subPath$resourceName.pb.dart';");
}
}
final exportsDartContent = exportsDartLines.join('\n');
await File.fromUri(dartOutputPath.join('exports.dart'))
.writeAsString(exportsDartContent);

// Prepare communication channels between Dart and Rust.
for (final entry in markedMessagesAll.entries) {
final subPath = entry.key;
Expand Down Expand Up @@ -268,9 +289,9 @@ import 'package:rinf/rinf.dart';

use prost::Message;
use rinf::{
debug_print, message_channel, send_rust_signal,
DartSignal, MessageReceiver, MessageSender,
RinfError,
debug_print, send_rust_signal, signal_channel,
DartSignal, RinfError, SignalReceiver,
SignalSender,
};
use std::sync::LazyLock;

Expand All @@ -289,15 +310,15 @@ use std::sync::LazyLock;
await insertTextToFile(
rustPath,
'''
type ${messageName}Cell = LazyLock<(
MessageSender<DartSignal<${normalizePascal(messageName)}>>,
MessageReceiver<DartSignal<${normalizePascal(messageName)}>>,
type ${messageName}Channel = LazyLock<(
SignalSender<DartSignal<${normalizePascal(messageName)}>>,
SignalReceiver<DartSignal<${normalizePascal(messageName)}>>,
)>;
pub static ${snakeName.toUpperCase()}_CHANNEL: ${messageName}Cell =
LazyLock::new(message_channel);
pub static ${snakeName.toUpperCase()}_CHANNEL: ${messageName}Channel =
LazyLock::new(signal_channel);

impl ${normalizePascal(messageName)} {
pub fn get_dart_signal_receiver() -> MessageReceiver<DartSignal<Self>> {
pub fn get_dart_signal_receiver() -> SignalReceiver<DartSignal<Self>> {
${snakeName.toUpperCase()}_CHANNEL.1.clone()
}
}
Expand All @@ -307,7 +328,7 @@ impl ${normalizePascal(messageName)} {
await insertTextToFile(
dartPath,
'''
extension ${messageName}Extension on $messageName{
extension ${messageName}Ext on $messageName{
void sendSignalToRust() {
sendDartSignal(
${markedMessage.id},
Expand All @@ -324,7 +345,7 @@ extension ${messageName}Extension on $messageName{
await insertTextToFile(
dartPath,
'''
extension ${messageName}Extension on $messageName{
extension ${messageName}Ext on $messageName{
void sendSignalToRust(Uint8List binary) {
sendDartSignal(
${markedMessage.id},
Expand Down Expand Up @@ -402,7 +423,7 @@ impl ${normalizePascal(messageName)} {
#![allow(unused_mut)]

use prost::Message;
use rinf::{debug_print, message_channel, DartSignal, RinfError};
use rinf::{debug_print, signal_channel, DartSignal, RinfError};
use std::collections::HashMap;
use std::error::Error;
use std::sync::OnceLock;
Expand Down
4 changes: 1 addition & 3 deletions flutter_package/example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:rinf/rinf.dart';
import './messages/generated.dart';
import './messages/counter_number.pb.dart';
import './messages/fractal_art.pb.dart';
import './messages/exports.dart';

void main() async {
await initializeRust(assignRustSignal);
Expand Down
1 change: 0 additions & 1 deletion flutter_package/example/native/hub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ mod common;
mod messages;
mod sample_functions;

// use tokio;
use common::*;
use tokio_with_wasm::alias as tokio;

Expand Down
9 changes: 2 additions & 7 deletions flutter_package/example/native/hub/src/sample_functions.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! This crate is written for Rinf demonstrations.

use crate::common::*;
use crate::messages;
use crate::messages::*;
use crate::tokio;
use rinf::debug_print;
use std::time::Duration;
Expand All @@ -14,8 +14,6 @@ static IS_DEBUG_MODE: bool = false;

// Business logic for the counter widget.
pub async fn tell_numbers() {
use messages::counter_number::*;

let mut vector = Vec::new();

// Stream getter is generated from a marked Protobuf message.
Expand Down Expand Up @@ -44,9 +42,6 @@ pub async fn tell_numbers() {

// Business logic for the fractal image.
pub async fn stream_fractal() {
use messages::counter_number::*;
use messages::fractal_art::*;

let mut current_scale: f64 = 1.0;

let (sender, mut receiver) = tokio::sync::mpsc::channel(5);
Expand Down Expand Up @@ -103,13 +98,13 @@ pub async fn stream_fractal() {
// A dummy function that uses sample messages to eliminate warnings.
#[allow(dead_code)]
async fn use_messages() {
use messages::sample_folder::sample_file::*;
let _ = SampleInput::get_dart_signal_receiver();
SampleOutput {
kind: 3,
oneof_input: Some(sample_output::OneofInput::Age(25)),
}
.send_signal_to_dart();
let _ = DeeperDummy {};
}

// Business logic for testing various crates.
Expand Down
4 changes: 1 addition & 3 deletions flutter_package/template/native/hub/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ mod common;
mod messages;

use crate::common::*;
use tokio; // Comment this line to target the web.
use crate::messages::*;
// use tokio_with_wasm::alias as tokio; // Uncomment this line to target the web.

rinf::write_interface!();
Expand All @@ -29,8 +29,6 @@ async fn main() -> Result<()> {
}

async fn communicate() {
use messages::basic::*;

// Send signals to Dart like below.
SmallNumber { number: 7 }.send_signal_to_dart();

Expand Down
Loading
Loading