use gpui::{App, Axis, FocusHandle, Window};
use gpui_material_theme::Direction;
pub fn move_roving_focus(
items: &[(&FocusHandle, bool)],
key: &str,
axis: Axis,
direction: Direction,
window: &mut Window,
cx: &mut App,
) -> Option<usize> {
match key {
"home" => {
return items.iter().enumerate().find_map(|(ix, (focus, enabled))| {
enabled.then(|| {
focus.focus(window, cx);
ix
})
});
}
"end" => {
return items
.iter()
.enumerate()
.rev()
.find_map(|(ix, (focus, enabled))| {
enabled.then(|| {
focus.focus(window, cx);
ix
})
});
}
_ => {}
}
let backward = match key {
"left" if axis == Axis::Horizontal => direction == Direction::Ltr,
"right" if axis == Axis::Horizontal => direction == Direction::Rtl,
"up" if axis == Axis::Vertical => true,
"down" if axis == Axis::Vertical => false,
_ => return None,
};
let len = items.len();
let current = items.iter().position(|(focus, _)| focus.is_focused(window));
let start = current.unwrap_or(if backward { 0 } else { len.saturating_sub(1) });
(1..=len).find_map(|offset| {
let ix = if backward {
(start + len - offset) % len
} else {
(start + offset) % len
};
let (focus, enabled) = items[ix];
enabled.then(|| {
focus.focus(window, cx);
ix
})
})
}
pub struct DragCapture {
#[cfg(windows)]
_watch: Option<gpui::Task<()>>,
}
impl DragCapture {
pub fn watch(
window: &Window,
cx: &App,
on_lost: impl FnOnce(&mut Window, &mut App) + 'static,
) -> Self {
Self::watch_capture(
window,
cx,
|_, cx| cx.has_active_drag(),
move |window, cx| {
window.release_pointer();
cx.stop_active_drag(window);
on_lost(window, cx);
},
)
}
pub fn watch_pointer(
window: &Window,
cx: &App,
on_lost: impl FnOnce(&mut Window, &mut App) + 'static,
) -> Self {
Self::watch_capture(
window,
cx,
|window, _| window.captured_hitbox().is_some(),
move |window, cx| {
window.release_pointer();
on_lost(window, cx);
},
)
}
fn watch_capture(
window: &Window,
cx: &App,
is_active: fn(&Window, &App) -> bool,
on_lost: impl FnOnce(&mut Window, &mut App) + 'static,
) -> Self {
#[cfg(windows)]
{
use std::time::Duration;
use windows::Win32::UI::Input::KeyboardAndMouse::GetCapture;
let capture = unsafe { GetCapture() };
let watch = (!capture.is_invalid()).then(|| {
let executor = cx.background_executor().clone();
let mut on_lost = Some(on_lost);
window.spawn(cx, async move |cx| {
loop {
executor.timer(Duration::from_millis(16)).await;
let keep_watching = cx.update(|window, cx| {
if !is_active(window, cx) {
return false;
}
if unsafe { GetCapture() } == capture {
return true;
}
if let Some(on_lost) = on_lost.take() {
on_lost(window, cx);
}
false
});
if !keep_watching.unwrap_or(false) {
break;
}
}
})
});
Self { _watch: watch }
}
#[cfg(not(windows))]
{
let _ = (window, cx, is_active, on_lost);
Self {}
}
}
pub fn cancel(self, window: &mut Window, cx: &mut App) {
window.release_pointer();
cx.stop_active_drag(window);
}
}