update dock

This commit is contained in:
2026-08-23 10:03:10 +07:00
parent 7fb7275233
commit 8da48bdc4a
25 changed files with 1583 additions and 5471 deletions
+1 -10
View File
@@ -1,6 +1,6 @@
[package]
name = "dock"
description = "Dock (DockArea / Dock / Panel) components vendored from gpui-component."
description = "The Signed dock skin over gpui-component's upstream dock (gpui_base::dock engine + renderer traits)."
version.workspace = true
edition.workspace = true
publish.workspace = true
@@ -9,12 +9,3 @@ publish.workspace = true
gpui.workspace = true
gpui-component.workspace = true
gpui-base.workspace = true
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
itertools = "0.13.0"
smallvec = "1"
[dev-dependencies]
gpui = { workspace = true, features = ["test-support"] }
-429
View File
@@ -1,429 +0,0 @@
use std::ops::Deref;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
App, AppContext, Axis, Context, Element, Empty, Entity, IntoElement, MouseMoveEvent,
MouseUpEvent, ParentElement as _, Pixels, Point, Render, Style, StyleRefinement, Styled as _,
WeakEntity, Window, div, px,
};
use gpui_component::{Side, StyledExt};
use serde::{Deserialize, Serialize};
use super::{DockArea, DockEvent, DockItem, PanelView, TabPanel};
use crate::resize_handle::{PANEL_MIN_SIZE, resize_handle};
#[derive(Clone)]
struct ResizePanel;
impl Render for ResizePanel {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
Empty
}
}
/// Where to place a panel.
///
/// The [`DockArea`] has a fixed left dock and a center area. `Left` targets
/// the left dock; `Center` adds a tab to the center; `Right` and `Bottom`
/// split the center so the new panel lands on the given side of the existing
/// center content.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum DockPlacement {
#[serde(rename = "center")]
Center,
#[serde(rename = "left")]
Left,
#[serde(rename = "bottom")]
Bottom,
#[serde(rename = "right")]
Right,
}
impl DockPlacement {
/// The split axis used when the placement splits the center area.
pub(crate) fn axis(&self) -> Axis {
match self {
Self::Left | Self::Right => Axis::Horizontal,
Self::Bottom => Axis::Vertical,
Self::Center => unreachable!(),
}
}
pub fn is_left(&self) -> bool {
matches!(self, Self::Left)
}
}
/// The Dock is a fixed container that places at the left side of the window.
///
/// This is unlike Panel, it can't be move or add any other panel.
pub struct Dock {
pub(super) placement: DockPlacement,
dock_area: WeakEntity<DockArea>,
pub(crate) panel: DockItem,
/// The width of the dock.
pub(super) size: Pixels,
pub(super) open: bool,
/// Whether the Dock is collapsible, default: true
pub(super) collapsible: bool,
// Runtime state
/// Whether the Dock is resizing
resizing: bool,
}
impl Dock {
pub(crate) fn new(
dock_area: WeakEntity<DockArea>,
placement: DockPlacement,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let panel = cx.new(|cx| {
let mut tab = TabPanel::new(None, dock_area.clone(), window, cx);
tab.closable = false;
tab
});
let panel = DockItem::Tabs {
size: None,
items: Vec::new(),
active_ix: 0,
view: panel.clone(),
};
Self::subscribe_panel_events(dock_area.clone(), &panel, window, cx);
Self {
placement,
dock_area,
panel,
open: true,
collapsible: true,
size: px(200.0),
resizing: false,
}
}
pub fn left(
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
Self::new(dock_area, DockPlacement::Left, window, cx)
}
/// Update the Dock to be collapsible or not.
///
/// And if the Dock is not collapsible, it will be open.
pub fn set_collapsible(&mut self, collapsible: bool, _: &mut Window, cx: &mut Context<Self>) {
self.collapsible = collapsible;
if !collapsible {
self.open = true
}
cx.notify();
}
pub(super) fn from_state(
dock_area: WeakEntity<DockArea>,
placement: DockPlacement,
size: Pixels,
panel: DockItem,
open: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
Self::subscribe_panel_events(dock_area.clone(), &panel, window, cx);
if !open {
match panel.clone() {
DockItem::Tabs { view, .. } => {
view.update(cx, |panel, cx| {
panel.set_collapsed(true, window, cx);
});
}
DockItem::Split { items, .. } => {
for item in items {
item.set_collapsed(true, window, cx);
}
}
_ => {}
}
}
Self {
placement,
dock_area,
panel,
open,
size,
collapsible: true,
resizing: false,
}
}
fn subscribe_panel_events(
dock_area: WeakEntity<DockArea>,
panel: &DockItem,
window: &mut Window,
cx: &mut Context<Self>,
) {
match panel {
DockItem::Tabs { view, .. } => {
window.defer(cx, {
let view = view.clone();
move |window, cx| {
_ = dock_area.update(cx, |this, cx| {
this.subscribe_panel(&view, window, cx);
});
}
});
}
DockItem::Split { items, view, .. } => {
for item in items {
Self::subscribe_panel_events(dock_area.clone(), item, window, cx);
}
window.defer(cx, {
let view = view.clone();
move |window, cx| {
_ = dock_area.update(cx, |this, cx| {
this.subscribe_panel(&view, window, cx);
});
}
});
}
DockItem::Panel { .. } => {
// Not supported
}
}
}
pub fn set_panel(&mut self, panel: DockItem, _: &mut Window, cx: &mut Context<Self>) {
self.panel = panel;
cx.notify();
}
pub fn panel(&self) -> &DockItem {
&self.panel
}
pub fn is_open(&self) -> bool {
self.open
}
pub fn toggle_open(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.set_open(!self.open, window, cx);
}
/// Returns the size of the Dock, the size is means the width or height of
/// the Dock, if the placement is left or right, the size is width,
/// otherwise the size is height.
pub fn size(&self) -> Pixels {
self.size
}
/// Set the size of the Dock.
pub fn set_size(&mut self, size: Pixels, _: &mut Window, cx: &mut Context<Self>) {
self.size = size.max(PANEL_MIN_SIZE);
cx.notify();
}
/// Set the open state of the Dock.
pub fn set_open(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
self.open = open;
let item = self.panel.clone();
cx.defer_in(window, move |_, window, cx| {
item.set_collapsed(!open, window, cx);
});
cx.notify();
}
/// Add item to the Dock.
pub fn add_panel(
&mut self,
panel: Arc<dyn PanelView>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.panel.add_panel(panel, &self.dock_area, window, cx);
cx.notify();
}
/// Remove item from the Dock.
pub fn remove_panel(
&mut self,
panel: Arc<dyn PanelView>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.panel.remove_panel(panel, window, cx);
cx.notify();
}
fn render_resize_handle(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let axis = self.placement.axis();
let view = cx.entity().clone();
resize_handle("resize-handle", axis)
.when(self.placement == DockPlacement::Left, |this| {
this.placement(Side::Left)
})
.on_drag(ResizePanel {}, move |info, _, _, cx| {
cx.stop_propagation();
view.update(cx, |view, _| {
view.resizing = true;
});
cx.new(|_| info.deref().clone())
})
}
fn resize(
&mut self,
mouse_position: Point<Pixels>,
window: &mut Window,
cx: &mut Context<Self>,
) {
if !self.resizing {
return;
}
if !self.open {
self.set_open(true, window, cx);
}
let dock_area = self
.dock_area
.upgrade()
.expect("DockArea is missing")
.read(cx);
let area_bounds = dock_area.bounds;
let size = mouse_position.x - area_bounds.left();
let max_size = (area_bounds.size.width - PANEL_MIN_SIZE).max(PANEL_MIN_SIZE);
self.size = size.clamp(PANEL_MIN_SIZE, max_size);
cx.notify();
}
fn done_resizing(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
if !self.resizing {
return;
}
self.resizing = false;
// Dragging the dock's resize handle finished, bubble a layout change
// so subscribers can persist the new dock size.
_ = self.dock_area.update(cx, |_, cx| {
cx.emit(DockEvent::LayoutChanged);
});
}
}
impl Render for Dock {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl gpui::IntoElement {
if !self.open {
return div();
}
let cache_style = StyleRefinement::default().absolute().size_full();
div()
.relative()
.overflow_hidden()
.h_flex()
.h_full()
.w(self.size)
.map(|this| match &self.panel {
DockItem::Split { view, .. } => this.child(view.clone()),
DockItem::Tabs { view, .. } => this.child(view.clone()),
DockItem::Panel { view, .. } => this.child(view.clone().view().cached(cache_style)),
})
.child(self.render_resize_handle(window, cx))
.child(DockElement {
view: cx.entity().clone(),
})
}
}
struct DockElement {
view: Entity<Dock>,
}
impl IntoElement for DockElement {
type Element = Self;
fn into_element(self) -> Self::Element {
self
}
}
impl Element for DockElement {
type PrepaintState = ();
type RequestLayoutState = ();
fn id(&self) -> Option<gpui::ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
window: &mut gpui::Window,
cx: &mut App,
) -> (gpui::LayoutId, Self::RequestLayoutState) {
(window.request_layout(Style::default(), None, cx), ())
}
fn prepaint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
_window: &mut gpui::Window,
_cx: &mut App,
) -> Self::PrepaintState {
}
fn paint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
window: &mut gpui::Window,
cx: &mut App,
) {
window.on_mouse_event({
let view = self.view.clone();
let resizing = view.read(cx).resizing;
move |e: &MouseMoveEvent, phase, window, cx| {
if !resizing {
return;
}
if !phase.bubble() {
return;
}
view.update(cx, |view, cx| view.resize(e.position, window, cx))
}
});
// When any mouse up, stop dragging
window.on_mouse_event({
let view = self.view.clone();
move |_: &MouseUpEvent, phase, window, cx| {
if phase.bubble() {
view.update(cx, |view, cx| view.done_resizing(window, cx));
}
}
})
}
}
+350
View File
@@ -0,0 +1,350 @@
//! The dock-area appearance: the outer frame, the split frames, and one
//! dock's chrome. Ported from the vendored dock's `DockArea`/`Dock` render
//! onto `gpui_base::dock::DockAreaRenderer`.
use std::cell::Cell;
use std::ops::Deref as _;
use std::rc::Rc;
use std::sync::Arc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Axis, Context, Div, Element, Empty, InteractiveElement as _,
IntoElement, MouseMoveEvent, MouseUpEvent, ParentElement as _, Pixels, Render, Stateful, Style,
Styled as _, WeakEntity, Window, div, px,
};
use gpui_base::dock::{
DockArea, DockAreaRenderer, DockContext, DockEvent, DockPlacement, NodeId, PanelState,
PanelView, TabGroupRenderer, TilesRenderer,
};
use gpui_base::resize_handle;
use gpui_component::scroll::ScrollbarMode;
use gpui_component::{ActiveTheme as _, Side, StyledExt as _};
use crate::invalid_panel::InvalidPanel;
use crate::tab_panel::SignedTabGroupSkin;
use crate::tiles::SignedTilesSkin;
use crate::{TAB_BAR_HEIGHT, panel_handle};
/// What every part of the skin reads, and the dock area it belongs to.
///
/// The renderer is the only skin-owned object in the picture, so the settings
/// the old `DockArea` carried live here. It is shared by reference with the
/// per-container renderers, which are built once each and outlive any one
/// frame.
pub(crate) struct SkinShared {
area: WeakEntity<DockArea>,
toggle_button_visible: Cell<bool>,
tiles_scrollbar_mode: Cell<Option<ScrollbarMode>>,
/// The dock whose resize handle is being dragged, if any. Only one can be.
resizing_dock: Cell<Option<DockPlacement>>,
}
impl SkinShared {
pub(crate) fn area(&self) -> &WeakEntity<DockArea> {
&self.area
}
pub(crate) fn is_toggle_button_visible(&self) -> bool {
self.toggle_button_visible.get()
}
pub(crate) fn tiles_scrollbar_mode(&self) -> Option<ScrollbarMode> {
self.tiles_scrollbar_mode.get()
}
pub(crate) fn resizing_dock(&self) -> &Cell<Option<DockPlacement>> {
&self.resizing_dock
}
/// Redraw the area after a setting changed. The skin is not an entity, so
/// nothing else would notice.
pub(crate) fn notify(&self, cx: &mut App) {
_ = self.area.update(cx, |_, cx| cx.notify());
}
}
/// The Signed appearance for a [`DockArea`].
///
/// Install it at construction, where the area's own weak handle is available:
///
/// ```ignore
/// let dock = cx.new(|cx| {
/// let skin = SignedDockSkin::new(cx);
/// DockArea::new("dock", Some(1), window, cx).with_renderer(skin)
/// });
/// ```
pub struct SignedDockSkin {
shared: Rc<SkinShared>,
}
impl SignedDockSkin {
pub fn new(cx: &mut Context<DockArea>) -> Rc<Self> {
Rc::new(Self {
shared: Rc::new(SkinShared {
area: cx.weak_entity(),
toggle_button_visible: Cell::new(true),
tiles_scrollbar_mode: Cell::new(None),
resizing_dock: Cell::new(None),
}),
})
}
pub(crate) fn shared(&self) -> &Rc<SkinShared> {
&self.shared
}
/// Whether tab bars offer the affordance that collapses a neighbouring
/// dock.
pub fn is_toggle_button_visible(&self) -> bool {
self.shared.is_toggle_button_visible()
}
pub fn set_toggle_button_visible(&self, visible: bool, cx: &mut App) {
self.shared.toggle_button_visible.set(visible);
self.shared.notify(cx);
}
/// When a tiles canvas shows its scrollbar. `None` follows the theme.
pub fn tiles_scrollbar_mode(&self) -> Option<ScrollbarMode> {
self.shared.tiles_scrollbar_mode()
}
pub fn set_tiles_scrollbar_mode(&self, mode: Option<ScrollbarMode>, cx: &mut App) {
self.shared.tiles_scrollbar_mode.set(mode);
self.shared.notify(cx);
}
}
/// The payload a dock's resize handle drags. It draws nothing: the handle
/// itself is the affordance.
#[derive(Clone)]
struct ResizePanel;
impl Render for ResizePanel {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
Empty
}
}
impl DockAreaRenderer for SignedDockSkin {
fn frame(&self, _: &mut Window, _: &mut App) -> Stateful<Div> {
div()
.id("dock-area")
.relative()
.size_full()
.overflow_hidden()
.flex()
.flex_row()
}
fn center_frame(&self, _: &mut Window, _: &mut App) -> Stateful<Div> {
div()
.id("dock-area-center")
.flex()
.flex_1()
.flex_col()
.overflow_hidden()
}
fn split_frame(&self, node: NodeId, _: Axis, _: &mut Window, cx: &mut App) -> Stateful<Div> {
// `size_full` is what the old `StackPanel::render` carried; `flex_1`
// is belt and braces so the frame never collapses to zero height in
// an unsizing parent.
div()
.id(("dock-split-frame", node.as_u64()))
.size_full()
.flex_1()
.min_h(px(0.))
.overflow_hidden()
.bg(cx.theme().tokens.tab_bar)
}
fn render_dock(
&self,
dock: &DockContext,
content: AnyElement,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let placement = dock.placement();
let open = dock.is_open();
// A closed left or right dock takes no space at all; a closed bottom
// dock keeps a strip so its tab bar stays clickable.
if !open && !placement.is_bottom() {
return div().into_any_element();
}
div()
.flex()
.flex_none()
.relative()
.overflow_hidden()
.map(|this| match placement {
DockPlacement::Left | DockPlacement::Right => this.h_flex().h_full().w(dock.size()),
DockPlacement::Bottom => this.w_full().h(dock.size()),
// Base never builds a dock for the centre.
DockPlacement::Center => this,
})
// The closed bottom dock's strip is the tab bar itself, which is
// a full tab bar tall.
.when(!open && placement.is_bottom(), |this| {
this.h(TAB_BAR_HEIGHT)
})
.child(content)
.child(self.render_resize_handle(dock, window, cx))
.child(DockResizeTracker {
dock: dock.clone(),
shared: self.shared().clone(),
})
.into_any_element()
}
/// The "unknown panel" message the old `InvalidPanel` drew.
///
/// It answers `dump` with the state it was handed, so a layout written by
/// a build that knows the panel survives a load and save here.
fn build_placeholder(
&self,
state: &PanelState,
_: &mut Window,
cx: &mut App,
) -> Option<Arc<dyn PanelView>> {
let state = state.clone();
Some(panel_handle(cx.new(|cx| {
InvalidPanel::new(state.panel_name.clone(), state, cx)
})))
}
fn tab_group_renderer(&self) -> Rc<dyn TabGroupRenderer> {
Rc::new(SignedTabGroupSkin::new(self.shared().clone()))
}
fn tiles_renderer(&self) -> Rc<dyn TilesRenderer> {
Rc::new(SignedTilesSkin::new(self.shared().clone()))
}
}
impl SignedDockSkin {
fn render_resize_handle(
&self,
dock: &DockContext,
_: &mut Window,
_: &mut App,
) -> impl IntoElement {
let placement = dock.placement();
let shared = self.shared().clone();
resize_handle("resize-handle", placement.axis())
.when(placement.is_left(), |this| this.placement(Side::Left))
.on_drag(ResizePanel, move |info, _, _, cx| {
cx.stop_propagation();
shared.resizing_dock().set(Some(placement));
cx.new(|_| info.deref().clone())
})
}
}
/// Turns the window's mouse stream into dock resizing.
///
/// A resize is driven by pointer moves that land anywhere in the window, not
/// only on the handle, so it cannot be expressed as a listener on the handle
/// itself. This element paints nothing and exists for its `paint` hook, which
/// is the only place a window-level mouse listener can be registered.
struct DockResizeTracker {
dock: DockContext,
shared: Rc<SkinShared>,
}
impl IntoElement for DockResizeTracker {
type Element = Self;
fn into_element(self) -> Self::Element {
self
}
}
impl Element for DockResizeTracker {
type PrepaintState = ();
type RequestLayoutState = ();
fn id(&self) -> Option<gpui::ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (gpui::LayoutId, Self::RequestLayoutState) {
(window.request_layout(Style::default(), None, cx), ())
}
fn prepaint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
_: &mut Window,
_: &mut App,
) -> Self::PrepaintState {
}
fn paint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<Pixels>,
_: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
window: &mut Window,
_: &mut App,
) {
let placement = self.dock.placement();
window.on_mouse_event({
let dock = self.dock.clone();
let shared = self.shared.clone();
move |event: &MouseMoveEvent, phase, window, cx| {
if !phase.bubble() || shared.resizing_dock().get() != Some(placement) {
return;
}
// Dragging a closed dock's handle reopens it, as the old dock
// did. The live state is read rather than the render-time
// snapshot in `dock`, which would still say closed for the
// rest of the frame and toggle it shut again on the next move.
let open = shared
.area()
.upgrade()
.is_some_and(|area| area.read(cx).is_dock_open(placement));
if !open {
dock.toggle(window, cx);
}
dock.resize_to(event.position, window, cx);
}
});
window.on_mouse_event({
let shared = self.shared.clone();
move |_: &MouseUpEvent, phase, _, cx| {
if !phase.bubble() || shared.resizing_dock().get() != Some(placement) {
return;
}
shared.resizing_dock().set(None);
// The size lives on the dock, not in the layout tree, so
// nothing else tells a subscriber to persist it.
_ = shared
.area()
.update(cx, |_, cx| cx.emit(DockEvent::LayoutChanged));
}
});
}
}
-205
View File
@@ -1,205 +0,0 @@
{
"center": {
"panel_name": "StackPanel",
"children": [
{
"panel_name": "TabPanel",
"children": [
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "ButtonStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "InputStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "TextStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "SelectStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "DialogStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "SwitchStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "ProgressStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "DataTableStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "ImageStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "IconStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "TooltipStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "ProgressStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "CalendarStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "ResizableStory"
}
}
},
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "ScrollbarStory"
}
}
}
],
"info": {
"tabs": {
"active_index": 0
}
}
},
{
"panel_name": "TabPanel",
"children": [
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "PopupStory"
}
}
}
],
"info": {
"tabs": {
"active_index": 0
}
}
}
],
"info": {
"stack": {
"sizes": [
704.0,
263.0
],
"axis": 1
}
}
},
"left_dock": {
"panel": {
"panel_name": "TabPanel",
"children": [
{
"panel_name": "StoryContainer",
"children": [],
"info": {
"panel": {
"story_klass": "ListStory"
}
}
}
],
"info": {
"tabs": {
"active_index": 0
}
}
},
"placement": "left",
"size": 350.0,
"open": true,
"resizeable": true
}
}
+26 -13
View File
@@ -1,11 +1,18 @@
use gpui::{
App, EventEmitter, FocusHandle, Focusable, ParentElement as _, Render, SharedString,
Styled as _, Window,
App, Context, EventEmitter, FocusHandle, Focusable, IntoElement, ParentElement as _, Render,
SharedString, Styled as _, Window, div,
};
use gpui_base::dock::{PanelEvent, PanelState};
use gpui_component::ActiveTheme as _;
use super::{Panel, PanelEvent, PanelState};
use crate::Panel;
/// Stands in for a panel this build cannot construct — one whose `panel_name`
/// no [`PanelRegistry`](gpui_base::dock::PanelRegistry) builder answers to.
///
/// It reports the original [`PanelState`] from
/// [`dump`](gpui_base::dock::Panel::dump), so a layout written by a build that
/// knows the panel survives a load and a save here rather than losing it.
pub(crate) struct InvalidPanel {
name: SharedString,
focus_handle: FocusHandle,
@@ -13,36 +20,42 @@ pub(crate) struct InvalidPanel {
}
impl InvalidPanel {
pub(crate) fn new(name: &str, state: PanelState, _: &mut Window, cx: &mut App) -> Self {
pub(crate) fn new(
name: impl Into<SharedString>,
state: PanelState,
cx: &mut Context<Self>,
) -> Self {
Self {
focus_handle: cx.focus_handle(),
name: SharedString::from(name.to_owned()),
name: name.into(),
old_state: state,
}
}
}
impl Panel for InvalidPanel {
impl gpui_base::dock::Panel for InvalidPanel {
fn panel_name(&self) -> &'static str {
"InvalidPanel"
}
fn dump(&self, _cx: &App) -> super::PanelState {
fn dump(&self, _: &App) -> PanelState {
self.old_state.clone()
}
}
impl Panel for InvalidPanel {}
impl EventEmitter<PanelEvent> for InvalidPanel {}
impl Focusable for InvalidPanel {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl Render for InvalidPanel {
fn render(
&mut self,
_: &mut gpui::Window,
cx: &mut gpui::Context<Self>,
) -> impl gpui::IntoElement {
gpui::div()
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.my_6()
.flex()
+72 -1002
View File
File diff suppressed because it is too large Load Diff
-351
View File
@@ -1,351 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use gpui::{
AnyElement, AnyView, App, AppContext as _, Context, Entity, EntityId, EventEmitter,
FocusHandle, Focusable, Global, IntoElement, Render, SharedString, WeakEntity, Window,
};
use gpui_component::button::Button;
use gpui_component::menu::PopupMenu;
use super::{DockArea, PanelInfo, PanelState, TabPanel};
use crate::invalid_panel::InvalidPanel;
use crate::t;
pub enum PanelEvent {
ZoomIn,
ZoomOut,
LayoutChanged,
}
#[derive(Clone, Copy, Default)]
pub enum PanelControl {
Both,
#[default]
Menu,
Toolbar,
}
impl PanelControl {
#[inline]
pub fn toolbar_visible(&self) -> bool {
matches!(self, PanelControl::Both | PanelControl::Toolbar)
}
#[inline]
pub fn menu_visible(&self) -> bool {
matches!(self, PanelControl::Both | PanelControl::Menu)
}
}
/// The Panel trait used to define the panel.
#[allow(unused_variables)]
pub trait Panel: EventEmitter<PanelEvent> + Render + Focusable {
/// The name of the panel used to serialize, deserialize and identify the panel.
///
/// This is used to identify the panel when deserializing the panel.
/// Once you have defined a panel name, this must not be changed.
fn panel_name(&self) -> &'static str;
/// The name of the tab of the panel, default is `None`.
///
/// Used to display in the already collapsed tab panel.
fn tab_name(&self, cx: &App) -> Option<SharedString> {
None
}
/// The title of the panel
fn title(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
t("Dock.Unnamed")
}
/// The suffix of the panel title, default is `None`.
///
/// This is used to add a suffix element to the panel title.
fn title_suffix(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<impl IntoElement> {
None::<gpui::Div>
}
/// Whether the panel can be closed, default is `true`.
///
/// This method called in Panel render, we should make sure it is fast.
fn closable(&self, cx: &App) -> bool {
true
}
/// Return `PanelControl` if the panel is zoomable, default is `PanelControl::Menu`.
///
/// This method called in Panel render, we should make sure it is fast.
fn zoomable(&self, cx: &App) -> Option<PanelControl> {
Some(PanelControl::Menu)
}
/// Return false to hide panel, true to show panel, default is `true`.
///
/// This method called in Panel render, we should make sure it is fast.
fn visible(&self, cx: &App) -> bool {
true
}
/// Set active state of the panel.
///
/// Called with the frame-end net state when this panel becomes (or stops
/// being) the displayed tab of its tab group: exactly one notification
/// per edge, delivered on the next tick after the change — never
/// same-value repeats nor false→true flips within one frame.
///
/// A panel removed from its group is NOT told `false`; [`Panel::on_removed`]
/// is the deactivation signal. A hidden panel occupying `active_ix` still
/// receives `true` even though rendering falls back to the first visible
/// panel, and panels inside a bare `DockItem::Panel` (no tab group) are
/// outside this contract.
fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {}
/// Set zoomed state of the panel.
///
/// This method will be called when the panel is zoomed or unzoomed.
///
/// Only current Panel will touch this method.
fn set_zoomed(&mut self, zoomed: bool, window: &mut Window, cx: &mut Context<Self>) {}
/// When this Panel is added to a TabPanel, this will be called.
fn on_added_to(
&mut self,
tab_panel: WeakEntity<TabPanel>,
window: &mut Window,
cx: &mut Context<Self>,
) {
}
/// When this Panel is removed from a TabPanel, this will be called.
fn on_removed(&mut self, window: &mut Window, cx: &mut Context<Self>) {}
/// The addition dropdown menu of the panel, default is `None`.
fn dropdown_menu(
&mut self,
this: PopupMenu,
window: &mut Window,
cx: &mut Context<Self>,
) -> PopupMenu {
this
}
/// The addition toolbar buttons of the panel used to show in the right of the title bar, default is `None`.
fn toolbar_buttons(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<Vec<Button>> {
None
}
/// Dump the panel, used to serialize the panel.
fn dump(&self, cx: &App) -> PanelState {
PanelState::new(self)
}
}
/// The PanelView trait used to define the panel view.
#[allow(unused_variables)]
pub trait PanelView: 'static + Send + Sync {
fn panel_name(&self, cx: &App) -> &'static str;
fn panel_id(&self, cx: &App) -> EntityId;
fn tab_name(&self, cx: &App) -> Option<SharedString>;
fn title(&self, window: &mut Window, cx: &mut App) -> AnyElement;
fn title_suffix(&self, window: &mut Window, cx: &mut App) -> Option<AnyElement>;
fn closable(&self, cx: &App) -> bool;
fn zoomable(&self, cx: &App) -> Option<PanelControl>;
fn visible(&self, cx: &App) -> bool;
fn set_active(&self, active: bool, window: &mut Window, cx: &mut App);
fn set_zoomed(&self, zoomed: bool, window: &mut Window, cx: &mut App);
fn on_added_to(&self, tab_panel: WeakEntity<TabPanel>, window: &mut Window, cx: &mut App);
fn on_removed(&self, window: &mut Window, cx: &mut App);
fn dropdown_menu(&self, menu: PopupMenu, window: &mut Window, cx: &mut App) -> PopupMenu;
fn toolbar_buttons(&self, window: &mut Window, cx: &mut App) -> Option<Vec<Button>>;
fn view(&self) -> AnyView;
fn focus_handle(&self, cx: &App) -> FocusHandle;
fn dump(&self, cx: &App) -> PanelState;
}
impl<T: Panel> PanelView for Entity<T> {
fn panel_name(&self, cx: &App) -> &'static str {
self.read(cx).panel_name()
}
fn panel_id(&self, _: &App) -> EntityId {
self.entity_id()
}
fn tab_name(&self, cx: &App) -> Option<SharedString> {
self.read(cx).tab_name(cx)
}
fn title(&self, window: &mut Window, cx: &mut App) -> AnyElement {
self.update(cx, |this, cx| this.title(window, cx).into_any_element())
}
fn title_suffix(&self, window: &mut Window, cx: &mut App) -> Option<AnyElement> {
self.update(cx, |this, cx| {
this.title_suffix(window, cx)
.map(|el| el.into_any_element())
})
}
fn closable(&self, cx: &App) -> bool {
self.read(cx).closable(cx)
}
fn zoomable(&self, cx: &App) -> Option<PanelControl> {
self.read(cx).zoomable(cx)
}
fn visible(&self, cx: &App) -> bool {
self.read(cx).visible(cx)
}
fn set_active(&self, active: bool, window: &mut Window, cx: &mut App) {
self.update(cx, |this, cx| {
this.set_active(active, window, cx);
})
}
fn set_zoomed(&self, zoomed: bool, window: &mut Window, cx: &mut App) {
self.update(cx, |this, cx| {
this.set_zoomed(zoomed, window, cx);
})
}
fn on_added_to(&self, tab_panel: WeakEntity<TabPanel>, window: &mut Window, cx: &mut App) {
self.update(cx, |this, cx| this.on_added_to(tab_panel, window, cx));
}
fn on_removed(&self, window: &mut Window, cx: &mut App) {
self.update(cx, |this, cx| this.on_removed(window, cx));
}
fn dropdown_menu(&self, menu: PopupMenu, window: &mut Window, cx: &mut App) -> PopupMenu {
self.update(cx, |this, cx| this.dropdown_menu(menu, window, cx))
}
fn toolbar_buttons(&self, window: &mut Window, cx: &mut App) -> Option<Vec<Button>> {
self.update(cx, |this, cx| this.toolbar_buttons(window, cx))
}
fn view(&self) -> AnyView {
self.clone().into()
}
fn focus_handle(&self, cx: &App) -> FocusHandle {
self.read(cx).focus_handle(cx)
}
fn dump(&self, cx: &App) -> PanelState {
self.read(cx).dump(cx)
}
}
impl From<&dyn PanelView> for AnyView {
fn from(handle: &dyn PanelView) -> Self {
handle.view()
}
}
impl<T: Panel> From<&dyn PanelView> for Entity<T> {
fn from(value: &dyn PanelView) -> Self {
value.view().downcast::<T>().unwrap()
}
}
impl PartialEq for dyn PanelView {
fn eq(&self, other: &Self) -> bool {
self.view() == other.view()
}
}
/// The deserializer used by [`PanelRegistry`] to rebuild a panel from its
/// persisted [`PanelState`].
type PanelBuilder = dyn Fn(
WeakEntity<DockArea>,
&PanelState,
&PanelInfo,
&mut Window,
&mut App,
) -> Box<dyn PanelView>;
pub struct PanelRegistry {
pub(super) items: HashMap<String, Arc<PanelBuilder>>,
}
impl PanelRegistry {
/// Initialize the panel registry.
pub(crate) fn init(cx: &mut App) {
if cx.try_global::<PanelRegistry>().is_none() {
cx.set_global(PanelRegistry::new());
}
}
pub fn new() -> Self {
Self {
items: HashMap::new(),
}
}
pub fn global(cx: &App) -> &Self {
cx.global::<PanelRegistry>()
}
pub fn global_mut(cx: &mut App) -> &mut Self {
cx.global_mut::<PanelRegistry>()
}
/// Build a panel by name.
///
/// If not registered, return InvalidPanel.
pub fn build_panel(
panel_name: &str,
dock_area: WeakEntity<DockArea>,
panel_state: &PanelState,
panel_info: &PanelInfo,
window: &mut Window,
cx: &mut App,
) -> Box<dyn PanelView> {
if let Some(view) = Self::global(cx)
.items
.get(panel_name)
.cloned()
.map(|f| f(dock_area, panel_state, panel_info, window, cx))
{
view
} else {
// Show an invalid panel if the panel is not registered.
Box::new(cx.new(|cx| InvalidPanel::new(panel_name, panel_state.clone(), window, cx)))
}
}
}
impl Default for PanelRegistry {
fn default() -> Self {
Self::new()
}
}
impl Global for PanelRegistry {}
/// Register the Panel init by panel_name to global registry.
pub fn register_panel<F>(cx: &mut App, panel_name: &str, deserialize: F)
where
F: Fn(
WeakEntity<DockArea>,
&PanelState,
&PanelInfo,
&mut Window,
&mut App,
) -> Box<dyn PanelView>
+ 'static,
{
PanelRegistry::init(cx);
PanelRegistry::global_mut(cx)
.items
.insert(panel_name.to_string(), Arc::new(deserialize));
}
-232
View File
@@ -1,232 +0,0 @@
//! Vendored from `gpui-base`'s private `resizable::resize_handle` module
//! (v0.5.2, rev 9e3a29dcbdebc318632bf68203f26c33e9f0e902). gpui-component
//! keeps this and [`PANEL_MIN_SIZE`] crate-private, so the dock crate carries
//! its own copy.
use std::cell::Cell;
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, Axis, Element, ElementId, Entity, GlobalElementId, InteractiveElement,
IntoElement, MouseDownEvent, MouseUpEvent, ParentElement as _, Pixels, Point, Render,
StatefulInteractiveElement, Styled as _, Window, div, px,
};
use gpui_component::{ActiveTheme as _, AxisExt as _, Side};
pub(crate) const PANEL_MIN_SIZE: Pixels = px(100.);
pub(crate) const HANDLE_PADDING: Pixels = px(4.);
pub(crate) const HANDLE_SIZE: Pixels = px(1.);
/// Create a resize handle for a resizable panel.
#[doc(hidden)]
pub fn resize_handle<T: 'static, E: 'static + Render>(
id: impl Into<ElementId>,
axis: Axis,
) -> ResizeHandle<T, E> {
ResizeHandle::new(id, axis)
}
type DragHandler<E> = dyn Fn(&Point<Pixels>, &mut Window, &mut App) -> Entity<E>;
#[doc(hidden)]
pub struct ResizeHandle<T: 'static, E: 'static + Render> {
id: ElementId,
axis: Axis,
drag_value: Option<Rc<T>>,
placement: Option<Side>,
on_drag: Option<Rc<DragHandler<E>>>,
}
impl<T: 'static, E: 'static + Render> ResizeHandle<T, E> {
fn new(id: impl Into<ElementId>, axis: Axis) -> Self {
let id = id.into();
Self {
id: id.clone(),
on_drag: None,
drag_value: None,
placement: None,
axis,
}
}
pub fn on_drag(
mut self,
value: T,
f: impl Fn(Rc<T>, &Point<Pixels>, &mut Window, &mut App) -> Entity<E> + 'static,
) -> Self {
let value = Rc::new(value);
self.drag_value = Some(value.clone());
self.on_drag = Some(Rc::new(move |p, window, cx| {
f(value.clone(), p, window, cx)
}));
self
}
pub fn placement(mut self, placement: Side) -> Self {
self.placement = Some(placement);
self
}
}
#[derive(Default, Debug, Clone)]
struct ResizeHandleState {
active: Cell<bool>,
}
impl ResizeHandleState {
fn set_active(&self, active: bool) {
self.active.set(active);
}
fn is_active(&self) -> bool {
self.active.get()
}
}
impl<T: 'static, E: 'static + Render> IntoElement for ResizeHandle<T, E> {
type Element = ResizeHandle<T, E>;
fn into_element(self) -> Self::Element {
self
}
}
impl<T: 'static, E: 'static + Render> Element for ResizeHandle<T, E> {
type PrepaintState = ();
type RequestLayoutState = AnyElement;
fn id(&self) -> Option<ElementId> {
Some(self.id.clone())
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
id: Option<&GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (gpui::LayoutId, Self::RequestLayoutState) {
let neg_offset = -HANDLE_PADDING;
let axis = self.axis;
window.with_element_state(id.unwrap(), |state: Option<ResizeHandleState>, window| {
let state = state.unwrap_or_default();
let bg_color = if state.is_active() {
cx.theme().drag_border
} else {
cx.theme().border
};
let mut el = div()
.id(self.id.clone())
.occlude()
.absolute()
.flex_shrink_0()
.group("handle")
.when_some(self.on_drag.clone(), |this, on_drag| {
this.on_drag(
self.drag_value.clone().unwrap(),
move |_, position, window, cx| on_drag(&position, window, cx),
)
})
.map(|this| match self.placement {
Some(Side::Left) => {
// Special for Left Dock
// FIXME: Improve this to let the scroll bar have px(HANDLE_PADDING)
this.cursor_col_resize()
.top_0()
.right(px(1.))
.h_full()
.w(HANDLE_SIZE)
.pl(HANDLE_PADDING)
}
_ => this
.when(axis.is_horizontal(), |this| {
this.cursor_col_resize()
.top_0()
.left(neg_offset)
.h_full()
.w(HANDLE_SIZE)
.px(HANDLE_PADDING)
})
.when(axis.is_vertical(), |this| {
this.cursor_row_resize()
.top(neg_offset)
.left_0()
.w_full()
.h(HANDLE_SIZE)
.py(HANDLE_PADDING)
}),
})
.child(
div()
.bg(bg_color)
.group_hover("handle", |this| this.bg(bg_color))
.when(axis.is_horizontal(), |this| this.h_full().w(HANDLE_SIZE))
.when(axis.is_vertical(), |this| this.w_full().h(HANDLE_SIZE)),
)
.into_any_element();
let layout_id = el.request_layout(window, cx);
((layout_id, el), state)
})
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<Pixels>,
request_layout: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) -> Self::PrepaintState {
request_layout.prepaint(window, cx);
}
fn paint(
&mut self,
id: Option<&GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
bounds: gpui::Bounds<Pixels>,
request_layout: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
request_layout.paint(window, cx);
window.with_element_state(id.unwrap(), |state: Option<ResizeHandleState>, window| {
let state = state.unwrap_or_default();
window.on_mouse_event({
let state = state.clone();
move |ev: &MouseDownEvent, phase, window, _| {
if bounds.contains(&ev.position) && phase.bubble() {
state.set_active(true);
window.refresh();
}
}
});
window.on_mouse_event({
let state = state.clone();
move |_: &MouseUpEvent, _, window, _| {
if state.is_active() {
state.set_active(false);
window.refresh();
}
}
});
((), state)
});
}
}
-397
View File
@@ -1,397 +0,0 @@
use std::sync::Arc;
use gpui::{
App, AppContext as _, Axis, Context, DismissEvent, Entity, EventEmitter, FocusHandle,
Focusable, IntoElement, ParentElement, Pixels, Render, Styled, Subscription, WeakEntity,
Window,
};
use gpui_component::{
ActiveTheme, Placement, ResizablePanelEvent, ResizablePanelGroup, ResizableState, h_flex,
resizable_panel,
};
use smallvec::SmallVec;
use super::{DockArea, Panel, PanelEvent, PanelState, PanelView, TabPanel};
use crate::PanelInfo;
use crate::resize_handle::PANEL_MIN_SIZE;
pub struct StackPanel {
pub(super) parent: Option<WeakEntity<StackPanel>>,
pub(super) axis: Axis,
focus_handle: FocusHandle,
pub(crate) panels: SmallVec<[Arc<dyn PanelView>; 2]>,
state: Entity<ResizableState>,
_subscriptions: Vec<Subscription>,
}
impl Panel for StackPanel {
fn panel_name(&self) -> &'static str {
"StackPanel"
}
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
"StackPanel"
}
fn set_active(&mut self, active: bool, window: &mut Window, cx: &mut Context<Self>) {
for panel in &self.panels {
panel.set_active(active, window, cx);
}
}
fn dump(&self, cx: &App) -> PanelState {
let sizes = self.state.read(cx).sizes().clone();
let mut state = PanelState::new(self);
state.info = PanelInfo::stack(sizes, self.axis);
for panel in &self.panels {
state.add_child(panel.dump(cx));
}
state
}
}
impl StackPanel {
pub fn new(axis: Axis, _: &mut Window, cx: &mut Context<Self>) -> Self {
let state = cx.new(|_| ResizableState::default());
let _subscriptions = vec![
// Bubble up the resize event.
cx.subscribe(&state, |_, _, _: &ResizablePanelEvent, cx| {
cx.emit(PanelEvent::LayoutChanged)
}),
];
Self {
axis,
parent: None,
focus_handle: cx.focus_handle(),
panels: SmallVec::new(),
state,
_subscriptions,
}
}
/// The first level of the stack panel is root, will not have a parent.
fn is_root(&self) -> bool {
self.parent.is_none()
}
/// Return true if self or parent only have last panel.
pub(super) fn is_last_panel(&self, cx: &App) -> bool {
if self.panels.len() > 1 {
return false;
}
if let Some(parent) = &self.parent
&& let Some(parent) = parent.upgrade()
{
return parent.read(cx).is_last_panel(cx);
}
true
}
pub(super) fn panels_len(&self) -> usize {
self.panels.len()
}
/// Return the index of the panel.
pub(crate) fn index_of_panel(&self, panel: Arc<dyn PanelView>) -> Option<usize> {
self.panels.iter().position(|p| p == &panel)
}
fn assert_panel_is_valid(&self, panel: &Arc<dyn PanelView>) {
assert!(
panel.view().downcast::<TabPanel>().is_ok()
|| panel.view().downcast::<StackPanel>().is_ok(),
"Panel must be a `TabPanel` or `StackPanel`"
);
}
/// Add a panel at the end of the stack.
///
/// If `size` is `None`, the panel will be given the average size of all panels in the stack.
///
/// The `panel` must be a [`TabPanel`] or [`StackPanel`].
pub fn add_panel(
&mut self,
panel: Arc<dyn PanelView>,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.insert_panel(panel, self.panels.len(), size, dock_area, window, cx);
}
/// Add a panel at the [`Placement`].
///
/// The `panel` must be a [`TabPanel`] or [`StackPanel`].
pub fn add_panel_at(
&mut self,
panel: Arc<dyn PanelView>,
placement: Placement,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.insert_panel_at(
panel,
self.panels_len(),
placement,
size,
dock_area,
window,
cx,
);
}
/// Insert a panel at the index.
///
/// The `panel` must be a [`TabPanel`] or [`StackPanel`].
#[allow(clippy::too_many_arguments)]
pub fn insert_panel_at(
&mut self,
panel: Arc<dyn PanelView>,
ix: usize,
placement: Placement,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
match placement {
Placement::Top | Placement::Left => {
self.insert_panel_before(panel, ix, size, dock_area, window, cx)
}
Placement::Right | Placement::Bottom => {
self.insert_panel_after(panel, ix, size, dock_area, window, cx)
}
}
}
/// Insert a panel at the index.
///
/// The `panel` must be a [`TabPanel`] or [`StackPanel`].
pub fn insert_panel_before(
&mut self,
panel: Arc<dyn PanelView>,
ix: usize,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.insert_panel(panel, ix, size, dock_area, window, cx);
}
/// Insert a panel after the index.
///
/// The `panel` must be a [`TabPanel`] or [`StackPanel`].
pub fn insert_panel_after(
&mut self,
panel: Arc<dyn PanelView>,
ix: usize,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.insert_panel(panel, ix + 1, size, dock_area, window, cx);
}
fn insert_panel(
&mut self,
panel: Arc<dyn PanelView>,
ix: usize,
size: Option<Pixels>,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.assert_panel_is_valid(&panel);
// If the panel is already in the stack, return.
if self.index_of_panel(panel.clone()).is_some() {
return;
}
let view = cx.entity().clone();
window.defer(cx, {
let panel = panel.clone();
move |window, cx| {
// If the panel is a TabPanel, set its parent to this.
if let Ok(tab_panel) = panel.view().downcast::<TabPanel>() {
tab_panel.update(cx, |tab_panel, _| tab_panel.set_parent(view.downgrade()));
} else if let Ok(stack_panel) = panel.view().downcast::<Self>() {
stack_panel.update(cx, |stack_panel, _| {
stack_panel.parent = Some(view.downgrade())
});
}
// Subscribe to the panel's layout change event.
_ = dock_area.update(cx, |this, cx| {
if let Ok(tab_panel) = panel.view().downcast::<TabPanel>() {
this.subscribe_panel(&tab_panel, window, cx);
} else if let Ok(stack_panel) = panel.view().downcast::<Self>() {
this.subscribe_panel(&stack_panel, window, cx);
}
});
}
});
let ix = if ix > self.panels.len() {
self.panels.len()
} else {
ix
};
// Get avg size of all panels to insert new panel, if size is None.
let size = match size {
Some(size) => size,
None => {
let state = self.state.read(cx);
(state.container_size() / (state.sizes().len() + 1) as f32).max(PANEL_MIN_SIZE)
}
};
self.panels.insert(ix, panel.clone());
self.state.update(cx, |state, cx| {
state.insert_panel(Some(size), Some(ix), cx);
});
cx.emit(PanelEvent::LayoutChanged);
cx.notify();
}
/// Remove panel from the stack.
///
/// If `ix` is not found, do nothing.
pub fn remove_panel(
&mut self,
panel: Arc<dyn PanelView>,
window: &mut Window,
cx: &mut Context<Self>,
) {
let Some(ix) = self.index_of_panel(panel.clone()) else {
return;
};
self.panels.remove(ix);
self.state.update(cx, |state, cx| {
state.remove_panel(ix, cx);
});
cx.emit(PanelEvent::LayoutChanged);
self.remove_self_if_empty(window, cx);
}
/// Replace the old panel with the new panel at same index.
pub(super) fn replace_panel(
&mut self,
old_panel: Arc<dyn PanelView>,
new_panel: Entity<StackPanel>,
_: &mut Window,
cx: &mut Context<Self>,
) {
if let Some(ix) = self.index_of_panel(old_panel.clone()) {
self.panels[ix] = Arc::new(new_panel.clone());
self.state.update(cx, |state, cx| {
state.reset_panel(ix, cx);
});
cx.emit(PanelEvent::LayoutChanged);
}
}
/// If children is empty, remove self from parent view.
pub(crate) fn remove_self_if_empty(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.is_root() {
return;
}
if !self.panels.is_empty() {
return;
}
let view = cx.entity().clone();
if let Some(parent) = self.parent.as_ref() {
_ = parent.update(cx, |parent, cx| {
parent.remove_panel(Arc::new(view.clone()), window, cx);
});
}
cx.emit(PanelEvent::LayoutChanged);
cx.notify();
}
/// Find the first top left in the stack.
pub(super) fn left_top_tab_panel(
&self,
check_parent: bool,
cx: &App,
) -> Option<Entity<TabPanel>> {
if check_parent
&& let Some(parent) = self.parent.as_ref().and_then(|parent| parent.upgrade())
&& let Some(panel) = parent.read(cx).left_top_tab_panel(true, cx)
{
return Some(panel);
}
let first_panel = self.panels.first();
if let Some(view) = first_panel {
if let Ok(tab_panel) = view.view().downcast::<TabPanel>() {
Some(tab_panel)
} else if let Ok(stack_panel) = view.view().downcast::<StackPanel>() {
stack_panel.read(cx).left_top_tab_panel(false, cx)
} else {
None
}
} else {
None
}
}
/// Remove all panels from the stack.
pub(super) fn remove_all_panels(&mut self, _: &mut Window, cx: &mut Context<Self>) {
self.panels.clear();
self.state.update(cx, |state, cx| {
state.clear();
cx.notify();
});
}
/// Change the axis of the stack panel.
pub(super) fn set_axis(&mut self, axis: Axis, _: &mut Window, cx: &mut Context<Self>) {
self.axis = axis;
cx.notify();
}
}
impl Focusable for StackPanel {
fn focus_handle(&self, _cx: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl EventEmitter<PanelEvent> for StackPanel {}
impl EventEmitter<DismissEvent> for StackPanel {}
impl Render for StackPanel {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
h_flex()
.size_full()
.overflow_hidden()
.bg(cx.theme().tokens.tab_bar)
.child(
ResizablePanelGroup::new("stack-panel-group")
.with_state(&self.state)
.axis(self.axis)
.children(self.panels.clone().into_iter().map(|panel| {
resizable_panel()
.child(panel.view())
.visible(panel.visible(cx))
})),
)
}
}
-233
View File
@@ -1,233 +0,0 @@
use gpui::{App, AppContext, Axis, Entity, Pixels, WeakEntity, Window};
use itertools::Itertools as _;
use serde::{Deserialize, Serialize};
use super::{Dock, DockArea, DockItem, DockPlacement, Panel, PanelRegistry};
/// Used to serialize and deserialize the DockArea
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
pub struct DockAreaState {
/// The version is used to mark this persisted state is compatible with the current version
/// For example, some times we many totally changed the structure of the Panel,
/// then we can compare the version to decide whether we can use the state or ignore.
#[serde(default)]
pub version: Option<usize>,
pub center: PanelState,
#[serde(skip_serializing_if = "Option::is_none")]
pub left_dock: Option<DockState>,
}
/// Used to serialize and deserialize the Dock
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DockState {
panel: PanelState,
placement: DockPlacement,
size: Pixels,
open: bool,
}
impl DockState {
pub fn new(dock: Entity<Dock>, cx: &App) -> Self {
let dock = dock.read(cx);
Self {
placement: dock.placement,
size: dock.size,
open: dock.open,
panel: dock.panel.view().dump(cx),
}
}
/// Convert the DockState to Dock
pub fn to_dock(
&self,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut App,
) -> Entity<Dock> {
let item = self.panel.to_item(dock_area.clone(), window, cx);
cx.new(|cx| {
Dock::from_state(
dock_area.clone(),
self.placement,
self.size,
item,
self.open,
window,
cx,
)
})
}
}
/// Used to serialize and deserialize the DockerItem
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PanelState {
pub panel_name: String,
pub children: Vec<PanelState>,
pub info: PanelInfo,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PanelInfo {
#[serde(rename = "stack")]
Stack {
sizes: Vec<Pixels>,
axis: usize, // 0 for horizontal, 1 for vertical
},
#[serde(rename = "tabs")]
Tabs { active_index: usize },
#[serde(rename = "panel")]
Panel(serde_json::Value),
}
impl PanelInfo {
pub fn stack(sizes: Vec<Pixels>, axis: Axis) -> Self {
Self::Stack {
sizes,
axis: if axis == Axis::Horizontal { 0 } else { 1 },
}
}
pub fn tabs(active_index: usize) -> Self {
Self::Tabs { active_index }
}
pub fn panel(info: serde_json::Value) -> Self {
Self::Panel(info)
}
pub fn axis(&self) -> Option<Axis> {
match self {
Self::Stack { axis, .. } => Some(if *axis == 0 {
Axis::Horizontal
} else {
Axis::Vertical
}),
_ => None,
}
}
pub fn sizes(&self) -> Option<&Vec<Pixels>> {
match self {
Self::Stack { sizes, .. } => Some(sizes),
_ => None,
}
}
pub fn active_index(&self) -> Option<usize> {
match self {
Self::Tabs { active_index } => Some(*active_index),
_ => None,
}
}
}
impl Default for PanelState {
fn default() -> Self {
Self {
panel_name: "".to_string(),
children: Vec::new(),
info: PanelInfo::Panel(serde_json::Value::Null),
}
}
}
impl PanelState {
pub fn new<P: Panel>(panel: &P) -> Self {
Self {
panel_name: panel.panel_name().to_string(),
..Default::default()
}
}
pub fn add_child(&mut self, panel: PanelState) {
self.children.push(panel);
}
pub fn to_item(
&self,
dock_area: WeakEntity<DockArea>,
window: &mut Window,
cx: &mut App,
) -> DockItem {
let info = self.info.clone();
let items: Vec<DockItem> = self
.children
.iter()
.map(|child| child.to_item(dock_area.clone(), window, cx))
.collect();
match info {
PanelInfo::Stack { sizes, axis } => {
let axis = if axis == 0 {
Axis::Horizontal
} else {
Axis::Vertical
};
let sizes = sizes.iter().map(|s| Some(*s)).collect_vec();
DockItem::split_with_sizes(axis, items, sizes, &dock_area, window, cx)
}
PanelInfo::Tabs { active_index } => {
if items.len() == 1 {
return items[0].clone();
}
let items = items
.iter()
.flat_map(|item| match item {
DockItem::Tabs { items, .. } => items.clone(),
_ => {
// ignore invalid panels in tabs
vec![]
}
})
.collect_vec();
DockItem::tabs(items, &dock_area, window, cx).active_index(active_index, cx)
}
PanelInfo::Panel(_) => {
let view = PanelRegistry::build_panel(
&self.panel_name,
dock_area.clone(),
self,
&info,
window,
cx,
);
DockItem::tabs(vec![view.into()], &dock_area, window, cx)
}
}
}
}
#[cfg(test)]
mod tests {
use gpui::px;
use super::*;
#[test]
fn test_deserialize_item_state() {
let json = include_str!("fixtures/layout.json");
let state: DockAreaState = serde_json::from_str(json).unwrap();
assert_eq!(state.version, None);
assert_eq!(state.center.panel_name, "StackPanel");
assert_eq!(state.center.children.len(), 2);
assert_eq!(state.center.children[0].panel_name, "TabPanel");
assert_eq!(state.center.children[1].children.len(), 1);
assert_eq!(
state.center.children[1].children[0].panel_name,
"StoryContainer"
);
assert_eq!(state.center.children[1].panel_name, "TabPanel");
let left_dock = state.left_dock.unwrap();
assert!(left_dock.open);
assert_eq!(left_dock.size, px(350.0));
assert_eq!(left_dock.placement, DockPlacement::Left);
assert_eq!(left_dock.panel.panel_name, "TabPanel");
assert_eq!(left_dock.panel.children.len(), 1);
assert_eq!(left_dock.panel.children[0].panel_name, "StoryContainer");
}
}
-469
View File
@@ -1,469 +0,0 @@
use std::sync::Arc;
use gpui::prelude::FluentBuilder;
use gpui::{
AnyElement, App, AppContext, ElementId, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, RenderOnce, ScrollHandle, StatefulInteractiveElement, Styled as _, Window,
div, px,
};
use gpui_base::{InteractiveElementExt, Tab, Tabs};
use gpui_component::{ActiveTheme, ElementExt, h_flex};
use super::{AnyDrag, DragPanel, PanelView, TabPanel};
use crate::TAB_BAR_HEIGHT;
/// The dock's custom tab bar, built on gpui-base's unstyled [`Tab`]/[`Tabs`].
///
/// The dock owns the pill presentation; the layout mirrors gpui-component's
/// `TabBar`: a prefix (dock toggle / tab navigation), a scrollable tab strip
/// with a trailing drop target, then a suffix (panel toolbar).
///
/// Tabs are draggable to move panels between groups and double as drop
/// targets, so panel-level events are forwarded to the owning [`TabPanel`].
#[derive(IntoElement)]
pub(crate) struct TabBar {
id: ElementId,
panels: Vec<Arc<dyn PanelView>>,
active_panel: Option<Arc<dyn PanelView>>,
collapsed: bool,
draggable: bool,
droppable: bool,
tab_panel: Entity<TabPanel>,
scroll_handle: ScrollHandle,
prefix: Option<AnyElement>,
suffix: Option<AnyElement>,
empty_space: Option<AnyElement>,
}
impl TabBar {
pub(crate) fn new(id: impl Into<ElementId>, tab_panel: Entity<TabPanel>) -> Self {
Self {
id: id.into(),
panels: Vec::new(),
active_panel: None,
collapsed: false,
draggable: false,
droppable: false,
tab_panel,
scroll_handle: ScrollHandle::new(),
prefix: None,
suffix: None,
empty_space: None,
}
}
/// The panels to show as tabs, in strip order.
pub(crate) fn panels(mut self, panels: Vec<Arc<dyn PanelView>>) -> Self {
self.panels = panels;
self
}
/// The currently active panel; its tab is rendered as the filled pill.
pub(crate) fn active_panel(mut self, active_panel: Option<Arc<dyn PanelView>>) -> Self {
self.active_panel = active_panel;
self
}
/// Collapsed tab panels render no suffix or trailing drop target, and
/// their tabs lose the active style and all interactions.
pub(crate) fn collapsed(mut self, collapsed: bool) -> Self {
self.collapsed = collapsed;
self
}
/// Whether the tabs can start a panel drag.
pub(crate) fn draggable(mut self, draggable: bool) -> Self {
self.draggable = draggable;
self
}
/// Whether the tabs and trailing space accept drops.
pub(crate) fn droppable(mut self, droppable: bool) -> Self {
self.droppable = droppable;
self
}
/// Track the strip's scroll state with the given handle, so callers can
/// scroll a tab into view with [`ScrollHandle::scroll_to_item`].
pub(crate) fn scroll_handle(mut self, scroll_handle: &ScrollHandle) -> Self {
self.scroll_handle = scroll_handle.clone();
self
}
/// Element shown before the tab strip.
pub(crate) fn prefix(mut self, prefix: impl IntoElement) -> Self {
self.prefix = Some(prefix.into_any_element());
self
}
/// Element shown after the tab strip.
pub(crate) fn suffix(mut self, suffix: impl IntoElement) -> Self {
self.suffix = Some(suffix.into_any_element());
self
}
/// Replace the trailing empty space (the drop target after the last tab).
#[cfg(test)]
pub(crate) fn empty_space(mut self, empty_space: impl IntoElement) -> Self {
self.empty_space = Some(empty_space.into_any_element());
self
}
fn render_tab(
&self,
ix: usize,
panel: Arc<dyn PanelView>,
active: bool,
window: &mut Window,
cx: &mut App,
) -> Tab {
// While collapsed, tabs lose the active style and all interactions.
let droppable = self.collapsed;
let tab_panel = self.tab_panel.clone();
// The `ix` element id keeps each tab's identity stable across renders.
Tab::new(ix)
.h_6()
.px_3()
.text_sm()
.whitespace_nowrap()
.flex()
.items_center()
.justify_center()
.gap_1()
.flex_shrink_0()
.overflow_hidden()
.rounded(cx.theme().radius)
.text_color(cx.theme().foreground)
.map(|this| {
if let Some(tab_name) = panel.tab_name(cx) {
this.child(tab_name)
} else {
this.child(panel.title(window, cx))
}
})
// Pill presentation: the selected tab is the filled pill, the
// rest are transparent until hovered.
.styles(|styles| {
styles.selected(|style| {
style
.text_color(cx.theme().tab_active_foreground)
.bg(cx.theme().tab_active)
})
})
.hover(|this| {
if active {
this
} else {
this.text_color(cx.theme().secondary_foreground)
.bg(cx.theme().secondary_hover)
}
})
.selected(active)
.on_click(move |_, window, cx| {
tab_panel.update(cx, |view, cx| view.set_active_ix(ix, window, cx));
})
.when(!droppable, |this| {
this.when(self.draggable, |this| {
this.on_drag(
DragPanel::new(panel.clone(), self.tab_panel.clone()),
|drag, offset, _, cx| {
cx.stop_propagation();
drag.drag_offset.set(offset);
cx.new(|_| drag.clone())
},
)
})
.when(self.droppable, |this| {
this.drag_over::<DragPanel>(|this, _, _, cx| {
this.rounded_l_none()
.border_l_2()
.border_r_0()
.border_color(cx.theme().drag_border)
})
.on_drop({
let tab_panel = self.tab_panel.clone();
move |drag: &DragPanel, window, cx| {
tab_panel.update(cx, |view, cx| {
view.will_split_placement = None;
view.on_drop(drag, Some(ix), true, window, cx);
});
}
})
.drag_over::<AnyDrag>(|this, _, _, cx| {
this.rounded_l_none()
.border_l_2()
.border_r_0()
.border_color(cx.theme().drag_border)
})
.on_drop({
let tab_panel = self.tab_panel.clone();
move |item: &AnyDrag, _, cx| {
tab_panel.update(cx, |view, cx| {
view.will_split_placement = None;
view.emit_drag_drop(item, None, cx);
});
}
})
})
})
}
fn render_empty_space(&self) -> AnyElement {
let tabs_count = self.panels.len();
// The strip after the last tab is a drop target for panels and
// host-owned drag items. Its left edge (right after the last tab)
// marks the start of the title-bar drag overlay.
let mut empty = div()
.id("tab-bar-empty-space")
.h_full()
.flex_grow_1()
.min_w_16()
.on_prepaint({
let view = self.tab_panel.clone();
move |bounds, _, cx| {
view.update(cx, |this, cx| {
if this.title_bar_strip_bounds != Some(bounds) {
this.title_bar_strip_bounds = Some(bounds);
cx.notify();
}
});
}
});
if self.droppable {
empty = empty
.drag_over::<DragPanel>(|this, _, _, cx| this.bg(cx.theme().tokens.drop_target))
.on_drop({
let view = self.tab_panel.clone();
move |drag: &DragPanel, window, cx| {
view.update(cx, |this, cx| {
this.will_split_placement = None;
// Dropping a panel from this same tab group onto
// the strip moves it after the last tab.
let ix = if drag.tab_panel == cx.entity() {
Some(tabs_count - 1)
} else {
None
};
this.on_drop(drag, ix, false, window, cx);
});
}
})
.drag_over::<AnyDrag>(|this, _, _, cx| this.bg(cx.theme().tokens.drop_target))
.on_drop({
let view = self.tab_panel.clone();
move |item: &AnyDrag, _, cx| {
view.update(cx, |this, cx| {
this.will_split_placement = None;
this.emit_drag_drop(item, None, cx);
});
}
});
}
empty.into_any_element()
}
}
impl RenderOnce for TabBar {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let tabs: Vec<_> = self
.panels
.iter()
.enumerate()
.filter_map(|(ix, panel)| {
let mut active = self.active_panel.as_ref() == Some(panel);
if !panel.visible(cx) {
return None;
}
// Always not show active tab style, if the panel is collapsed
if self.collapsed {
active = false;
}
Some(self.render_tab(ix, panel.clone(), active, window, cx))
})
.collect();
let empty_space = match self.empty_space {
Some(empty_space) => empty_space,
None => self.render_empty_space(),
};
Tabs::new(self.id)
.px(px(-1.))
.h(TAB_BAR_HEIGHT)
.flex()
.items_center()
.text_color(cx.theme().tab_foreground)
.when_some(self.prefix, |this, prefix| this.child(prefix))
.child(
h_flex().id("tabs").flex_1().overflow_x_hidden().child(
h_flex()
.id("tabs-inner")
.relative()
.gap(px(4.))
.overflow_x_scroll()
.lock_scroll_axis()
.track_scroll(&self.scroll_handle)
.children(tabs)
.when(!self.collapsed, |this| this.child(empty_space)),
),
)
.when_some(self.suffix, |this, suffix| {
this.when(!self.collapsed, |this| this.child(suffix))
})
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use gpui::{
Context, Entity, MouseButton, Render, TestAppContext, VisualTestContext, WindowOptions,
div, px, size,
};
use gpui_component::{Root, Theme, v_flex};
use super::*;
use crate::DockArea;
use crate::tab_panel::title_bar_drag_handlers;
#[derive(Default)]
struct ProbeFlags {
empty_down: AtomicBool,
empty_click: AtomicBool,
control_down: AtomicBool,
control_click: AtomicBool,
}
struct ProbeView {
flags: Entity<ProbeFlags>,
tab_panel: Entity<TabPanel>,
}
impl Render for ProbeView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let flags = self.flags.clone();
let empty = title_bar_drag_handlers(
div()
.id("empty-space")
.h(TAB_BAR_HEIGHT)
.flex_grow_1()
.min_w_16(),
window,
cx,
)
.debug_selector(|| "empty-space".into())
.on_mouse_down(MouseButton::Left, {
let flags = flags.clone();
move |_, _, cx| flags.update(cx, |f, _| f.empty_down.store(true, Ordering::SeqCst))
})
.on_click({
let flags = flags.clone();
move |_, _, cx| flags.update(cx, |f, _| f.empty_click.store(true, Ordering::SeqCst))
});
let control =
title_bar_drag_handlers(div().id("control-space").h_8().flex_grow_1(), window, cx)
.debug_selector(|| "control-space".into())
.on_mouse_down(MouseButton::Left, {
let flags = flags.clone();
move |_, _, cx| {
flags.update(cx, |f, _| f.control_down.store(true, Ordering::SeqCst))
}
})
.on_click({
let flags = flags.clone();
move |_, _, cx| {
flags.update(cx, |f, _| f.control_click.store(true, Ordering::SeqCst))
}
});
v_flex()
.size_full()
.child(TabBar::new("probe-bar", self.tab_panel.clone()).empty_space(empty))
.child(control)
}
}
/// Diagnostic: verify that the tab bar's trailing empty space receives
/// mouse events when wrapped by `title_bar_drag_handlers`, i.e. the
/// strip's scroll containers do not swallow them.
#[gpui::test]
fn tab_bar_empty_space_receives_events(cx: &mut TestAppContext) {
let (flags, handle) = cx.update(|cx| {
cx.set_global(Theme::default());
let flags = cx.new(|_| ProbeFlags::default());
let handle = cx.open_window(
WindowOptions {
window_bounds: Some(gpui::WindowBounds::Windowed(gpui::Bounds {
origin: gpui::Point::default(),
size: size(px(800.), px(100.)),
})),
..Default::default()
},
|window, cx| {
let flags = flags.clone();
let dock_area = cx.new(|cx| DockArea::new("probe-dock", None, window, cx));
let tab_panel =
cx.new(|cx| TabPanel::new(None, dock_area.downgrade(), window, cx));
let content = cx.new(|_| ProbeView { flags, tab_panel });
cx.new(|cx| Root::new(content, window, cx))
},
);
(flags, handle.unwrap())
});
let mut cx = VisualTestContext::from_window(handle.into(), cx);
cx.run_until_parked();
cx.update(|window, cx| {
_ = window.draw(cx);
});
let empty_bounds = cx
.debug_bounds("empty-space")
.expect("empty-space must be laid out");
let control_bounds = cx
.debug_bounds("control-space")
.expect("control-space must be laid out");
let empty_center = empty_bounds.center();
let control_center = control_bounds.center();
// Control: a plain div with the same handlers, outside the tab bar.
cx.simulate_click(control_center, Default::default());
// Target: the tab bar's empty-space strip.
cx.simulate_click(empty_center, Default::default());
let (empty_down, empty_click, control_down, control_click) = cx.read(|cx| {
let flags = flags.read(cx);
(
flags.empty_down.load(Ordering::SeqCst),
flags.empty_click.load(Ordering::SeqCst),
flags.control_down.load(Ordering::SeqCst),
flags.control_click.load(Ordering::SeqCst),
)
});
assert!(
control_down,
"control mouse_down must fire at {control_center:?}"
);
assert!(
control_click,
"control click must fire at {control_center:?}"
);
assert!(
empty_down,
"empty-space mouse_down must fire at {empty_center:?}"
);
assert!(
empty_click,
"empty-space click must fire at {empty_center:?}"
);
}
}
+628 -1988
View File
File diff suppressed because it is too large Load Diff
+416
View File
@@ -0,0 +1,416 @@
//! The Signed appearance for a tiles canvas.
//!
//! `gpui_base::dock::TilesState` owns the geometry — snapping, the resize
//! arithmetic, the undo stack, the zoom flag — and draws none of it. The tile
//! frame, its title bar and its resize affordances are here, ported from
//! gpui-component's `TilesSkin` (the vendored dock had no tiles canvas, so
//! there is no local look to preserve).
use std::rc::Rc;
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Div, DragMoveEvent, Empty, InteractiveElement as _,
IntoElement, MouseButton, MouseDownEvent, ParentElement as _, Pixels, Render, ScrollHandle,
Size, Stateful, StatefulInteractiveElement as _, Styled as _, Window, div, px,
};
use gpui_base::dock::{
DRAG_BAR_HEIGHT, HANDLE_SIZE, NodeId, ResizeSide, TileContext, TilesRenderer,
};
use gpui_component::button::{Button, ButtonVariants as _};
use gpui_component::menu::{DropdownMenu as _, PopupMenuItem};
use gpui_component::scroll::Scrollbar;
use gpui_component::{
ActiveTheme as _, Icon, IconName, Selectable as _, Sizable as _, h_flex, v_flex,
};
use crate::dock_area::SkinShared;
use crate::tab_panel::panel_title;
use crate::{PanelHandle, t};
/// How far a resize handle sticks out past the tile's edge.
const HANDLE_OFFSET: Pixels = px(-4.);
/// The payload a tile drag carries, so one canvas ignores another's drags.
#[derive(Clone)]
struct DragMoving(NodeId);
impl Render for DragMoving {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
Empty
}
}
/// The payload a tile resize carries, for the same reason.
#[derive(Clone)]
struct DragResizing(NodeId);
impl Render for DragResizing {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
Empty
}
}
/// One tiles canvas's appearance.
///
/// Built per canvas — `DockAreaRenderer::tiles_renderer` is called once per
/// container — so the scroll position belongs to the canvas it scrolls.
pub(crate) struct SignedTilesSkin {
shared: Rc<SkinShared>,
scroll_handle: ScrollHandle,
}
impl SignedTilesSkin {
pub(crate) fn new(shared: Rc<SkinShared>) -> Self {
Self {
shared,
scroll_handle: ScrollHandle::default(),
}
}
/// One edge or corner handle.
fn resize_handle(
&self,
tile: &TileContext,
id: &'static str,
side: ResizeSide,
build: impl FnOnce(Stateful<Div>) -> Stateful<Div>,
) -> Stateful<Div> {
let node = tile.node();
build(div().id(id).absolute())
.on_mouse_down(MouseButton::Left, {
let tile = tile.clone();
move |event: &MouseDownEvent, window, cx| {
tile.begin_resize(side, event.position, window, cx);
cx.stop_propagation();
}
})
.on_drag(DragResizing(node), |drag, _, _, cx| {
cx.stop_propagation();
cx.new(|_| drag.clone())
})
.on_drag_move({
let tile = tile.clone();
move |event: &DragMoveEvent<DragResizing>, window, cx| {
if event.drag(cx).0 != node {
return;
}
tile.resize_to(event.event.position, window, cx);
}
})
}
/// The trailing controls of a tile's title bar.
///
/// A tile has no tab bar to hang a toolbar off, so this is where its zoom,
/// close and ellipsis menu live. The entries use click handlers rather
/// than the [`ToggleZoom`](crate::ToggleZoom) and
/// [`ClosePanel`](crate::ClosePanel) actions: those are dispatched to a
/// focused tab group, and a tile is not one.
fn render_tile_controls(
&self,
tile: &TileContext,
window: &mut Window,
cx: &mut App,
) -> impl IntoElement {
let handle = PanelHandle::of(tile.panel());
let control = handle.and_then(|handle| handle.zoom_control(cx));
let zoomed = tile.is_zoomed();
let toolbar_zoom =
tile.can_zoom() && control.is_some_and(|control| control.toolbar_visible());
let menu_zoom = tile.can_zoom() && control.is_some_and(|control| control.menu_visible());
let closable = tile.can_close();
let buttons = handle.and_then(|handle| handle.toolbar_buttons(window, cx));
let panel = handle.map(|handle| handle.panel());
h_flex()
.gap_1()
.flex_shrink_0()
.occlude()
.when_some(buttons, |this, buttons| {
this.children(
buttons
.into_iter()
.map(|button| button.xsmall().ghost().tab_stop(false)),
)
})
.when_some(
match (zoomed, toolbar_zoom) {
(true, _) => Some(("zoom-out", IconName::Minimize, t("Dock.Zoom Out"))),
(false, true) => Some(("zoom-in", IconName::Maximize, t("Dock.Zoom In"))),
(false, false) => None,
},
|this, (id, icon, tooltip)| {
this.child(
Button::new(id)
.icon(icon)
.xsmall()
.ghost()
.tab_stop(false)
.tooltip(tooltip)
.selected(zoomed)
.on_click({
let tile = tile.clone();
move |_, window, cx| tile.toggle_zoom(window, cx)
}),
)
},
)
.child(
Button::new("menu")
.icon(IconName::Ellipsis)
.xsmall()
.ghost()
.tab_stop(false)
.dropdown_menu({
let tile = tile.clone();
move |menu, window, cx| {
menu.when_some(panel.clone(), |menu, panel| {
panel.dropdown_menu(menu, window, cx)
})
.separator()
.item(
PopupMenuItem::new(match zoomed {
true => t("Dock.Zoom Out"),
false => t("Dock.Zoom In"),
})
.disabled(!menu_zoom && !zoomed)
.on_click({
let tile = tile.clone();
move |_, window, cx| tile.toggle_zoom(window, cx)
}),
)
.when(closable, |menu| {
menu.separator()
.item(PopupMenuItem::new(t("Dock.Close")).on_click({
let tile = tile.clone();
move |_, window, cx| tile.close(window, cx)
}))
})
}
})
.anchor(gpui::Anchor::TopRight),
)
}
}
impl TilesRenderer for SignedTilesSkin {
fn frame(&self, _: &mut Window, cx: &mut App) -> Stateful<Div> {
div()
.id("tiles")
.relative()
.size_full()
.bg(cx.theme().tokens.tiles)
.track_scroll(&self.scroll_handle)
.overflow_scroll()
}
fn tile_frame(&self, tile: &TileContext, _: &mut Window, cx: &mut App) -> Stateful<Div> {
v_flex()
.id(("tile", tile.panel_id().as_u64()))
.occlude()
.overflow_hidden()
.bg(cx.theme().tokens.background)
.border_1()
.border_color(cx.theme().border)
.rounded(cx.theme().tile_radius)
// Room for the title bar, which is positioned over the padding so
// the panel below it is never covered. Base draws the panel view
// as a plain child, so this is the only way to keep the two from
// overlapping.
.pt(DRAG_BAR_HEIGHT)
// Base installs the stored bounds on an ordinary tile and nothing
// at all on a zoomed one — how a zoomed tile fills the dock is
// this skin's decision.
.when(tile.is_zoomed(), |this| this.size_full())
.on_mouse_down(MouseButton::Left, {
let tile = tile.clone();
move |_, window, cx| tile.bring_to_front(window, cx)
})
// A gesture can end with the pointer anywhere, so both halves are
// needed; each is a no-op unless this tile is the one moving.
.on_mouse_up(MouseButton::Left, {
let tile = tile.clone();
move |_, window, cx| {
tile.end_move(window, cx);
tile.end_resize(window, cx);
}
})
.on_mouse_up_out(MouseButton::Left, {
let tile = tile.clone();
move |_, window, cx| {
tile.end_move(window, cx);
tile.end_resize(window, cx);
}
})
}
fn render_drag_bar(&self, tile: &TileContext, window: &mut Window, cx: &mut App) -> AnyElement {
let node = tile.node();
let handle = PanelHandle::of(tile.panel());
let title_style = handle.and_then(|handle| handle.title_style(cx));
h_flex()
.id("drag-bar")
.absolute()
.top_0()
.left_0()
.w_full()
.h(DRAG_BAR_HEIGHT)
.items_center()
.gap_1()
.pl_3()
.pr_2()
.when_some(title_style, |this, style| {
this.bg(style.background).text_color(style.foreground)
})
.child(
div()
.flex_1()
.min_w_16()
.overflow_hidden()
.text_ellipsis()
.whitespace_nowrap()
.child(panel_title(tile.panel(), window, cx)),
)
.children(handle.and_then(|handle| handle.title_suffix(window, cx)))
.child(self.render_tile_controls(tile, window, cx))
// A zoomed tile is not at its stored bounds, so there is nothing
// for a move to mean; base refuses the gesture too.
.when(!tile.is_zoomed(), |this| {
this.cursor_grab()
.on_mouse_down(MouseButton::Left, {
let tile = tile.clone();
move |event: &MouseDownEvent, window, cx| {
tile.begin_move(event.position, window, cx);
}
})
.on_drag(DragMoving(node), |drag, _, _, cx| {
cx.stop_propagation();
cx.new(|_| drag.clone())
})
.on_drag_move({
let tile = tile.clone();
move |event: &DragMoveEvent<DragMoving>, window, cx| {
if event.drag(cx).0 != node {
return;
}
tile.move_to(event.event.position, window, cx);
}
})
})
.into_any_element()
}
fn render_resize_handles(
&self,
tile: &TileContext,
_: &mut Window,
cx: &mut App,
) -> AnyElement {
let bounds = tile.bounds();
// A passive full-tile box so each handle is positioned against the
// tile rather than against whatever the flow put it next to. It
// registers no interaction of its own, so it does not shadow the panel
// underneath.
div()
.absolute()
.top_0()
.left_0()
.size_full()
.child(
self.resize_handle(tile, "left-resize-handle", ResizeSide::Left, |this| {
this.cursor_ew_resize()
.top_0()
.left(HANDLE_OFFSET)
.w(HANDLE_SIZE)
.h(bounds.size.height)
}),
)
.child(
self.resize_handle(tile, "right-resize-handle", ResizeSide::Right, |this| {
this.cursor_ew_resize()
.top_0()
.right(HANDLE_OFFSET)
.w(HANDLE_SIZE)
.h(bounds.size.height)
}),
)
.child(
self.resize_handle(tile, "top-resize-handle", ResizeSide::Top, |this| {
this.cursor_ns_resize()
.left_0()
.top(HANDLE_OFFSET)
.w(bounds.size.width)
.h(HANDLE_SIZE)
}),
)
.child(
self.resize_handle(tile, "bottom-resize-handle", ResizeSide::Bottom, |this| {
this.cursor_ns_resize()
.left_0()
.bottom(HANDLE_OFFSET)
.w(bounds.size.width)
.h(HANDLE_SIZE)
}),
)
.child(
Icon::new(IconName::ResizeCorner)
.size_3()
.absolute()
.right(px(1.))
.bottom(px(1.))
.text_color(cx.theme().muted_foreground.opacity(0.5)),
)
.child(self.resize_handle(
tile,
"corner-resize-handle",
ResizeSide::BottomRight,
|this| {
this.cursor_nwse_resize()
.right(HANDLE_OFFSET)
.bottom(HANDLE_OFFSET)
.size_3()
},
))
.into_any_element()
}
/// The panel of a tile gets `size_full` here; base draws the panel as a
/// plain child, so without it a panel that does not size itself has no
/// size.
fn panel_frame(&self, tile: &TileContext, _: &mut Window, _: &mut App) -> Stateful<Div> {
h_flex()
.id(("tile-panel", tile.panel_id().as_u64()))
.overflow_hidden()
.size_full()
}
/// The canvas scrollbar.
///
/// It has to be an overlay rather than one of the frame's own children:
/// the frame is the scroll container and base appends the tiles after
/// whatever the frame carries, so a scrollbar placed there would paint and
/// hit-test underneath every tile.
fn render_overlay(
&self,
content: Size<Pixels>,
_: &mut Window,
_: &mut App,
) -> Option<AnyElement> {
Some(
Scrollbar::new(&self.scroll_handle)
.scroll_size(content)
.when_some(self.shared.tiles_scrollbar_mode(), |this, mode| {
this.mode(mode)
})
.into_any_element(),
)
}
fn grid_size(&self, cx: &App) -> Pixels {
cx.theme().tile_grid_size
}
}
+25 -5
View File
@@ -91,17 +91,37 @@ impl LruImageCache {
}
}
/// Drop a cache entry from the sprite atlas and remove its resource from the
/// asset system, so both the decoded image and the raw fetched bytes are
/// freed. `window` restricts the atlas removal to the current window; `None`
/// removes it from all windows.
/// Drop a cache entry's decoded data and remove its resource from the asset
/// system, so both the decoded image and the raw fetched bytes are freed.
///
/// The atlas texture is freed **on the next frame, before it paints**, never
/// in the middle of one: the release that empties the cache can run at the
/// end of a frame's draw — after the scene was built, before it is presented
/// — and eviction runs while a frame is painting (`load` is called from
/// paint). The next frame also has to repaint every view instead of replaying
/// their recorded paint commands: `cached()` views reuse recorded commands
/// across frames, and those commands reference the atlas tiles being freed,
/// so a replay would hand the renderer a scene full of freed texture ids.
/// `window.refresh()` disables that reuse for exactly one frame.
///
/// `window` restricts the atlas removal to the current window; `None` removes
/// it from all windows (the cache entity is being released at shutdown, when
/// no scene is in flight).
fn unload(
(mut item, resource): (ImageCacheItem, Resource),
window: Option<&mut Window>,
cx: &mut App,
) {
if let Some(Ok(image)) = item.get() {
cx.drop_image(image, window);
match window {
Some(window) => {
window.on_next_frame(move |window, cx| {
window.refresh();
cx.drop_image(image, Some(window));
});
}
None => cx.drop_image(image, None),
}
}
ImageSource::Resource(resource).remove_asset(cx);
}
@@ -1,7 +1,7 @@
use std::path::PathBuf;
use std::rc::Rc;
use dock::{Panel, PanelEvent};
use dock::{BasePanel, Panel, PanelEvent};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
@@ -455,11 +455,13 @@ impl CommitDiffView {
}
}
impl Panel for CommitDiffView {
impl BasePanel for CommitDiffView {
fn panel_name(&self) -> &'static str {
"commit_diff"
}
}
impl Panel for CommitDiffView {
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().text_sm().child(SharedString::from(format!(
"{}/{}",
@@ -1,4 +1,4 @@
use dock::{Panel, PanelEvent};
use dock::{BasePanel, Panel, PanelEvent};
use gpui::prelude::*;
use gpui::{
App, Context, Entity, EventEmitter, FocusHandle, Focusable, Render, SharedString, Window, div,
@@ -131,11 +131,13 @@ impl IssueDetailView {
}
}
impl Panel for IssueDetailView {
impl BasePanel for IssueDetailView {
fn panel_name(&self) -> &'static str {
"issue_detail"
}
}
impl Panel for IssueDetailView {
fn title(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let short_id = self
.store
@@ -3,10 +3,9 @@
//! the header's All/Open/Closed filter.
use std::rc::Rc;
use std::sync::Arc;
use assets::CustomIconName;
use dock::{DockArea, DockPlacement, Panel, PanelEvent};
use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
@@ -123,7 +122,7 @@ impl IssuesView {
let panel = cx.new(|cx| IssueDetailView::new(self.store.clone(), issue_id, window, cx));
dock_area.update(cx, |dock_area, cx| {
dock_area.add_panel(Arc::new(panel), DockPlacement::Bottom, window, cx);
dock_area.add_panel_view(panel_handle(panel), DockPlacement::Bottom, None, window, cx);
});
}
@@ -417,11 +416,13 @@ fn open_new_issue_dialog(store: Entity<RepoStore>, window: &mut Window, cx: &mut
});
}
impl Panel for IssuesView {
impl BasePanel for IssuesView {
fn panel_name(&self) -> &'static str {
"issues"
}
}
impl Panel for IssuesView {
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().child(SharedString::from(format!("{}/issues", self.repo_name)))
}
@@ -1,11 +1,10 @@
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Component, Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use anyhow::Error;
use assets::CustomIconName;
use dock::{DockArea, DockPlacement, Panel, PanelEvent};
use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
use gix::Repository;
use gpui::prelude::*;
use gpui::{
@@ -653,7 +652,7 @@ impl RepoDetailView {
cx.new(|cx| CommitDiffView::new(worktree, repo_name, commit_id.into(), window, cx));
dock_area.update(cx, |dock_area, cx| {
dock_area.add_panel(Arc::new(panel), DockPlacement::Center, window, cx);
dock_area.add_panel_view(panel_handle(panel), DockPlacement::Center, None, window, cx);
});
}
@@ -674,7 +673,7 @@ impl RepoDetailView {
});
dock_area.update(cx, |dock_area, cx| {
dock_area.add_panel(Arc::new(panel), DockPlacement::Center, window, cx);
dock_area.add_panel_view(panel_handle(panel), DockPlacement::Center, None, window, cx);
});
}
@@ -695,7 +694,7 @@ impl RepoDetailView {
});
dock_area.update(cx, |dock_area, cx| {
dock_area.add_panel(Arc::new(panel), DockPlacement::Center, window, cx);
dock_area.add_panel_view(panel_handle(panel), DockPlacement::Center, None, window, cx);
});
}
@@ -1203,11 +1202,13 @@ impl RepoDetailView {
}
}
impl Panel for RepoDetailView {
impl BasePanel for RepoDetailView {
fn panel_name(&self) -> &'static str {
"repo_detail"
}
}
impl Panel for RepoDetailView {
fn title(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.display_name(cx)
}
@@ -1,7 +1,7 @@
use std::path::PathBuf;
use std::rc::Rc;
use dock::{Panel, PanelEvent};
use dock::{BasePanel, Panel, PanelEvent};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
@@ -819,11 +819,13 @@ fn commit_meta(commit: &FileCommit) -> String {
}
}
impl Panel for PullRequestDetailView {
impl BasePanel for PullRequestDetailView {
fn panel_name(&self) -> &'static str {
"pull-request-detail"
}
}
impl Panel for PullRequestDetailView {
fn title(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let subject = self
.store
@@ -1,8 +1,7 @@
use std::rc::Rc;
use std::sync::Arc;
use assets::CustomIconName;
use dock::{DockArea, DockPlacement, Panel, PanelEvent};
use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
@@ -126,7 +125,7 @@ impl PullRequestsView {
let panel = cx.new(|cx| PullRequestDetailView::new(self.store.clone(), pr_id, window, cx));
dock_area.update(cx, |dock_area, cx| {
dock_area.add_panel(Arc::new(panel), DockPlacement::Bottom, window, cx);
dock_area.add_panel_view(panel_handle(panel), DockPlacement::Bottom, None, window, cx);
});
}
@@ -504,11 +503,13 @@ fn open_new_pull_request_dialog(store: Entity<RepoStore>, window: &mut Window, c
});
}
impl Panel for PullRequestsView {
impl BasePanel for PullRequestsView {
fn panel_name(&self) -> &'static str {
"pull-requests"
}
}
impl Panel for PullRequestsView {
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().child(SharedString::from(format!(
"{}/pull-requests",
+11 -4
View File
@@ -1,13 +1,12 @@
use std::rc::Rc;
use std::sync::Arc;
use dock::{BasePanel, DockArea, DockPlacement, Panel, PanelEvent, panel_handle};
use gpui::prelude::*;
use gpui::{
AnyElement, App, Context, Entity, EventEmitter, FocusHandle, Focusable, Pixels, Render,
SharedString, Size, Subscription, WeakEntity, Window, div, px, size,
};
use gpui_component::avatar::Avatar;
use dock::{DockArea, DockPlacement, Panel, PanelEvent};
use gpui_component::scroll::Scrollbar;
use gpui_component::{
ActiveTheme, Sizable, StyledExt, VirtualListScrollHandle, h_flex, v_flex, v_virtual_list,
@@ -68,7 +67,13 @@ impl RepoListView {
if let Some(dock_area) = dock_area.upgrade() {
dock_area.update(cx, |dock_area, cx| {
dock_area.add_panel(Arc::new(detail), DockPlacement::Center, window, cx);
dock_area.add_panel_view(
panel_handle(detail),
DockPlacement::Center,
None,
window,
cx,
);
});
}
}
@@ -166,11 +171,13 @@ impl RepoListView {
}
}
impl Panel for RepoListView {
impl BasePanel for RepoListView {
fn panel_name(&self) -> &'static str {
"repo_list"
}
}
impl Panel for RepoListView {
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().text_sm().child(SharedString::from("Explore"))
}
+12 -9
View File
@@ -1,7 +1,8 @@
use std::sync::Arc;
use assets::CustomIconName;
use dock::{DockArea, DockPlacement, Panel, PanelEvent, TAB_BAR_HEIGHT, title_bar_drag_handlers};
use dock::{
BasePanel, DockArea, DockPlacement, Panel, PanelEvent, TAB_BAR_HEIGHT, panel_handle,
title_bar_drag_handlers,
};
use gpui::prelude::*;
use gpui::{
App, ClickEvent, Context, ElementId, EventEmitter, FocusHandle, Focusable, Render,
@@ -74,7 +75,7 @@ impl SidebarPanel {
self.explore = Some(panel.downgrade());
let _ = self.dock_area.update(cx, |dock_area, cx| {
dock_area.add_panel(Arc::new(panel), DockPlacement::Center, window, cx);
dock_area.add_panel_view(panel_handle(panel), DockPlacement::Center, None, window, cx);
});
}
@@ -138,20 +139,22 @@ impl SidebarPanel {
}
}
impl Panel for SidebarPanel {
impl BasePanel for SidebarPanel {
fn panel_name(&self) -> &'static str {
"sidebar"
}
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
}
fn closable(&self, _cx: &App) -> bool {
false
}
}
impl Panel for SidebarPanel {
fn title(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
}
}
impl EventEmitter<PanelEvent> for SidebarPanel {}
impl Focusable for SidebarPanel {
+9 -8
View File
@@ -1,6 +1,4 @@
use std::sync::Arc;
use dock::{DockArea, DockItem};
use dock::{DockArea, DockLayout, DockPlacement, SignedDockSkin, panel_handle};
use gpui::prelude::*;
use gpui::{Context, Entity, Render, Subscription, Window, div, px};
use gpui_component::{Root, StyledExt, Theme};
@@ -19,20 +17,23 @@ pub struct Workspace {
impl Workspace {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let dock = cx.new(|cx| DockArea::new("dock", Some(1), window, cx));
let dock = cx.new(|cx| {
let skin = SignedDockSkin::new(cx);
DockArea::new("dock", Some(1), window, cx).with_renderer(skin)
});
let weak_dock = dock.downgrade();
let sidebar = cx.new(|cx| SidebarPanel::new(weak_dock.clone(), cx));
let weak_sidebar = sidebar.downgrade();
dock.update(cx, |dock_area, cx| {
dock_area.set_left_dock(
DockItem::panel(Arc::new(sidebar)),
Some(px(240.)),
true,
dock_area.set_dock(
DockPlacement::Left,
DockLayout::tabs().panel_view(panel_handle(sidebar), cx),
window,
cx,
);
dock_area.set_dock_size(DockPlacement::Left, px(240.), window, cx);
});
let backend = Backend::global(cx);