Files
signed/crates/signed_app/src/shared/panels.rs
T

129 lines
3.4 KiB
Rust

use std::sync::Arc;
use gpui::{App, Entity, SharedString, WeakEntity, Window};
use ui::layout::panel::{Panel, PanelView};
use crate::workspace::Workspace;
/// Which slot of the workspace a panel opens into.
#[derive(Clone, Copy)]
enum PanelSlot {
Main,
Detail,
}
impl PanelSlot {
/// Whether the slot already holds a panel under `id`.
fn has(self, workspace: &WeakEntity<Workspace>, id: &SharedString, cx: &App) -> bool {
match self {
PanelSlot::Main => workspace
.read_with(cx, |workspace, _| workspace.has_main(id))
.unwrap_or(false),
PanelSlot::Detail => workspace
.read_with(cx, |workspace, _| workspace.has_detail(id))
.unwrap_or(false),
}
}
/// Activates the slot's cached panel under `id`.
fn activate(self, workspace: &WeakEntity<Workspace>, id: &SharedString, cx: &mut App) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.activate_main(id, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.activate_detail(id, cx))
}
};
if let Err(error) = result {
log::warn!("failed to activate panel {id}: {error}");
}
}
/// Shows the panel in the slot.
fn show(
self,
workspace: &WeakEntity<Workspace>,
id: SharedString,
view: Arc<dyn PanelView>,
cx: &mut App,
) {
let result = match self {
PanelSlot::Main => {
workspace.update(cx, |workspace, cx| workspace.show_main(id, view, cx))
}
PanelSlot::Detail => {
workspace.update(cx, |workspace, cx| workspace.show_detail(id, view, cx))
}
};
if let Err(error) = result {
log::warn!("failed to open panel: {error}");
}
}
}
/// Opens a panel in `slot`, reusing it when it is already cached.
fn open_slot<P, F>(
slot: PanelSlot,
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
let id = id.into();
if slot.has(workspace, &id, cx) {
slot.activate(workspace, &id, cx);
return;
}
let view: Arc<dyn PanelView> = Arc::new(build(window, cx));
slot.show(workspace, id, view, cx);
}
/// Opens a repository in the main panel, reusing it when it is already cached.
pub fn open_primary<P, F>(
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
open_slot(
PanelSlot::Main,
workspace,
id,
build,
window,
cx,
);
}
/// Opens a detail panel beside the main panel, reusing it when it is already cached.
pub fn open_detail<P, F>(
workspace: &WeakEntity<Workspace>,
id: impl Into<SharedString>,
build: F,
window: &mut Window,
cx: &mut App,
) where
P: Panel + 'static,
F: Fn(&mut Window, &mut App) -> Entity<P> + 'static,
{
open_slot(
PanelSlot::Detail,
workspace,
id,
build,
window,
cx,
);
}