From ce8fb5dd12a721604c9abad66de0cbc56a73a735 Mon Sep 17 00:00:00 2001 From: Nefo Fortressia Date: Thu, 16 Dec 2021 11:08:42 +0700 Subject: [PATCH] refactor: separate get_current_tab() from save_file_as() EchidnaWindow.get_current_tab() can now be used independently. This will help with reusing it in another places. I think it will be used a lot. Additionally, it will return Result instead of panicking, as it's a utils function now and should never panic. --- src/components/window/file.rs | 19 +++---------------- src/components/window/mod.rs | 23 ++++++++++++++++++++++- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/components/window/file.rs b/src/components/window/file.rs index 7989465..bf0dcb9 100644 --- a/src/components/window/file.rs +++ b/src/components/window/file.rs @@ -82,22 +82,9 @@ impl FileImplementedEditor for super::EchidnaWindow { } fn save_file_as(&self, file: &gio::File) { let window_imp = self.to_imp(); - let page: EchidnaCoreEditor; - - match window_imp.notebook - .nth_page( - Some(window_imp.notebook - .current_page() - .expect( - "No tabs is the current tab, probably all tabs closed. No files to save" - ) - ) - ).expect( - "Couldn't get the page of the current index. Try again." - ).downcast::() { - Ok(res) => page = res, - Err(e) => panic!(format!("We got an error when trying to downcast the current tab page into EchidnaCoreEditor:\n{}", e)) - } + let page: EchidnaCoreEditor = self + .get_current_tab() + .expect("Can't find the current tab because there are no tabs."); let buffer: Buffer = page .to_imp() diff --git a/src/components/window/mod.rs b/src/components/window/mod.rs index 40ed731..d692722 100644 --- a/src/components/window/mod.rs +++ b/src/components/window/mod.rs @@ -6,7 +6,7 @@ pub mod file; pub mod imp; pub mod menubar; -use glib::object::IsA; +use glib::object::{Cast, IsA}; use gtk::subclass::prelude::*; glib::wrapper! { @@ -28,4 +28,25 @@ impl EchidnaWindow { pub fn to_imp(&self) -> &imp::EchidnaWindow { imp::EchidnaWindow::from_instance(self) } + + pub fn get_current_tab>(&self) -> Result { + let window_imp = self.to_imp(); + let nth = window_imp.notebook.current_page(); + + match nth { + None => Err("No tabs are currently opened, maybe there are no tabs."), + Some(nth) => { + let page = window_imp + .notebook + .nth_page(Some(nth)) + .expect("Couldn't get the page of the current index."); + + match page.downcast::() + { + Ok(page) => Ok(page), + Err(e) => Err("Cannot downcast to type parameter A. Maybe it's not in the type you are looking for."), + } + } + } + } }