use super::context::ControllerContext;
use super::feature::ControllerFeature;
use super::types::{TabId, TabInfo};
use crate::error::Result;
pub struct FeatureRegistry {
features: Vec<Box<dyn ControllerFeature>>,
active_tab: Option<TabId>,
}
impl FeatureRegistry {
pub fn new() -> Self {
Self { features: Vec::new(), active_tab: None }
}
pub fn register(&mut self, feature: Box<dyn ControllerFeature>) {
self.features.push(feature);
self.features.sort_by_key(|f| f.tab_info().order);
}
pub fn tabs(&self) -> Vec<TabInfo> {
self.features.iter().map(|f| f.tab_info()).collect()
}
pub fn active_tab(&self) -> Option<&TabId> {
self.active_tab.as_ref()
}
pub fn set_active(&mut self, tab_id: &TabId, ctx: &mut ControllerContext) {
if self.active_tab.as_ref() == Some(tab_id) {
return;
}
if let Some(ref old_id) = self.active_tab {
if let Some(feature) = self.features.iter_mut().find(|f| &f.tab_info().id == old_id) {
feature.on_deactivate(ctx);
}
}
if let Some(feature) = self.features.iter_mut().find(|f| &f.tab_info().id == tab_id) {
feature.on_activate(ctx);
}
self.active_tab = Some(tab_id.clone());
}
pub fn activate_first(&mut self, ctx: &mut ControllerContext) {
if let Some(first_tab) = self.tabs().first().map(|t| t.id.clone()) {
self.set_active(&first_tab, ctx);
}
}
pub fn get_mut(&mut self, tab_id: &TabId) -> Option<&mut Box<dyn ControllerFeature>> {
self.features.iter_mut().find(|f| &f.tab_info().id == tab_id)
}
pub fn get(&self, tab_id: &TabId) -> Option<&dyn ControllerFeature> {
self.features.iter().find(|f| &f.tab_info().id == tab_id).map(|b| b.as_ref())
}
pub fn update_all(&mut self, ctx: &mut ControllerContext) {
for feature in &mut self.features {
feature.update(ctx);
}
}
pub fn render_active(&mut self, ui: &mut egui::Ui, ctx: &mut ControllerContext) {
if let Some(ref tab_id) = self.active_tab.clone() {
if let Some(feature) = self.get_mut(tab_id) {
feature.render(ui, ctx);
}
}
}
pub fn initialize_all(&mut self, ctx: &mut ControllerContext) -> Result<()> {
for feature in &mut self.features {
feature.initialize(ctx)?;
}
Ok(())
}
pub fn shutdown_all(&mut self) {
for feature in &mut self.features {
feature.shutdown();
}
}
pub fn len(&self) -> usize {
self.features.len()
}
pub fn is_empty(&self) -> bool {
self.features.is_empty()
}
}
impl Default for FeatureRegistry {
fn default() -> Self {
Self::new()
}
}