Add 'Open' button to open a file
This commit is contained in:
parent
aee8b1f31f
commit
86d5cc8f60
31
src/main.rs
31
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<Arc<String>, io::ErrorKind>),
|
||||
FileOpened(Result<Arc<String>, Error>),
|
||||
}
|
||||
|
||||
struct BookManagerApp {
|
||||
book_content: text_editor::Content,
|
||||
io_error: Option<io::ErrorKind>,
|
||||
io_error: Option<Error>,
|
||||
}
|
||||
|
||||
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<Path>) -> Result<Arc<String>, io::ErrorKind> {
|
||||
#[derive(Debug, Clone)]
|
||||
enum Error {
|
||||
DialogClosed,
|
||||
IO(io::ErrorKind),
|
||||
}
|
||||
|
||||
async fn load_file(path: impl AsRef<Path>) -> Result<Arc<String>, 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<Arc<String>, 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
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue