From b36d3fafc6e13c22e90a0e136736689f3cba5896 Mon Sep 17 00:00:00 2001 From: Jarrod Doyle Date: Sun, 21 Jan 2024 17:46:58 +0000 Subject: [PATCH] Add asynchronous file loading and load default file --- src/main.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/src/main.rs b/src/main.rs index 31ad4e4..ae2a3c8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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, 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 { 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) -> Result, io::ErrorKind> { + tokio::fs::read_to_string(path) + .await + .map(Arc::new) + .map_err(|error| error.kind()) +}