Show filename in title

This commit is contained in:
Jeremy Soller 2022-10-19 14:05:14 -06:00
parent 65f60d1565
commit bfdc9a6d66
No known key found for this signature in database
GPG key ID: 87F211AF2BE4C2FE

View file

@ -29,6 +29,7 @@ use cosmic_text::{
use std::{ use std::{
env, env,
fs, fs,
path::PathBuf,
sync::Mutex, sync::Mutex,
}; };
@ -93,6 +94,7 @@ fn main() -> cosmic::iced::Result {
pub struct Window { pub struct Window {
theme: Theme, theme: Theme,
path_opt: Option<PathBuf>,
buffer: Mutex<TextBuffer<'static>>, buffer: Mutex<TextBuffer<'static>>,
} }
@ -104,6 +106,23 @@ pub enum Message {
ThemeChanged(&'static str), ThemeChanged(&'static str),
} }
impl Window {
pub fn open(&mut self, path: PathBuf) {
let mut buffer = self.buffer.lock().unwrap();
match fs::read_to_string(&path) {
Ok(text) => {
buffer.set_text(&text);
self.path_opt = Some(path);
},
Err(err) => {
log::error!("failed to open '{}': {}", path.display(), err);
buffer.set_text("");
self.path_opt = None;
}
}
}
}
impl Application for Window { impl Application for Window {
type Executor = iced::executor::Default; type Executor = iced::executor::Default;
type Flags = (); type Flags = ();
@ -117,21 +136,14 @@ impl Application for Window {
FONT_SIZES[font_size_i], FONT_SIZES[font_size_i],
); );
if let Some(arg) = env::args().nth(1) { let mut window = Window {
match fs::read_to_string(&arg) {
Ok(text) => {
buffer.set_text(&text);
},
Err(err) => {
log::error!("failed to open '{}': {}", arg, err);
}
}
}
let window = Window {
theme: Theme::Dark, theme: Theme::Dark,
path_opt: None,
buffer: Mutex::new(buffer), buffer: Mutex::new(buffer),
}; };
if let Some(arg) = env::args().nth(1) {
window.open(PathBuf::from(arg));
}
(window, Command::none()) (window, Command::none())
} }
@ -140,23 +152,18 @@ impl Application for Window {
} }
fn title(&self) -> String { fn title(&self) -> String {
format!("COSMIC Text - iced - {}", FONT_SYSTEM.locale) if let Some(path) = &self.path_opt {
format!("COSMIC Text - {} - {}", FONT_SYSTEM.locale, path.display())
} else {
format!("COSMIC Text - {}", FONT_SYSTEM.locale)
}
} }
fn update(&mut self, message: Message) -> iced::Command<Self::Message> { fn update(&mut self, message: Message) -> iced::Command<Self::Message> {
match message { match message {
Message::Open => { Message::Open => {
if let Some(path) = rfd::FileDialog::new().pick_file() { if let Some(path) = rfd::FileDialog::new().pick_file() {
let mut buffer = self.buffer.lock().unwrap(); self.open(path);
match fs::read_to_string(&path) {
Ok(text) => {
buffer.set_text(&text);
},
Err(err) => {
buffer.set_text("");
log::error!("failed to open '{}': {}", path.display(), err);
}
}
} }
}, },
Message::MetricsChanged(metrics) => { Message::MetricsChanged(metrics) => {