From 86d5cc8f605aba65029f82f6bce477fa798279e3 Mon Sep 17 00:00:00 2001 From: Jarrod Doyle Date: Sun, 21 Jan 2024 19:14:13 +0000 Subject: [PATCH] Add 'Open' button to open a file --- src/main.rs | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/main.rs b/src/main.rs index a47120f..27056fe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,19 +2,20 @@ use std::{io, path::Path, sync::Arc}; use iced::{ executor, - widget::{column, text, text_editor}, + widget::{button, column, row, text, text_editor}, Application, Command, Element, Settings, Theme, }; #[derive(Debug, Clone)] enum Message { + Open, Edit(text_editor::Action), - FileOpened(Result, io::ErrorKind>), + FileOpened(Result, Error>), } struct BookManagerApp { book_content: text_editor::Content, - io_error: Option, + io_error: Option, } impl Application for BookManagerApp { @@ -47,16 +48,20 @@ impl Application for BookManagerApp { Ok(content) => self.book_content = text_editor::Content::with_text(&content), Err(error) => self.io_error = Some(error), }, + Message::Open => { + return Command::perform(pick_file(), Message::FileOpened); + } } Command::none() } fn view(&self) -> Element<'_, Self::Message> { + let controls = row![button("Open").on_press(Message::Open)]; let hello_world = text("Hello, world!"); let active_editor = text_editor(&self.book_content).on_action(Message::Edit); - column![hello_world, active_editor] + column![hello_world, controls, active_editor] .spacing(10) .padding(10) .into() @@ -71,9 +76,25 @@ fn main() -> iced::Result { BookManagerApp::run(Settings::default()) } -async fn load_file(path: impl AsRef) -> Result, io::ErrorKind> { +#[derive(Debug, Clone)] +enum Error { + DialogClosed, + IO(io::ErrorKind), +} + +async fn load_file(path: impl AsRef) -> Result, Error> { tokio::fs::read_to_string(path) .await .map(Arc::new) .map_err(|error| error.kind()) + .map_err(Error::IO) +} + +async fn pick_file() -> Result, Error> { + let file_handle = rfd::AsyncFileDialog::new() + .set_title("Choose a file...") + .pick_file() + .await + .ok_or(Error::DialogClosed)?; + load_file(file_handle.path()).await }