Add asynchronous file loading and load default file

This commit is contained in:
Jarrod Doyle 2024-01-21 17:46:58 +00:00
parent dd34f09958
commit b36d3fafc6
Signed by: Jayrude
GPG Key ID: 38B57B16E7C0ADF7
1 changed files with 21 additions and 3 deletions

View File

@ -1,12 +1,15 @@
use std::{io, path::Path, sync::Arc};
use iced::{
executor,
widget::{column, text, text_editor},
Application, Command, Element, Result, Settings, Theme,
Application, Command, Element, Settings, Theme,
};
#[derive(Debug, Clone)]
enum Message {
Edit(text_editor::Action),
FileOpened(Result<Arc<String>, io::ErrorKind>),
}
struct BookManagerApp {
@ -24,7 +27,10 @@ impl Application for BookManagerApp {
Self {
book_content: text_editor::Content::new(),
},
Command::none(),
Command::perform(
load_file(format!("{}/src/main.rs", env!("CARGO_MANIFEST_DIR"))),
Message::FileOpened,
),
)
}
@ -35,6 +41,11 @@ impl Application for BookManagerApp {
fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
match message {
Message::Edit(action) => self.book_content.perform(action),
Message::FileOpened(result) => {
if let Ok(content) = result {
self.book_content = text_editor::Content::with_text(&content);
}
}
}
Command::none()
@ -55,6 +66,13 @@ impl Application for BookManagerApp {
}
}
fn main() -> Result {
fn main() -> iced::Result {
BookManagerApp::run(Settings::default())
}
async fn load_file(path: impl AsRef<Path>) -> Result<Arc<String>, io::ErrorKind> {
tokio::fs::read_to_string(path)
.await
.map(Arc::new)
.map_err(|error| error.kind())
}