use duplicate::duplicate;
use egui::{
Context, CornerRadius, CursorIcon, EventFilter, Key, Pos2, Rect, Sense, StrokeKind, Ui, Vec2,
WidgetInfo,
accesskit::{Action, ActionData, Orientation, Role},
};
use paste::paste;
use super::{drag_and_drop::TreeComponent, state::State, tab_removal::TabRemoval};
use crate::NodePath;
use crate::dock_area::tab_removal::ForcedRemoval;
use crate::tab_viewer::{DropVerdict, OnCloseResponse};
use crate::{
AllowedSplits, DockArea, Node, NodeIndex, OverlayType, Style, SurfaceIndex, TabDestination,
TabViewer,
utils::{expand_to_pixel, fade_dock_style, map_to_pixel},
};
mod leaf;
mod main_surface;
mod window_surface;
const SEPARATOR_KEY_STEP: f32 = 16.0;
const SEPARATOR_LARGE_KEY_STEP: f32 = 64.0;
impl<Tab> DockArea<'_, Tab> {
pub fn show_inside(mut self, ui: &mut Ui, tab_viewer: &mut impl TabViewer<Tab = Tab>) {
self.style
.get_or_insert(Style::from_egui(ui.style().as_ref()));
self.window_bounds.get_or_insert(ui.ctx().content_rect());
let mut state = State::load(ui.ctx(), self.id);
state.dragged = None;
if !ui.input(|i| i.pointer.any_released()) {
state.last_hover_pos = ui.input(|i| i.pointer.hover_pos());
}
let (drag_data, hover_data) = ui.memory_mut(|mem| {
(
mem.data.remove_temp(self.id.with("drag_data")).flatten(),
mem.data.remove_temp(self.id.with("hover_data")).flatten(),
)
});
if let (Some(source), Some(hover)) = (drag_data, hover_data) {
let style = self.style.as_ref().unwrap();
state.set_drag_and_drop(source, hover, ui.ctx(), style);
let tab_dst = self.show_drag_drop_overlay(ui, &mut state, tab_viewer);
if ui.input(|i| i.pointer.primary_released())
&& let Some(destination) = tab_dst
{
let source = {
match state.dnd.as_ref().unwrap().drag.src {
TreeComponent::Tab(src) => src,
_ => todo!(
"collections of tabs, like nodes and surfaces can't be docked (yet)"
),
}
};
let src_tab_count = self.dock_state[source.node_path()].tabs_count();
self.dock_state.move_tab(source, destination);
if self.hidable_tab_bars
&& let Ok(leaf) = self.dock_state.leaf_mut(source.node_path())
&& leaf.tabs.len() < src_tab_count
&& leaf.tab_bar_hidden
{
leaf.tab_bar_hidden = false;
}
}
}
if ui.input(|i| i.pointer.primary_released()) {
state.reset_drag();
}
let style = self.style.as_ref().unwrap();
let fade_surface =
self.hovered_window_surface(&mut state, style.overlay.feel.fade_hold_time, ui.ctx());
let fade_style = {
fade_surface.is_some().then(|| {
let mut fade_style = style.clone();
fade_dock_style(&mut fade_style, style.overlay.surface_fade_opacity);
(fade_style, style.overlay.surface_fade_opacity)
})
};
for &surface_index in self.dock_state.valid_surface_indices().iter() {
self.show_surface_inside(
surface_index,
ui,
tab_viewer,
&mut state,
fade_style.as_ref().map(|(style, factor)| {
(style, *factor, fade_surface.unwrap_or(SurfaceIndex::main()))
}),
);
}
for removal in self.to_remove.drain(..).rev() {
match removal {
TabRemoval::Tab(path, ForcedRemoval(is_forced)) => {
if is_forced {
self.dock_state.remove_tab(path);
} else {
let leaf = &mut self.dock_state.leaf_mut(path.node_path()).unwrap();
match tab_viewer.on_close(&mut leaf.tabs[path.tab.0]) {
OnCloseResponse::Close => {
self.dock_state.remove_tab(path);
}
OnCloseResponse::Focus => {
leaf.active = path.tab;
self.new_focused = Some(path.node_path());
}
OnCloseResponse::Ignore => {
}
}
}
}
TabRemoval::Node(path) => {
let mut all_tabs_are_closable = true;
for tab in self.dock_state[path].iter_tabs_mut() {
if !(tab_viewer.is_closeable(tab)
&& matches!(tab_viewer.on_close(tab), OnCloseResponse::Close))
{
all_tabs_are_closable = false;
}
}
if all_tabs_are_closable {
self.dock_state.remove_leaf(path);
}
}
TabRemoval::Window(surface) => {
let mut all_tabs_are_closable = true;
for node in self.dock_state[surface].iter_mut() {
for tab in node.iter_tabs_mut() {
if !(tab_viewer.is_closeable(tab)
&& matches!(tab_viewer.on_close(tab), OnCloseResponse::Close))
{
all_tabs_are_closable = false;
}
}
}
if all_tabs_are_closable {
self.dock_state.remove_surface(surface);
}
}
}
}
for path in self.to_detach.drain(..).rev() {
let mouse_pos = state.last_hover_pos;
self.dock_state
.eject_tab(path, mouse_pos.unwrap_or(Pos2::ZERO));
}
if let Some(focused) = self.new_focused {
self.dock_state.set_focused_node_and_surface(focused);
}
state.store(ui.ctx(), self.id);
}
#[inline(always)]
fn hovered_window_surface(
&self,
state: &mut State,
hold_time: f32,
ctx: &Context,
) -> Option<SurfaceIndex> {
if let Some(dnd_state) = &state.dnd
&& dnd_state.is_locked(self.style.as_ref().unwrap(), ctx)
{
state.window_fade =
Some((ctx.input(|i| i.time), dnd_state.hover.dst.surface_address()));
}
state.window_fade.and_then(|(time, surface)| {
ctx.request_repaint();
(hold_time > (ctx.input(|i| i.time) - time) as f32).then_some(surface)
})
}
fn show_drag_drop_overlay(
&mut self,
ui: &Ui,
state: &mut State,
tab_viewer: &impl TabViewer<Tab = Tab>,
) -> Option<TabDestination> {
let drag_state = state.dnd.as_mut().unwrap();
let style = self.style.as_ref().unwrap();
let deserted_node = {
match (
drag_state.drag.src.node_address(),
drag_state.hover.dst.node_address(),
) {
((src_surf, Some(src_node)), (dst_surf, Some(dst_node))) => {
src_surf == dst_surf
&& src_node == dst_node
&& self.dock_state[src_surf][src_node].tabs_count() == 1
}
_ => false,
}
};
let restricted_splits = if drag_state.hover.dst.is_surface() || deserted_node {
AllowedSplits::None
} else {
AllowedSplits::All
};
let allowed_splits = self.allowed_splits & restricted_splits;
let allowed_in_window = match drag_state.drag.src {
TreeComponent::Tab(path) => {
let Node::Leaf(leaf) = &mut self.dock_state[path.node_path()] else {
unreachable!("tab drags can only come from leaf nodes")
};
tab_viewer.allowed_in_windows(&mut leaf.tabs[path.tab.0])
}
_ => todo!("collections of tabs, like nodes or surfaces, can't be dragged! (yet)"),
};
if let Some(pointer) = state.last_hover_pos {
drag_state.pointer = pointer;
}
let window_bounds = self.window_bounds.unwrap();
let destination = match (style.overlay.overlay_type, drag_state.is_on_title_bar()) {
(OverlayType::HighlightedAreas, _) | (_, true) => drag_state.resolve_traditional(
ui,
style,
allowed_splits,
allowed_in_window,
window_bounds,
),
(OverlayType::Widgets, false) => drag_state.resolve_icon_based(
ui,
style,
allowed_splits,
allowed_in_window,
window_bounds,
),
}?;
let TreeComponent::Tab(path) = drag_state.drag.src else {
unreachable!("only tabs can be dragged")
};
let tab = &self.dock_state[path.node_path()]
.tabs()
.expect("tab drags can only come from leaf nodes")[path.tab.0];
match tab_viewer.drop_allowed(tab, &destination) {
DropVerdict::Allow => Some(destination),
DropVerdict::Refuse(reason) => {
drag_state.draw_refusal(ui, style, &destination, reason, window_bounds);
None
}
}
}
fn show_surface_inside(
&mut self,
surf_index: SurfaceIndex,
ui: &mut Ui,
tab_viewer: &mut impl TabViewer<Tab = Tab>,
state: &mut State,
fade_style: Option<(&Style, f32, SurfaceIndex)>,
) {
if surf_index.is_main() {
self.show_root_surface_inside(ui, tab_viewer, state);
} else {
self.show_window_surface(ui, surf_index, tab_viewer, state, fade_style);
}
}
fn render_nodes(
&mut self,
ui: &mut Ui,
tab_viewer: &mut impl TabViewer<Tab = Tab>,
state: &mut State,
surf_index: SurfaceIndex,
fade_style: Option<(&Style, f32)>,
) {
let max_rect = self.allocate_area_for_root_node(ui, surf_index);
for node_index in self.dock_state[surf_index].breadth_first_index_iter() {
let path = NodePath {
surface: surf_index,
node: node_index,
};
if self.dock_state[path].is_parent() {
self.compute_rect_sizes(ui, path, max_rect);
}
}
for node_index in self.dock_state[surf_index].breadth_first_index_iter() {
let path = NodePath {
surface: surf_index,
node: node_index,
};
if self.dock_state[path].is_leaf() {
self.show_leaf(ui, state, path, tab_viewer, fade_style);
}
}
let fade_style = fade_style.map(|(style, _)| style);
for node_index in self.dock_state[surf_index].breadth_first_index_iter() {
let path = NodePath {
surface: surf_index,
node: node_index,
};
if self.dock_state[surf_index][node_index].is_parent() {
self.show_separator(ui, path, fade_style);
}
}
}
fn allocate_area_for_root_node(&mut self, ui: &mut Ui, surface: SurfaceIndex) -> Rect {
let style = self.style.as_ref().unwrap();
let mut rect = ui.available_rect_before_wrap();
if let Some(margin) = style.dock_area_padding {
rect.min += margin.left_top();
rect.max -= margin.right_bottom();
}
ui.painter().rect_stroke(
rect,
style.main_surface_border_rounding,
style.main_surface_border_stroke,
StrokeKind::Inside,
);
if surface == SurfaceIndex::main() {
rect = rect.expand(-style.main_surface_border_stroke.width / 2.0);
}
ui.allocate_rect(rect, Sense::hover());
if self.dock_state[surface].is_empty() {
return rect;
}
self.dock_state[surface][NodeIndex::root()].set_rect(rect);
rect
}
fn compute_rect_sizes(&mut self, ui: &Ui, path: NodePath, max_rect: Rect) {
assert!(self.dock_state[path].is_parent());
let style = self.style.as_ref().unwrap();
let pixels_per_point = ui.ctx().pixels_per_point();
let left_collapsed_count = self.dock_state[path.left_node()].collapsed_leaf_count();
let right_collapsed_count = self.dock_state[path.right_node()].collapsed_leaf_count();
let left_collapsed = self.dock_state[path.left_node()].is_collapsed();
let right_collapsed = self.dock_state[path.right_node()].is_collapsed();
if (left_collapsed || right_collapsed)
&& let Node::Vertical(split) = &mut self.dock_state[path.surface][path.node]
{
let rect = split.rect();
debug_assert!(!rect.any_nan() && rect.is_finite());
let rect = expand_to_pixel(rect, pixels_per_point);
if left_collapsed {
let border_y = rect.min.y + (left_collapsed_count as f32) * style.tab_bar.height;
let left_separator_border = map_to_pixel(
border_y - style.separator.width * 0.5,
pixels_per_point,
f32::round,
);
let right_separator_border = map_to_pixel(
border_y + style.separator.width * 0.5,
pixels_per_point,
f32::round,
);
let left = rect
.intersect(Rect::everything_above(left_separator_border))
.intersect(max_rect);
let right = rect
.intersect(Rect::everything_below(right_separator_border))
.intersect(max_rect);
self.dock_state[path.left_node()].set_rect(left);
self.dock_state[path.right_node()].set_rect(right);
} else {
let border_y = rect.max.y - (right_collapsed_count as f32) * style.tab_bar.height;
let left_separator_border = map_to_pixel(
border_y - style.separator.width * 0.5,
pixels_per_point,
f32::round,
);
let right_separator_border = map_to_pixel(
border_y + style.separator.width * 0.5,
pixels_per_point,
f32::round,
);
let left = rect
.intersect(Rect::everything_above(left_separator_border))
.intersect(max_rect);
let right = rect
.intersect(Rect::everything_below(right_separator_border))
.intersect(max_rect);
self.dock_state[path.left_node()].set_rect(left);
self.dock_state[path.right_node()].set_rect(right);
}
return;
}
duplicate! {
[
orientation dim_point dim_size left_of right_of;
[Horizontal] [x] [width] [left_of] [right_of];
[Vertical] [y] [height] [above] [below];
]
if let Node::orientation(split) = &mut self.dock_state[path.surface][path.node] {
let rect = split.rect;
debug_assert!(!rect.any_nan() && rect.is_finite());
let rect = expand_to_pixel(rect, pixels_per_point);
let dim_size = rect.dim_size();
let midpoint = if dim_size > 0.0 {
rect.min.dim_point + dim_size * split.fraction
} else {
rect.min.dim_point
};
let left_separator_border = map_to_pixel(
midpoint - style.separator.width * 0.5,
pixels_per_point,
f32::round
);
let right_separator_border = map_to_pixel(
midpoint + style.separator.width * 0.5,
pixels_per_point,
f32::round
);
paste! {
let left = rect.intersect(Rect::[<everything_ left_of>](left_separator_border)).intersect(max_rect);
let right = rect.intersect(Rect::[<everything_ right_of>](right_separator_border)).intersect(max_rect);
}
self.dock_state[path.left_node()].set_rect(left);
self.dock_state[path.right_node()].set_rect(right);
}
}
}
fn show_separator(&mut self, ui: &mut Ui, path: NodePath, fade_style: Option<&Style>) {
assert!(self.dock_state[path.surface][path.node].is_parent());
if (self.dock_state[path.left_node()].is_collapsed()
|| self.dock_state[path.right_node()].is_collapsed())
&& self.dock_state[path.surface][path.node].is_vertical()
{
return;
}
let style = fade_style.unwrap_or_else(|| self.style.as_ref().unwrap());
let pixels_per_point = ui.ctx().pixels_per_point();
duplicate! {
[
orientation dim_point dim_size separator_orientation back_key forward_key lock_horizontal lock_vertical;
[Horizontal] [x] [width] [Vertical] [ArrowLeft] [ArrowRight] [true] [false];
[Vertical] [y] [height] [Horizontal] [ArrowUp] [ArrowDown] [false] [true];
]
if let Node::orientation(split) = &mut self.dock_state[path.surface][path.node] {
let rect = split.rect;
let mut separator = rect;
let midpoint = rect.min.dim_point + rect.dim_size() * split.fraction;
separator.min.dim_point = midpoint - style.separator.width * 0.5;
separator.max.dim_point = midpoint + style.separator.width * 0.5;
let mut expand = Vec2::ZERO;
expand.dim_point += style.separator.extra_interact_width / 2.0;
let interact_rect = separator.expand2(expand);
let response = ui.allocate_rect(interact_rect, Sense::click_and_drag())
.on_hover_and_drag_cursor(paste!{ CursorIcon::[<Resize orientation>]});
if response.has_focus() {
ui.memory_mut(|m| m.set_focus_lock_filter(response.id, EventFilter {
horizontal_arrows: lock_horizontal,
vertical_arrows: lock_vertical,
tab: false,
escape: false
}));
}
let (arrow_key_offset, reset) = if response.has_focus() {
ui.input(|i| {
let step = if i.modifiers.shift {
SEPARATOR_LARGE_KEY_STEP
} else {
SEPARATOR_KEY_STEP
};
let offset = if i.key_pressed(Key::back_key) {
Some(-step)
} else if i.key_pressed(Key::forward_key) {
Some(step)
} else {
None
};
(offset, i.key_pressed(Key::Enter))
})
} else {
(None, false)
};
let midpoint = rect.min.dim_point + rect.dim_size() * split.fraction;
separator.min.dim_point = map_to_pixel(
midpoint - style.separator.width * 0.5,
pixels_per_point,
f32::round,
);
separator.max.dim_point = map_to_pixel(
midpoint + style.separator.width * 0.5,
pixels_per_point,
f32::round,
);
let color = if response.dragged() {
style.separator.color_dragged
} else if response.hovered() || response.has_focus() {
style.separator.color_hovered
} else {
style.separator.color_idle
};
ui.painter().rect_filled(separator, CornerRadius::ZERO, color);
let range = rect.max.dim_point - rect.min.dim_point;
let accesskit_step = if range > 0.0 { (SEPARATOR_KEY_STEP / range).min(1.0) } else { 0.0 };
let (accesskit_steps, accesskit_value) = ui.input(|i| {
let steps = i.num_accesskit_action_requests(response.id, Action::Increment) as f32
- i.num_accesskit_action_requests(response.id, Action::Decrement) as f32;
let value = i
.accesskit_action_requests(response.id, Action::SetValue)
.filter_map(|request| match request.data {
Some(ActionData::NumericValue(value)) => Some(value as f32),
_ => None,
})
.last();
(steps, value)
});
let (min, max) = if range > 0.0 {
let min = (style.separator.extra / range).min(1.0);
let max = 1.0 - min;
(min.min(max), max.max(min))
} else {
(split.fraction, split.fraction)
};
if range > 0.0 {
let delta = arrow_key_offset.unwrap_or(response.drag_delta().dim_point);
let fraction = accesskit_value.unwrap_or(split.fraction);
split.fraction =
(fraction + delta / range + accesskit_steps * accesskit_step).clamp(min, max);
}
if response.double_clicked() || reset {
split.fraction = 0.5;
}
let fraction = split.fraction;
let enabled = ui.is_enabled();
response.widget_info(|| {
let mut info = WidgetInfo::labeled(Role::Splitter, enabled, &self.labels.separator);
info.value = Some(f64::from(fraction));
info
});
ui.ctx().accesskit_node_builder(response.id, |node| {
node.set_orientation(Orientation::separator_orientation);
node.set_min_numeric_value(f64::from(min));
node.set_max_numeric_value(f64::from(max));
node.set_numeric_value_step(f64::from(accesskit_step));
if range > 0.0 {
node.add_action(Action::SetValue);
if fraction < max {
node.add_action(Action::Increment);
}
if min < fraction {
node.add_action(Action::Decrement);
}
}
});
}
}
}
}