ced/src/io.rs

89 lines
2.9 KiB
Rust
Raw Normal View History

2025-07-15 00:42:01 -04:00
use crate::app::tab::Tab;
use crate::app::TextEditor;
2025-07-05 14:42:45 -04:00
use std::fs;
use std::path::PathBuf;
pub(crate) fn new_file(app: &mut TextEditor) {
app.add_new_tab();
}
pub(crate) fn open_file(app: &mut TextEditor) {
if let Some(path) = rfd::FileDialog::new()
.add_filter("Text files", &["*"])
.pick_file()
{
match fs::read_to_string(&path) {
Ok(content) => {
// Check if the current active tab is empty/clean and can be replaced
let should_replace_current_tab = if let Some(active_tab) = app.get_active_tab() {
active_tab.file_path.is_none()
&& active_tab.content.is_empty()
&& !active_tab.is_modified
} else {
false
};
if should_replace_current_tab {
// Replace the current empty tab
if let Some(active_tab) = app.get_active_tab_mut() {
active_tab.content = content;
active_tab.file_path = Some(path.clone());
active_tab.title = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("Untitled")
.to_string();
active_tab.mark_as_saved(); // This will set the hash and mark as not modified
}
} else {
// Create a new tab as before
let new_tab = Tab::new_with_file(content, path);
app.tabs.push(new_tab);
app.active_tab_index = app.tabs.len() - 1;
}
}
Err(err) => {
2025-07-15 00:42:01 -04:00
eprintln!("Failed to open file: {err}");
2025-07-05 14:42:45 -04:00
}
}
}
}
pub(crate) fn save_file(app: &mut TextEditor) {
if let Some(active_tab) = app.get_active_tab() {
if let Some(path) = &active_tab.file_path {
save_to_path(app, path.clone());
} else {
save_as_file(app);
}
}
}
pub(crate) fn save_as_file(app: &mut TextEditor) {
if let Some(path) = rfd::FileDialog::new()
.add_filter("Text files", &["*"])
.save_file()
{
save_to_path(app, path);
}
}
pub(crate) fn save_to_path(app: &mut TextEditor, path: PathBuf) {
if let Some(active_tab) = app.get_active_tab_mut() {
match fs::write(&path, &active_tab.content) {
Ok(()) => {
active_tab.file_path = Some(path.clone());
active_tab.title = path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("Untitled")
.to_string();
active_tab.mark_as_saved();
}
Err(err) => {
2025-07-15 00:42:01 -04:00
eprintln!("Failed to save file: {err}");
2025-07-05 14:42:45 -04:00
}
}
}
}