use crate::app::tab::Tab; use crate::app::TextEditor; 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) => { 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 { if let Some(active_tab) = app.get_active_tab_mut() { let title = path.file_name().and_then(|n| n.to_str()).unwrap_or("Untitled"); active_tab.content = content; active_tab.file_path = Some(path.to_path_buf()); active_tab.title = title.to_string(); active_tab.mark_as_saved(); } app.text_needs_processing = true; } else { let new_tab = Tab::new_with_file(content, path); app.tabs.push(new_tab); app.active_tab_index = app.tabs.len() - 1; app.text_needs_processing = true; } if app.show_find && !app.find_query.is_empty() { app.update_find_matches(); } } Err(err) => { eprintln!("Failed to open file: {err}"); } } } } 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.to_path_buf()); } 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(()) => { let title = path.file_name().and_then(|n| n.to_str()).unwrap_or("Untitled"); active_tab.file_path = Some(path.to_path_buf()); active_tab.title = title.to_string(); active_tab.mark_as_saved(); } Err(err) => { eprintln!("Failed to save file: {err}"); } } } }