use common::database::db_context::DbContext;
use common::event::EventHub;
use common::long_operation::LongOperationManager;
use common::undo_redo::UndoRedoManager;
use flume::{Receiver, Sender};
use parking_lot::Mutex;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct AppContext {
pub db_context: DbContext,
pub event_hub: Arc<EventHub>,
pub shutdown_rx: Receiver<()>,
shutdown_tx: Arc<Mutex<Option<Sender<()>>>>,
pub undo_redo_manager: Arc<Mutex<UndoRedoManager>>,
pub long_operation_manager: Arc<Mutex<LongOperationManager>>,
}
impl AppContext {
pub fn new() -> Self {
let db_context = DbContext::new().expect("Failed to create database context");
let event_hub = Arc::new(EventHub::new());
let (shutdown_tx, shutdown_rx) = flume::bounded(1);
let undo_redo_manager = Arc::new(Mutex::new(UndoRedoManager::new()));
let long_operation_manager = Arc::new(Mutex::new(LongOperationManager::new()));
{
let mut lom = long_operation_manager.lock();
lom.set_event_hub(&event_hub);
}
{
let mut urm = undo_redo_manager.lock();
urm.set_event_hub(&event_hub);
}
Self {
db_context,
event_hub,
shutdown_rx,
shutdown_tx: Arc::new(Mutex::new(Some(shutdown_tx))),
undo_redo_manager,
long_operation_manager,
}
}
pub fn new_sharing(other: &AppContext) -> Self {
let db_context = DbContext::new().expect("Failed to create database context");
let undo_redo_manager = Arc::new(Mutex::new(UndoRedoManager::new()));
{
let mut urm = undo_redo_manager.lock();
urm.set_event_hub(&other.event_hub);
}
Self {
db_context,
event_hub: Arc::clone(&other.event_hub),
shutdown_rx: other.shutdown_rx.clone(),
shutdown_tx: Arc::clone(&other.shutdown_tx),
undo_redo_manager,
long_operation_manager: Arc::clone(&other.long_operation_manager),
}
}
pub fn shutdown(&self) {
let _ = self.shutdown_tx.lock().take();
}
}
impl Default for AppContext {
fn default() -> Self {
Self::new()
}
}