use egui::{
Context, CursorIcon, Event, EventFilter, Key, Pos2, Rect, Sense, StrokeKind, Ui, Vec2,
WidgetInfo,
accesskit::{Action, ActionData, Orientation, Role},
pos2,
};
use super::{
drag_and_drop::{DragData, DragDropState, HoverData, TreeComponent, make_overlay_painter},
session::Outcome,
state::State,
tab_removal::TabRemoval,
};
use crate::NodePath;
use crate::dock_area::tab_removal::ForcedRemoval;
use crate::dock_space::{NoDrop, RestoreDrop, StripDrop, dock_name, remove_empty_docks};
use crate::dock_state::tree::node::shares;
use crate::layout::{Dir, ZoneName};
use crate::tab_viewer::{DockDrop, DropVerdict, OnCloseResponse};
use crate::{
AllowedSplits, DockArea, DockPainter, DockRules, LinearDir, Node, NodeIndex, OverlayType,
PartState, RestoreBandPaint, SeparatorAxis, SeparatorPaint, Style, SurfaceIndex,
TabDestination, TabPath, TabViewer,
utils::{expand_to_pixel, fade_dock_style, map_to_pixel},
};
use across::Across;
mod across;
mod float_out;
mod ghost;
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);
let pass = ui.ctx().cumulative_pass_nr();
let first_in_pass = state.pass != Some(pass);
state.pass = Some(pass);
if first_in_pass {
state.tab_bars.clear();
}
let dock_rect = ui.available_rect_before_wrap();
if let Some(space) = &mut self.space
&& let Some(dock) = space.dock
{
space.docks[dock].rect = Some(dock_rect);
space.docks[dock].viewport = Some(ui.ctx().viewport_id());
}
if let Some(space) = &mut self.space {
space.viewport = Some(ui.ctx().viewport_id());
}
if first_in_pass {
self.resolve_drag(ui, &mut state, tab_viewer, dock_rect);
}
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.surfaces_to_show() {
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 std::mem::take(&mut self.to_detach).into_iter().rev() {
let mouse_pos = state.last_hover_pos.unwrap_or(Pos2::ZERO);
if self.floats_on() {
let size = self.dock_state[path.node_path()]
.rect()
.map_or(Vec2::new(100., 150.), |rect| rect.size());
self.to_float.push((
TreeComponent::Tab(path),
Rect::from_min_size(mouse_pos, size),
None,
));
} else {
self.dock_state.eject_tab(path, mouse_pos);
}
}
for (path, destination) in std::mem::take(&mut self.to_move_group) {
match destination {
TabDestination::Window(rect) if self.floats_on() => {
self.to_float.push((TreeComponent::Node(path), rect, None));
}
destination => self.dock_state.move_node(path, destination),
}
}
for (source, rect, host) in std::mem::take(&mut self.to_float) {
self.float_out(ui.ctx(), source, rect, host, tab_viewer);
}
if let Some(focused) = self.new_focused {
self.dock_state.set_focused_node_and_surface(focused);
}
if let Some(space) = &mut self.space {
remove_empty_docks(self.dock_state, space.docks);
}
state.store(ui.ctx(), self.id);
}
fn resolve_drag(
&mut self,
ui: &Ui,
state: &mut State,
tab_viewer: &mut impl TabViewer<Tab = Tab>,
dock_rect: Rect,
) {
state.dragged = None;
state.tab_in_air = None;
state.dragged_node = None;
if self.drag_lost(ui, state) {
ui.memory_mut(|mem| {
mem.data
.remove_temp::<Option<DragData>>(self.id.with("drag_data"));
mem.data
.remove_temp::<Option<HoverData>>(self.id.with("hover_data"));
});
let viewport = ui.ctx().viewport_id();
if let Some(space) = self.space.as_mut()
&& space
.floating
.session
.as_ref()
.is_some_and(|session| session.source == viewport && session.released.is_none())
{
space.floating.session = None;
}
state.reset_drag();
self.forget_no_drop();
self.forget_verdicts();
ui.ctx().request_repaint();
return;
}
state.last_hover_pos = ui.input(|i| {
if i.pointer.any_released() {
i.pointer
.interact_pos()
.or(i.pointer.hover_pos())
.or(state.last_hover_pos)
} else {
i.pointer.hover_pos()
}
});
let (mut 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 drag_data
.as_ref()
.is_some_and(|drag: &DragData| !self.source_valid(&drag.src))
{
drag_data = None;
if let Some(space) = self.space.as_mut()
&& space
.floating
.session
.as_ref()
.is_some_and(|session| session.source == ui.ctx().viewport_id())
{
space.floating.session = None;
}
if let Some(id) = ui.ctx().dragged_id() {
state.drag_lost = Some(id);
ui.ctx().stop_dragging();
}
state.reset_drag();
state.tab_in_air = None;
self.forget_verdicts();
}
if state
.dnd
.as_ref()
.is_some_and(|dnd| !self.source_valid(&dnd.drag.src) || !self.hover_valid(&dnd.hover))
{
state.dnd = None;
state.window_fade = None;
}
let hover_data = hover_data.filter(|hover| self.hover_valid(hover));
let in_air = match &drag_data {
Some(DragData {
src: TreeComponent::Tab(path),
..
}) => Some(*path),
_ => None,
};
let (remote, take) = match self.across(ui, state, &mut drag_data, tab_viewer) {
Across::Here => (false, false),
Across::Remote { take } => (true, take),
Across::Covered => {
drag_data = None;
(false, false)
}
Across::Done => {
self.forget_no_drop();
return;
}
};
if drag_data
.as_ref()
.is_some_and(|drag| !self.source_valid(&drag.src))
{
drag_data = None;
state.reset_drag();
state.tab_in_air = None;
}
let hover_data = if drag_data.is_some() {
hover_data
} else {
None
};
let released = !remote && ui.input(|i| i.pointer.primary_released());
let ghost = match &drag_data {
Some(DragData {
src: TreeComponent::Node(path),
..
}) => Some((*path, None)),
Some(DragData {
src: TreeComponent::Tab(path),
..
}) => Some((path.node_path(), Some(path.tab))),
_ => None,
};
state.tab_in_air = if remote { None } else { in_air };
if !released
&& !take
&& let Some((path, tab)) = ghost
&& let Some(pointer) = state.last_hover_pos
{
self.paint_ghost(ui, path, tab, pointer, tab_viewer);
}
let restores = self
.space
.as_ref()
.filter(|space| !space.native)
.map(|space| space.no_drop.restores.clone())
.unwrap_or_default();
let bands = restore_bands(
&restores,
self.style.as_ref().unwrap().overlay.feel.restore_band,
);
let restore = drag_data
.as_ref()
.and_then(|_| self.hover_restore(state, &restores, &bands));
if drag_data.is_some() {
self.paint_restore_bands(ui, &restores, &bands, restore.as_ref().map(|r| r.2));
}
let strip = drag_data
.as_ref()
.filter(|_| restore.is_none())
.and_then(|_| self.hover_strip(state));
let preview = restore.as_ref().map(|(_, _, i)| restores[*i].restore.rect);
let drop_zone = match &restore {
Some((_, zone, i)) => Some((restores[*i].dock.clone(), zone.clone())),
None => strip
.as_ref()
.map(|(_, dock, zone)| (dock.clone(), zone.clone())),
};
let unfold = drop_zone.as_ref().map(|(_, zone)| zone.clone());
if let Some(space) = &mut self.space {
space.drop_zone = drop_zone;
}
let hover_data = restore
.map(|(hover, _, _)| hover)
.or_else(|| strip.map(|(hover, _, _)| hover))
.or(hover_data)
.or_else(|| (!remote).then(|| self.hover_outside(dock_rect, state, &drag_data))?);
let refused = preview.is_none()
&& hover_data
.as_ref()
.is_some_and(|hover| self.refuses_drop(ui.ctx(), state, hover));
let hover_data = if refused {
state.dnd = None;
None
} else {
hover_data
};
self.forget_no_drop();
let mut outcome = refused.then_some(Outcome::Refused);
if let (Some(source), Some(hover)) = (drag_data, hover_data) {
let style = self.style.as_ref().unwrap();
let tab_dst = if let Some(preview) = preview {
state.dnd = Some(DragDropState {
hover,
drag: source,
pointer: state.last_hover_pos.unwrap_or(Pos2::ZERO),
locked: None,
src_in_window: false,
dst_in_window: false,
});
self.show_restore_overlay(ui, state, tab_viewer, preview)
} else {
state.set_drag_and_drop(source, hover, ui.ctx(), style);
if let (Some(dnd), Some(pointer)) = (state.dnd.as_mut(), state.last_hover_pos) {
dnd.hover.retarget(pointer);
}
self.show_drag_drop_overlay(ui, state, tab_viewer)
};
if remote {
outcome = Some(tab_dst.map_or(Outcome::Refused, Outcome::Drop));
} else if released && let Some(destination) = tab_dst {
if let (Some(zone), Some(space)) = (unfold.clone(), &mut self.space) {
space.no_drop.unfolds.push(zone);
}
let source = state.dnd.as_ref().unwrap().drag.src.clone();
match destination {
TabDestination::Window(rect) if self.floats_on() => {
let host = self.release_host(rect.min);
self.to_float.push((source, rect, host));
}
destination => {
self.apply_move(source, destination, tab_viewer);
}
}
ui.ctx().request_repaint();
}
}
if remote {
self.report(
ui,
state,
outcome.unwrap_or(Outcome::Free),
unfold,
take,
tab_viewer,
);
}
if released {
state.reset_drag();
#[cfg(feature = "bus")]
if let Some(bus) = self.space.as_ref().and_then(|space| space.bus) {
bus.forget_verdicts();
}
}
}
fn drag_lost(&self, ui: &Ui, state: &mut State) -> bool {
let ctx = ui.ctx();
if let Some(id) = state.drag_lost {
if ctx.input(|i| i.pointer.any_down()) {
if ctx.dragged_id() == Some(id) {
ctx.stop_dragging();
}
return false;
}
state.drag_lost = None;
}
let Some(dragged) = ctx.dragged_id() else {
return false;
};
if state.drag_start.is_none() || state.remote {
return false;
}
let lost = ctx.input(|i| {
i.pointer.any_pressed()
|| i.events
.iter()
.any(|event| matches!(event, Event::WindowFocused(false)))
});
if lost {
state.drag_lost = Some(dragged);
ctx.stop_dragging();
}
lost
}
fn forget_no_drop(&mut self) {
if let Some(space) = &mut self.space
&& !space.native
{
let unfolds = std::mem::take(&mut space.no_drop.unfolds);
*space.no_drop = NoDrop {
unfolds,
..NoDrop::default()
};
}
}
fn surfaces_to_show(&self) -> Vec<SurfaceIndex> {
match &self.space {
None => self.dock_state.valid_surface_indices().to_vec(),
Some(space) => {
let dock = space.dock.map(|dock| space.docks[dock].surface);
let windows = self
.dock_state
.valid_surface_indices()
.into_iter()
.filter(|&surface| space.shows_windows && self.dock_state.is_window(surface));
dock.into_iter().chain(windows).collect()
}
}
}
fn dock_rules(&self, surface: SurfaceIndex) -> Option<DockRules> {
let space = self.space.as_ref()?;
space
.docks
.iter()
.find(|dock| dock.surface == surface)
.map(|dock| dock.rules)
}
fn refuses_drop(&self, ctx: &Context, state: &State, hover: &HoverData) -> bool {
let Some(space) = &self.space else {
return false;
};
let surface = hover.dst.surface_address();
if !hover.outside && self.dock_state.is_window(surface) {
return false;
}
if !hover.outside && self.dock_rules(surface).is_some_and(|r| !r.accept_drops) {
return true;
}
if space.native || (!hover.outside && self.is_float_dock(surface)) {
return false;
}
let Some(pointer) = state.last_hover_pos else {
return false;
};
if hover.outside && space.floating.release_host(space.docks, pointer).is_none() {
return true;
}
let widgets = space
.no_drop
.ids
.iter()
.filter_map(|&id| ctx.read_response(id).map(|r| r.rect));
space
.no_drop
.rects
.iter()
.copied()
.chain(widgets)
.any(|rect| rect.contains(pointer))
}
fn dock_name(&self, surface: SurfaceIndex) -> Option<&str> {
dock_name(self.space.as_ref()?.docks, surface)
}
#[cfg(feature = "bus")]
pub(super) fn drop_zone_of(&self, dock: Option<&str>) -> Option<String> {
let (dock, space) = (dock?, self.space.as_ref()?);
match &space.drop_zone {
Some((over, zone)) if over == dock => Some(zone.0.clone()),
_ => space
.docks
.iter()
.find(|d| d.name == dock)
.and_then(|d| d.zone.as_ref())
.map(|zone| zone.0.clone()),
}
}
pub(super) fn may_float(
&mut self,
path: TabPath,
tab_viewer: &impl TabViewer<Tab = Tab>,
) -> bool {
let dock_allows = self
.dock_rules(path.surface)
.is_none_or(|rules| rules.windows);
let Node::Leaf(leaf) = &mut self.dock_state[path.node_path()] else {
unreachable!("tab drags can only come from leaf nodes")
};
dock_allows && tab_viewer.allowed_in_windows(&mut leaf.tabs[path.tab.0])
}
pub(super) fn component_may_float(
&mut self,
src: &TreeComponent,
tab_viewer: &impl TabViewer<Tab = Tab>,
) -> bool {
match *src {
TreeComponent::Tab(path) => self.may_float(path, tab_viewer),
TreeComponent::Node(path) => self.node_may_float(path, tab_viewer),
TreeComponent::Surface(_) => false,
}
}
pub(super) fn may_join(
&mut self,
src: &TreeComponent,
surface: SurfaceIndex,
tab_viewer: &impl TabViewer<Tab = Tab>,
) -> bool {
!self.dock_state.is_window(surface) || self.component_may_float(src, tab_viewer)
}
pub(super) fn node_may_float(
&mut self,
path: NodePath,
tab_viewer: &impl TabViewer<Tab = Tab>,
) -> bool {
let count = self.dock_state[path].tabs_count();
(0..count).all(|i| self.may_float((path, crate::TabIndex(i)).into(), tab_viewer))
}
pub(super) fn covered_by_window(&self, ui: &Ui, pointer: Pos2) -> bool {
let Some(top) = ui.ctx().layer_id_at(pointer) else {
return false;
};
let over_a_float = self
.space
.as_ref()
.is_some_and(|space| !space.native && space.floating.layers.contains(&top));
top != ui.layer_id()
&& (over_a_float
|| self
.dock_state
.valid_surface_indices()
.iter()
.any(|&surface| {
self.dock_state.is_window(surface)
&& window_surface::window_layer_id(surface) == top
}))
}
fn hover_strip(&self, state: &State) -> Option<(HoverData, String, ZoneName)> {
let space = self.space.as_ref()?;
let pointer = state.last_hover_pos?;
let StripDrop {
rect: strip,
dock: name,
unfold,
} = space
.no_drop
.strips
.iter()
.find(|strip| strip.rect.contains(pointer))?;
let over_a_window = self
.dock_state
.valid_surface_indices()
.iter()
.filter_map(|&surface| self.dock_state.get_window_state(surface))
.any(|window| window.rect().contains(pointer));
if over_a_window {
return None;
}
let dst = self.dock_target(name)?;
Some((
HoverData {
rect: *strip,
dst,
tab: Some(*strip),
tab_bar: None,
outside: false,
},
name.clone(),
unfold.clone(),
))
}
fn dock_target(&self, name: &str) -> Option<TreeComponent> {
let space = self.space.as_ref()?;
let surface = space.docks.iter().find(|dock| dock.name == name)?.surface;
let tree = self.dock_state.get_surface(surface)?.node_tree()?;
let leaf = tree
.focused_leaf()
.filter(|&node| tree.iter().nth(node.0).is_some_and(Node::is_leaf))
.or_else(|| tree.iter().position(Node::is_leaf).map(NodeIndex));
Some(match leaf {
Some(node) => TreeComponent::Node(NodePath::new(surface, node)),
None => TreeComponent::Surface(surface),
})
}
fn hover_restore(
&self,
state: &State,
restores: &[RestoreDrop],
bands: &[Rect],
) -> Option<(HoverData, ZoneName, usize)> {
let pointer = state.last_hover_pos?;
let index = bands.iter().position(|band| band.contains(pointer))?;
let over_a_window = self
.dock_state
.valid_surface_indices()
.iter()
.filter_map(|&surface| self.dock_state.get_window_state(surface))
.any(|window| window.rect().contains(pointer));
if over_a_window {
return None;
}
let restore = &restores[index];
let dst = self.dock_target(&restore.dock)?;
let band = bands[index];
Some((
HoverData {
rect: band,
dst,
tab: Some(band),
tab_bar: None,
outside: false,
},
restore.zone.clone(),
index,
))
}
fn paint_restore_bands(
&self,
ui: &Ui,
restores: &[RestoreDrop],
bands: &[Rect],
hovered: Option<usize>,
) {
if bands.is_empty() {
return;
}
let style = self.style.as_ref().unwrap();
let painter = make_overlay_painter(ui);
for (i, (band, restore)) in bands.iter().zip(restores).enumerate() {
self.painter.0.restore_band(
&painter,
&RestoreBandPaint {
rect: *band,
zone: &restore.zone,
hovered: hovered == Some(i),
style,
},
);
}
}
fn show_restore_overlay(
&mut self,
ui: &Ui,
state: &mut State,
tab_viewer: &impl TabViewer<Tab = Tab>,
rect: Rect,
) -> Option<TabDestination> {
let drag_state = state.dnd.as_mut().unwrap();
let (src_surface, src_node) = drag_state.drag.src.node_address();
drag_state.src_in_window = self.dock_state.is_window(src_surface);
let destination = drag_state.hover.dst.as_tab_destination();
if (src_surface, src_node) == drag_state.hover.dst.node_address() {
return None;
}
let released = ui.input(|i| i.pointer.primary_released());
let refusal = self.drop_refusal(state, tab_viewer, &destination, released);
let allowed = refusal.is_none();
let style = self.style.as_ref().unwrap();
let painter: &dyn DockPainter = self.painter.0;
state.dnd.as_ref().unwrap().paint_preview_in(
ui,
style,
painter,
rect,
&destination,
false,
refusal,
);
allowed.then_some(destination)
}
fn hover_valid(&self, hover: &HoverData) -> bool {
hover.outside
|| match hover.dst {
TreeComponent::Tab(_) => self.source_valid(&hover.dst),
_ => self.destination_valid(&hover.dst.as_tab_destination()),
}
}
fn drop_refusal(
&self,
state: &State,
tab_viewer: &impl TabViewer<Tab = Tab>,
destination: &TabDestination,
fresh: bool,
) -> Option<Option<egui::WidgetText>> {
let drag_state = state.dnd.as_ref()?;
self.refusal_of(&drag_state.drag.src, tab_viewer, destination, fresh)
}
pub(super) fn refusal_of(
&self,
src: &TreeComponent,
tab_viewer: &impl TabViewer<Tab = Tab>,
destination: &TabDestination,
fresh: bool,
) -> Option<Option<egui::WidgetText>> {
if !self.source_valid(src) || !self.destination_valid(destination) {
return Some(None);
}
let (src, tabs, group) = match *src {
TreeComponent::Tab(path) => (path.node_path(), path.tab.0..path.tab.0 + 1, false),
TreeComponent::Node(path) => (path, 0..self.dock_state[path].tabs_count(), true),
TreeComponent::Surface(_) => unreachable!("surfaces can't be dragged (yet)"),
};
self.group_refusal_asked(src, tabs, group, destination, tab_viewer, fresh)
}
pub(super) fn group_refusal(
&self,
src: NodePath,
tabs: std::ops::Range<usize>,
destination: &TabDestination,
tab_viewer: &impl TabViewer<Tab = Tab>,
fresh: bool,
) -> Option<Option<egui::WidgetText>> {
let group = tabs.start == 0 && tabs.end == self.dock_state[src].tabs_count();
self.group_refusal_asked(src, tabs, group, destination, tab_viewer, fresh)
}
fn group_refusal_asked(
&self,
src: NodePath,
tabs: std::ops::Range<usize>,
group: bool,
destination: &TabDestination,
tab_viewer: &impl TabViewer<Tab = Tab>,
fresh: bool,
) -> Option<Option<egui::WidgetText>> {
let to = match *destination {
TabDestination::Node(path, _) => self.dock_name(path.surface),
TabDestination::EmptySurface(surface) => self.dock_name(surface),
TabDestination::Window(_) => None,
};
#[cfg(feature = "bus")]
if let Some(bus) = self.space.as_ref().and_then(|space| space.bus) {
use crate::bus::{DropAsk, DropTarget};
let target = match *destination {
TabDestination::Window(_) => DropTarget::NewWindow,
TabDestination::EmptySurface(_) => DropTarget::EmptyDock,
TabDestination::Node(_, crate::TabInsert::Append) => DropTarget::Append,
TabDestination::Node(_, crate::TabInsert::Insert(index)) => {
DropTarget::Insert(index.0)
}
TabDestination::Node(_, crate::TabInsert::Split(split)) => DropTarget::Split(split),
};
let to_surface = match *destination {
TabDestination::Node(path, _) => Some(path.surface),
TabDestination::EmptySurface(surface) => Some(surface),
TabDestination::Window(_) => None,
};
let leaf_tabs = self.dock_state[src]
.tabs()
.expect("drags can only come from leaf nodes");
let ask = DropAsk {
tabs: leaf_tabs[tabs].iter().map(bus.key).collect(),
group,
from: self.dock_name(src.surface).map(str::to_owned),
to: to.map(str::to_owned),
from_float: self.is_float_dock(src.surface),
to_float: to_surface.is_some_and(|surface| self.is_float_dock(surface)),
target,
zone: self.drop_zone_of(to),
};
return bus
.drop_refusal(ask, fresh)
.map(|reason| (!reason.is_empty()).then(|| reason.into()));
}
let _ = (group, fresh);
let drop = DockDrop {
destination,
from: self.dock_name(src.surface),
to,
};
let leaf_tabs = self.dock_state[src]
.tabs()
.expect("drags can only come from leaf nodes");
leaf_tabs[tabs]
.iter()
.find_map(|tab| match tab_viewer.dock_drop_allowed(tab, &drop) {
DropVerdict::Allow => None,
DropVerdict::Refuse(reason) => Some(reason),
})
}
fn hover_outside(
&self,
dock_rect: Rect,
state: &State,
drag_data: &Option<DragData>,
) -> Option<HoverData> {
if drag_data.is_none()
|| self.style.as_ref().unwrap().overlay.overlay_type != OverlayType::Zones
{
return None;
}
let pointer = state.last_hover_pos?;
let viewport = self.space.as_ref().and_then(|space| space.viewport);
let in_a_dock = match &self.space {
None => dock_rect.contains(pointer),
Some(space) => space
.docks
.iter()
.filter(|dock| dock.viewport.is_none_or(|v| Some(v) == viewport))
.filter_map(|dock| dock.rect)
.any(|rect| rect.contains(pointer)),
};
let over_a_float = self.space.as_ref().is_some_and(|space| {
!space.native
&& space
.floating
.rects
.iter()
.any(|rect| rect.contains(pointer))
});
let over_a_window = over_a_float
|| self
.dock_state
.valid_surface_indices()
.iter()
.filter_map(|&surface| self.dock_state.get_window_state(surface))
.any(|window| window.rect().contains(pointer));
(!in_a_dock && !over_a_window).then_some(HoverData {
rect: Rect::NOTHING,
dst: TreeComponent::Surface(SurfaceIndex::main()),
tab: None,
tab_bar: None,
outside: true,
})
}
#[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 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 (src_surface, dst_surface) = (
drag_state.drag.src.surface_address(),
drag_state.hover.dst.surface_address(),
);
let dock_splits = if drag_state.hover.outside {
AllowedSplits::All
} else {
self.dock_rules(dst_surface)
.map_or(AllowedSplits::All, |rules| rules.splits)
};
let allowed_splits = self.allowed_splits & restricted_splits & dock_splits;
if let TreeComponent::Node(src) = drag_state.drag.src
&& !drag_state.hover.outside
&& drag_state.hover.dst.node_address() == (src.surface, Some(src.node))
{
return None;
}
let allowed_in_window = match drag_state.drag.src {
TreeComponent::Tab(path) => self.may_float(path, tab_viewer),
TreeComponent::Node(path) => self.node_may_float(path, tab_viewer),
TreeComponent::Surface(_) => unreachable!("surfaces can't be dragged (yet)"),
};
let drag_state = state.dnd.as_mut().unwrap();
drag_state.src_in_window = self.dock_state.is_window(src_surface);
drag_state.dst_in_window =
!drag_state.hover.outside && self.dock_state.is_window(dst_surface);
let style = self.style.as_ref().unwrap();
if let Some(pointer) = state.last_hover_pos {
drag_state.pointer = pointer;
}
let window_bounds = self.window_bounds.unwrap();
let painter: &dyn DockPainter = self.painter.0;
let (destination, from_buttons) =
match (style.overlay.overlay_type, drag_state.is_on_title_bar()) {
(OverlayType::HighlightedAreas, _) | (_, true) => (
drag_state.resolve_traditional(
ui,
style,
painter,
allowed_splits,
allowed_in_window,
),
false,
),
(OverlayType::Widgets, false) => (
drag_state.resolve_icon_based(
ui,
style,
painter,
allowed_splits,
allowed_in_window,
),
true,
),
(OverlayType::Zones, false) => (
drag_state.resolve_zones(ui, style, painter, allowed_splits, allowed_in_window),
false,
),
};
let destination = destination?;
let from_buttons = from_buttons && !matches!(destination, TabDestination::Window(_));
let released = ui.input(|i| i.pointer.primary_released());
let refusal = self.drop_refusal(state, tab_viewer, &destination, released);
let allowed = refusal.is_none();
let drag_state = state.dnd.as_ref().unwrap();
drag_state.paint_preview(
ui,
style,
painter,
&destination,
from_buttons,
refusal,
window_bounds,
);
allowed.then_some(destination)
}
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 !self.dock_state.is_window(surf_index) {
self.show_root_surface_inside(ui, tab_viewer, state, surf_index);
} 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,
};
for separator in separators(&self.dock_state[path]) {
let name = self.separator_name(path, separator, tab_viewer);
self.show_separator(ui, path, separator, &name, 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 !self.dock_state.is_window(surface) {
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) {
let style = self.style.as_ref().unwrap();
let pixels_per_point = ui.ctx().pixels_per_point();
let tree = &self.dock_state[path.surface];
let linear = match &tree[path.node] {
Node::Linear(linear) => linear,
Node::Grid(_) => return self.compute_grid_rect_sizes(ui, path, max_rect),
_ => unreachable!("only containers have children"),
};
let rect = linear.rect;
debug_assert!(!rect.any_nan() && rect.is_finite());
let rect = expand_to_pixel(rect, pixels_per_point);
let collapsed: Vec<Option<i32>> = linear
.children()
.iter()
.map(|&child| {
(linear.dir == LinearDir::Vertical && tree[child].is_collapsed())
.then(|| tree[child].collapsed_leaf_count())
})
.collect();
let axis = linear.dir;
let (start, size) = match axis {
LinearDir::Horizontal => (rect.min.x, rect.width()),
LinearDir::Vertical => (rect.min.y, rect.height()),
};
let boundaries = boundaries(linear, &collapsed, size, style.tab_bar.height);
let children = linear.children().to_vec();
let half = style.separator.width * 0.5;
let last = children.len() - 1;
for (index, child) in children.into_iter().enumerate() {
let mut child_rect = rect;
let (min, max) = match axis {
LinearDir::Horizontal => (&mut child_rect.min.x, &mut child_rect.max.x),
LinearDir::Vertical => (&mut child_rect.min.y, &mut child_rect.max.y),
};
if index > 0 {
*min = map_to_pixel(
start + boundaries[index - 1] + half,
pixels_per_point,
f32::round,
);
}
if index < last {
*max = map_to_pixel(
start + boundaries[index] - half,
pixels_per_point,
f32::round,
);
}
let child_rect = rect.intersect(child_rect).intersect(max_rect);
self.dock_state[path.surface][child].set_rect(child_rect);
}
}
fn compute_grid_rect_sizes(&mut self, ui: &Ui, path: NodePath, max_rect: Rect) {
let style = self.style.as_ref().unwrap();
let pixels_per_point = ui.ctx().pixels_per_point();
let half = style.separator.width * 0.5;
let Node::Grid(grid) = &mut self.dock_state[path.surface][path.node] else {
unreachable!("a grid node")
};
grid.fit_shares();
let grid = grid.clone();
debug_assert!(!grid.rect.any_nan() && grid.rect.is_finite());
let rect = expand_to_pixel(grid.rect, pixels_per_point);
let span = |shares: &[f32], index: usize, count: usize, start: f32, size: f32| {
let min = if index > 0 {
map_to_pixel(
start + size * shares::boundary(shares, index - 1) + half,
pixels_per_point,
f32::round,
)
} else {
start
};
let max = if index + 1 < count {
map_to_pixel(
start + size * shares::boundary(shares, index) - half,
pixels_per_point,
f32::round,
)
} else {
start + size
};
(min, max)
};
let (columns, rows) = (grid.columns(), grid.rows());
for (index, &child) in grid.children().iter().enumerate() {
let (column, row) = grid.cell(index);
let (min_x, max_x) = span(grid.col_shares(), column, columns, rect.min.x, rect.width());
let (min_y, max_y) = span(grid.row_shares(), row, rows, rect.min.y, rect.height());
let child_rect = Rect::from_min_max(pos2(min_x, min_y), pos2(max_x, max_y));
let child_rect = rect.intersect(child_rect).intersect(max_rect);
self.dock_state[path.surface][child].set_rect(child_rect);
}
}
fn separator_name(
&mut self,
path: NodePath,
separator_of: SeparatorOf,
tab_viewer: &mut impl TabViewer<Tab = Tab>,
) -> String {
let surface = &mut self.dock_state[path.surface];
let pair = match (&surface[path.node], separator_of) {
(Node::Linear(linear), SeparatorOf::Linear(index)) => {
Some([linear.children()[index], linear.children()[index + 1]])
}
_ => None,
};
let mut title = |side: NodeIndex| {
let leaf = surface.first_leaf(side)?;
let leaf = surface[leaf].get_leaf_mut()?;
let active = leaf.active.0;
let tab = leaf.tabs.get_mut(active)?;
Some(tab_viewer.title(tab).text().to_owned())
};
match pair.map(|[first, second]| (title(first), title(second))) {
Some((Some(first), Some(second))) => self
.labels
.separator_between
.replace("{first}", &first)
.replace("{second}", &second),
_ => self.labels.separator.to_string(),
}
}
fn show_separator(
&mut self,
ui: &mut Ui,
path: NodePath,
separator_of: SeparatorOf,
label: &str,
fade_style: Option<&Style>,
) {
let tree = &self.dock_state[path.surface];
if let (Node::Linear(linear), SeparatorOf::Linear(index)) = (&tree[path.node], separator_of)
{
let pair = [linear.children()[index], linear.children()[index + 1]];
if linear.dir == LinearDir::Vertical && pair.iter().any(|&c| tree[c].is_collapsed()) {
return;
}
}
let style = fade_style.unwrap_or_else(|| self.style.as_ref().unwrap());
let pixels_per_point = ui.ctx().pixels_per_point();
let painter = self.painter.0;
let (horizontal, rect, shares, index) =
match (&mut self.dock_state[path.surface][path.node], separator_of) {
(Node::Linear(linear), SeparatorOf::Linear(index)) => (
linear.dir == LinearDir::Horizontal,
linear.rect,
&mut linear.shares,
index,
),
(Node::Grid(grid), SeparatorOf::Column(index)) => {
(true, grid.rect, &mut grid.col_shares, index)
}
(Node::Grid(grid), SeparatorOf::Row(index)) => {
(false, grid.rect, &mut grid.row_shares, index)
}
_ => unreachable!("a separator of this container"),
};
let dim = |v: Vec2| if horizontal { v.x } else { v.y };
let along = |r: Rect| {
if horizontal {
(r.min.x, r.max.x)
} else {
(r.min.y, r.max.y)
}
};
let set_along = |r: &mut Rect, min: f32, max: f32| {
if horizontal {
(r.min.x, r.max.x) = (min, max);
} else {
(r.min.y, r.max.y) = (min, max);
}
};
let (start, end) = along(rect);
let range = end - start;
let mut separator = rect;
let midpoint = start + range * shares::boundary(shares, index);
set_along(
&mut separator,
midpoint - style.separator.width * 0.5,
midpoint + style.separator.width * 0.5,
);
let mut expand = Vec2::ZERO;
if horizontal {
expand.x += style.separator.extra_interact_width / 2.0;
} else {
expand.y += style.separator.extra_interact_width / 2.0;
}
let interact_rect = separator.expand2(expand);
let cursor = if horizontal {
CursorIcon::ResizeHorizontal
} else {
CursorIcon::ResizeVertical
};
let response = ui
.allocate_rect(interact_rect, Sense::click_and_drag())
.on_hover_and_drag_cursor(cursor);
if response.has_focus() {
ui.memory_mut(|m| {
m.set_focus_lock_filter(
response.id,
EventFilter {
horizontal_arrows: horizontal,
vertical_arrows: !horizontal,
tab: false,
escape: false,
},
)
});
}
let (back_key, forward_key) = if horizontal {
(Key::ArrowLeft, Key::ArrowRight)
} else {
(Key::ArrowUp, Key::ArrowDown)
};
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(back_key) {
Some(-step)
} else if i.key_pressed(forward_key) {
Some(step)
} else {
None
};
(offset, i.key_pressed(Key::Enter))
})
} else {
(None, false)
};
set_along(
&mut separator,
map_to_pixel(
midpoint - style.separator.width * 0.5,
pixels_per_point,
f32::round,
),
map_to_pixel(
midpoint + style.separator.width * 0.5,
pixels_per_point,
f32::round,
),
);
painter.separator(
ui.painter(),
&SeparatorPaint {
rect: separator,
axis: if horizontal {
SeparatorAxis::Vertical
} else {
SeparatorAxis::Horizontal
},
state: PartState::NONE
.with(PartState::HOVERED, response.hovered())
.with(PartState::PRESSED, response.is_pointer_button_down_on())
.with(PartState::FOCUSED, response.has_focus())
.with(PartState::DRAGGED, response.dragged()),
style,
},
);
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_part = if range > 0.0 {
(style.separator.extra / range).min(1.0)
} else {
0.0
};
if range > 0.0 {
let delta = arrow_key_offset.unwrap_or(dim(response.drag_delta()));
let boundary = shares::boundary(shares, index);
let target = accesskit_value.unwrap_or(boundary)
+ delta / range
+ accesskit_steps * accesskit_step;
if target != boundary {
shares::move_boundary(shares, index, target - boundary, min_part);
}
}
if response.double_clicked() || reset {
shares::even_pair(shares, index);
}
let value = shares::boundary(shares, index);
let pair_start = if index == 0 {
0.0
} else {
shares::boundary(shares, index - 1)
};
let pair_end = shares::boundary(shares, index + 1);
let (min, max) = if range > 0.0 {
let min = pair_start + min_part;
let max = pair_end - min_part;
(min.min(max), max.max(min))
} else {
(value, value)
};
let enabled = ui.is_enabled();
response.widget_info(|| {
let mut info = WidgetInfo::labeled(Role::Splitter, enabled, label);
info.value = Some(f64::from(value));
info
});
ui.ctx().accesskit_node_builder(response.id, |node| {
node.set_orientation(if horizontal {
Orientation::Vertical
} else {
Orientation::Horizontal
});
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 value < max {
node.add_action(Action::Increment);
}
if min < value {
node.add_action(Action::Decrement);
}
}
});
}
}
#[derive(Clone, Copy, Debug)]
enum SeparatorOf {
Linear(usize),
Column(usize),
Row(usize),
}
fn separators<Tab>(node: &Node<Tab>) -> Vec<SeparatorOf> {
match node {
Node::Linear(linear) => (0..linear.len().saturating_sub(1))
.map(SeparatorOf::Linear)
.collect(),
Node::Grid(grid) => (0..grid.columns() - 1)
.map(SeparatorOf::Column)
.chain((0..grid.rows() - 1).map(SeparatorOf::Row))
.collect(),
_ => Vec::new(),
}
}
fn boundaries(
linear: &crate::LinearNode,
collapsed: &[Option<i32>],
size: f32,
tab_bar_height: f32,
) -> Vec<f32> {
let n = linear.len();
let sizes: Vec<f32> = if collapsed.iter().all(Option::is_none) {
(0..n).map(|i| size * linear.fraction(i)).collect()
} else {
let fixed: f32 = collapsed
.iter()
.flatten()
.map(|&count| count as f32 * tab_bar_height)
.sum();
let open_total: f32 = (0..n)
.filter(|&i| collapsed[i].is_none())
.map(|i| linear.shares()[i])
.sum();
let open_count = collapsed.iter().filter(|c| c.is_none()).count() as f32;
let rest = (size - fixed).max(0.0);
let mut sizes: Vec<f32> = (0..n)
.map(|i| match collapsed[i] {
Some(count) => count as f32 * tab_bar_height,
None if open_total > 0.0 => rest * linear.shares()[i] / open_total,
None => rest / open_count,
})
.collect();
if open_count == 0.0 {
let others: f32 = sizes[..n - 1].iter().sum();
sizes[n - 1] = size - others;
}
sizes
};
sizes
.iter()
.take(n - 1)
.scan(0.0, |acc, s| {
*acc += s;
Some(*acc)
})
.collect()
}
pub(crate) fn restore_bands(restores: &[RestoreDrop], breadth: f32) -> Vec<Rect> {
let along = |dir: Dir, rect: Rect| match dir {
Dir::Horizontal => rect.min.x,
Dir::Vertical => rect.min.y,
};
let across = |dir: Dir, rect: Rect| match dir {
Dir::Horizontal => (rect.min.y, rect.max.y),
Dir::Vertical => (rect.min.x, rect.max.x),
};
let same_boundary = |a: &RestoreDrop, b: &RestoreDrop| {
let (a, b) = (&a.restore, &b.restore);
let (a_min, a_max) = across(a.dir, a.line);
let (b_min, b_max) = across(b.dir, b.line);
a.dir == b.dir
&& a.towards_end == b.towards_end
&& (along(a.dir, a.line) - along(b.dir, b.line)).abs() < 0.5
&& a_min < b_max
&& b_min < a_max
};
restores
.iter()
.enumerate()
.map(|(i, drop)| {
let restore = &drop.restore;
let before = restores[..i]
.iter()
.filter(|other| same_boundary(drop, other))
.count();
let count = restores
.iter()
.filter(|other| same_boundary(drop, other))
.count();
let line = along(restore.dir, restore.line);
let from = if restore.towards_end {
line + before as f32 * breadth
} else {
line - (count - before) as f32 * breadth
};
let (min, max) = across(restore.dir, restore.line);
match restore.dir {
Dir::Horizontal => Rect::from_min_max(pos2(from, min), pos2(from + breadth, max)),
Dir::Vertical => Rect::from_min_max(pos2(min, from), pos2(max, from + breadth)),
}
})
.collect()
}