Add mousebinds to API

This commit is contained in:
Ottatop 2023-09-10 21:54:58 -05:00
parent 7f5d9e431c
commit 1c1898f0b1
7 changed files with 287 additions and 112 deletions

View file

@ -19,6 +19,8 @@ require("pinnacle").setup(function(pinnacle)
-- Every key supported by xkbcommon. -- Every key supported by xkbcommon.
local keys = input.keys local keys = input.keys
-- Mouse buttons
local buttons = input.buttons
---@type Modifier ---@type Modifier
local mod_key = "Ctrl" -- This is set to `Ctrl` instead of `Super` to not conflict with your WM/DE keybinds local mod_key = "Ctrl" -- This is set to `Ctrl` instead of `Super` to not conflict with your WM/DE keybinds
@ -37,6 +39,15 @@ require("pinnacle").setup(function(pinnacle)
-- --
-- dell:set_loc_left_of(lg, "bottom") -- dell:set_loc_left_of(lg, "bottom")
-- Mousebinds --------------------------------------------------------------------
input.mousebind({ "Ctrl" }, buttons.left, "Press", function()
window.begin_move(buttons.left)
end)
input.mousebind({ "Ctrl" }, buttons.right, "Press", function()
window.begin_resize(buttons.right)
end)
-- Keybinds ---------------------------------------------------------------------- -- Keybinds ----------------------------------------------------------------------
-- mod_key + Alt + q quits the compositor -- mod_key + Alt + q quits the compositor

View file

@ -7,6 +7,32 @@
local input_module = { local input_module = {
--- A table with every key provided by xkbcommon. --- A table with every key provided by xkbcommon.
keys = require("keys"), keys = require("keys"),
--- A table with mouse button codes. You can use indexes (1, 2, and 3 are left, right, and middle)
--- or keyed values (buttons.left, buttons.right, etc.).
---@enum MouseButton
buttons = {
--- Left
[1] = 0x110,
--- Right
[2] = 0x111,
--- Middle
[3] = 0x112,
--- Side
[4] = 0x113,
--- Extra
[5] = 0x114,
--- Forward
[6] = 0x115,
--- Back
[7] = 0x116,
left = 0x110,
right = 0x111,
middle = 0x112,
side = 0x113,
extra = 0x114,
forward = 0x115,
back = 0x116,
},
} }
---Set a keybind. If called with an already existing keybind, it gets replaced. ---Set a keybind. If called with an already existing keybind, it gets replaced.
@ -63,4 +89,26 @@ function input_module.keybind(modifiers, key, action)
}) })
end end
---Set a mousebind. If called with an already existing mousebind, it gets replaced.
---
---The mousebind can happen either on button press or release, so you must specify
---which edge you desire.
---
---@param modifiers (Modifier)[] The modifiers that need to be held for the mousebind to trigger.
---@param button MouseButton The button that needs to be pressed or released.
---@param edge "Press"|"Release" Whether or not to trigger `action` on button press or release.
---@param action fun() The function to run.
function input_module.mousebind(modifiers, button, edge, action)
table.insert(CallbackTable, action)
SendMsg({
SetMousebind = {
modifiers = modifiers,
button = button,
edge = edge,
callback_id = #CallbackTable,
},
})
end
return input_module return input_module

View file

@ -4,7 +4,7 @@
---@class _Msg ---@class _Msg
---@field SetKeybind { key: { Int: Keys?, String: string? }, modifiers: Modifier[], callback_id: integer }? ---@field SetKeybind { key: { Int: Keys?, String: string? }, modifiers: Modifier[], callback_id: integer }?
---@field SetMousebind { button: integer }? ---@field SetMousebind { modifiers: (Modifier)[], button: integer, edge: "Press"|"Release", callback_id: integer }?
--Windows --Windows
---@field CloseWindow { window_id: WindowId }? ---@field CloseWindow { window_id: WindowId }?
---@field SetWindowSize { window_id: WindowId, width: integer?, height: integer? }? ---@field SetWindowSize { window_id: WindowId, width: integer?, height: integer? }?
@ -14,6 +14,8 @@
---@field ToggleFullscreen { window_id: WindowId }? ---@field ToggleFullscreen { window_id: WindowId }?
---@field ToggleMaximized { window_id: WindowId }? ---@field ToggleMaximized { window_id: WindowId }?
---@field AddWindowRule { cond: _WindowRuleCondition, rule: _WindowRule }? ---@field AddWindowRule { cond: _WindowRuleCondition, rule: _WindowRule }?
---@field WindowMoveGrab { button: integer }?
---@field WindowResizeGrab { button: integer }?
-- --
---@field Spawn { command: string[], callback_id: integer? }? ---@field Spawn { command: string[], callback_id: integer? }?
---@field SetEnv { key: string, value: string }? ---@field SetEnv { key: string, value: string }?

View file

@ -552,4 +552,31 @@ function window_module.focused(win)
local focused = response.RequestResponse.response.WindowProps.focused local focused = response.RequestResponse.response.WindowProps.focused
return focused return focused
end end
---Begin a window move.
---
---This will start a window move grab with the provided button on the window the pointer
---is currently hovering over. Once `button` is let go, the move will end.
---@param button MouseButton The button you want to trigger the move.
function window_module.begin_move(button)
SendMsg({
WindowMoveGrab = {
button = button,
},
})
end
---Begin a window resize.
---
---This will start a window resize grab with the provided button on the window the
---pointer is currently hovering over. Once `button` is let go, the resize will end.
---@param button MouseButton
function window_module.begin_resize(button)
SendMsg({
WindowResizeGrab = {
button = button,
},
})
end
return window_module return window_module

View file

@ -5,6 +5,8 @@
pub mod window_rules; pub mod window_rules;
use smithay::input::keyboard::ModifiersState;
use crate::{ use crate::{
layout::Layout, layout::Layout,
output::OutputName, output::OutputName,
@ -23,6 +25,12 @@ pub enum KeyIntOrString {
String(String), String(String),
} }
#[derive(Debug, Hash, serde::Serialize, serde::Deserialize, Clone, Copy, PartialEq, Eq)]
pub enum MouseEdge {
Press,
Release,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)] #[derive(Debug, serde::Serialize, serde::Deserialize)]
pub enum Msg { pub enum Msg {
// Input // Input
@ -32,7 +40,10 @@ pub enum Msg {
callback_id: CallbackId, callback_id: CallbackId,
}, },
SetMousebind { SetMousebind {
button: u8, modifiers: Vec<Modifier>,
button: u32,
edge: MouseEdge,
callback_id: CallbackId,
}, },
// Window management // Window management
@ -67,6 +78,12 @@ pub enum Msg {
cond: WindowRuleCondition, cond: WindowRuleCondition,
rule: WindowRule, rule: WindowRule,
}, },
WindowMoveGrab {
button: u32,
},
WindowResizeGrab {
button: u32,
},
// Tag management // Tag management
ToggleTag { ToggleTag {
@ -153,8 +170,8 @@ pub enum Modifier {
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)] #[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub struct ModifierMask(u8); pub struct ModifierMask(u8);
impl<T: IntoIterator<Item = Modifier>> From<T> for ModifierMask { impl From<Vec<Modifier>> for ModifierMask {
fn from(value: T) -> Self { fn from(value: Vec<Modifier>) -> Self {
let value = value.into_iter(); let value = value.into_iter();
let mut mask: u8 = 0b0000_0000; let mut mask: u8 = 0b0000_0000;
for modifier in value { for modifier in value {
@ -164,6 +181,36 @@ impl<T: IntoIterator<Item = Modifier>> From<T> for ModifierMask {
} }
} }
impl From<&[Modifier]> for ModifierMask {
fn from(value: &[Modifier]) -> Self {
let value = value.iter();
let mut mask: u8 = 0b0000_0000;
for modifier in value {
mask |= *modifier as u8;
}
Self(mask)
}
}
impl From<ModifiersState> for ModifierMask {
fn from(state: ModifiersState) -> Self {
let mut mask: u8 = 0b0000_0000;
if state.shift {
mask |= Modifier::Shift as u8;
}
if state.ctrl {
mask |= Modifier::Ctrl as u8;
}
if state.alt {
mask |= Modifier::Alt as u8;
}
if state.logo {
mask |= Modifier::Super as u8;
}
Self(mask)
}
}
impl ModifierMask { impl ModifierMask {
#[allow(dead_code)] #[allow(dead_code)]
pub fn values(self) -> Vec<Modifier> { pub fn values(self) -> Vec<Modifier> {

View file

@ -3,7 +3,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{ use crate::{
api::msg::{CallbackId, Modifier, ModifierMask, OutgoingMsg}, api::msg::{CallbackId, Modifier, ModifierMask, MouseEdge, OutgoingMsg},
focus::FocusTarget, focus::FocusTarget,
state::{Backend, WithState}, state::{Backend, WithState},
window::WindowElement, window::WindowElement,
@ -21,7 +21,6 @@ use smithay::{
keyboard::{keysyms, FilterResult}, keyboard::{keysyms, FilterResult},
pointer::{AxisFrame, ButtonEvent, MotionEvent}, pointer::{AxisFrame, ButtonEvent, MotionEvent},
}, },
reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::ResizeEdge,
utils::{Logical, Point, SERIAL_COUNTER}, utils::{Logical, Point, SERIAL_COUNTER},
wayland::{seat::WaylandFocus, shell::wlr_layer}, wayland::{seat::WaylandFocus, shell::wlr_layer},
}; };
@ -32,7 +31,7 @@ pub struct InputState {
/// A hashmap of modifier keys and keycodes to callback IDs /// A hashmap of modifier keys and keycodes to callback IDs
pub keybinds: HashMap<(ModifierMask, u32), CallbackId>, pub keybinds: HashMap<(ModifierMask, u32), CallbackId>,
/// A hashmap of modifier keys and mouse button codes to callback IDs /// A hashmap of modifier keys and mouse button codes to callback IDs
pub mousebinds: HashMap<(ModifierMask, u32), CallbackId>, pub mousebinds: HashMap<(ModifierMask, u32, MouseEdge), CallbackId>,
pub reload_keybind: (ModifierMask, u32), pub reload_keybind: (ModifierMask, u32),
pub kill_keybind: (ModifierMask, u32), pub kill_keybind: (ModifierMask, u32),
} }
@ -276,77 +275,36 @@ impl State {
let pointer_loc = pointer.current_location(); let pointer_loc = pointer.current_location();
let edge = match button_state {
ButtonState::Released => MouseEdge::Release,
ButtonState::Pressed => MouseEdge::Press,
};
let modifier_mask = ModifierMask::from(keyboard.modifier_state());
// If any mousebinds are detected, call the config's callback and return.
if let Some(&callback_id) = self
.input_state
.mousebinds
.get(&(modifier_mask, button, edge))
{
if let Some(stream) = self.api_state.stream.clone() {
let mut stream = stream.lock().expect("failed to lock api stream");
crate::api::send_to_client(
&mut stream,
&OutgoingMsg::CallCallback {
callback_id,
args: None,
},
)
.expect("failed to call callback");
}
return;
}
// If the button was clicked, focus on the window below if exists, else // If the button was clicked, focus on the window below if exists, else
// unfocus on windows. // unfocus on windows.
if ButtonState::Pressed == button_state { if ButtonState::Pressed == button_state {
if let Some((focus, window_loc)) = self.surface_under(pointer_loc) { if let Some((focus, _)) = self.surface_under(pointer_loc) {
// tracing::debug!("button click on {window:?}");
const BUTTON_LEFT: u32 = 0x110;
const BUTTON_RIGHT: u32 = 0x111;
if self.move_mode {
if event.button_code() == BUTTON_LEFT {
if let Some(wl_surf) = focus.wl_surface() {
crate::grab::move_grab::move_request_server(
self,
&wl_surf,
&self.seat.clone(),
serial,
BUTTON_LEFT,
);
}
return; // TODO: kinda ugly return here
} else if event.button_code() == BUTTON_RIGHT {
let FocusTarget::Window(window) = focus else { return };
let window_geometry = window.geometry();
let window_x = window_loc.x as f64;
let window_y = window_loc.y as f64;
let window_width = window_geometry.size.w as f64;
let window_height = window_geometry.size.h as f64;
let half_width = window_x + window_width / 2.0;
let half_height = window_y + window_height / 2.0;
let full_width = window_x + window_width;
let full_height = window_y + window_height;
let edges = match pointer_loc {
Point { x, y, .. }
if (window_x..=half_width).contains(&x)
&& (window_y..=half_height).contains(&y) =>
{
ResizeEdge::TopLeft
}
Point { x, y, .. }
if (half_width..=full_width).contains(&x)
&& (window_y..=half_height).contains(&y) =>
{
ResizeEdge::TopRight
}
Point { x, y, .. }
if (window_x..=half_width).contains(&x)
&& (half_height..=full_height).contains(&y) =>
{
ResizeEdge::BottomLeft
}
Point { x, y, .. }
if (half_width..=full_width).contains(&x)
&& (half_height..=full_height).contains(&y) =>
{
ResizeEdge::BottomRight
}
_ => ResizeEdge::None,
};
if let Some(wl_surf) = window.wl_surface() {
crate::grab::resize_grab::resize_request_server(
self,
&wl_surf,
&self.seat.clone(),
serial,
edges.into(),
BUTTON_RIGHT,
);
}
}
} else {
// Move window to top of stack. // Move window to top of stack.
if let FocusTarget::Window(window) = &focus { if let FocusTarget::Window(window) = &focus {
self.space.raise_element(window, true); self.space.raise_element(window, true);
@ -386,7 +344,6 @@ impl State {
if let FocusTarget::Window(window) = &focus { if let FocusTarget::Window(window) = &focus {
tracing::debug!("setting keyboard focus to {:?}", window.class()); tracing::debug!("setting keyboard focus to {:?}", window.class());
} }
}
} else { } else {
self.space.elements().for_each(|window| match window { self.space.elements().for_each(|window| match window {
WindowElement::Wayland(window) => { WindowElement::Wayland(window) => {

View file

@ -4,7 +4,8 @@ use async_process::Stdio;
use futures_lite::AsyncBufReadExt; use futures_lite::AsyncBufReadExt;
use smithay::{ use smithay::{
desktop::space::SpaceElement, desktop::space::SpaceElement,
utils::Rectangle, reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::ResizeEdge,
utils::{Point, Rectangle, SERIAL_COUNTER},
wayland::{compositor, shell::xdg::XdgToplevelSurfaceData}, wayland::{compositor, shell::xdg::XdgToplevelSurfaceData},
}; };
@ -12,6 +13,7 @@ use crate::{
api::msg::{ api::msg::{
Args, CallbackId, KeyIntOrString, Msg, OutgoingMsg, Request, RequestId, RequestResponse, Args, CallbackId, KeyIntOrString, Msg, OutgoingMsg, Request, RequestId, RequestResponse,
}, },
focus::FocusTarget,
tag::Tag, tag::Tag,
window::WindowElement, window::WindowElement,
}; };
@ -51,7 +53,17 @@ impl State {
.keybinds .keybinds
.insert((modifiers.into(), key), callback_id); .insert((modifiers.into(), key), callback_id);
} }
Msg::SetMousebind { button: _ } => todo!(), Msg::SetMousebind {
modifiers,
button,
edge,
callback_id,
} => {
// TODO: maybe validate/parse valid codes?
self.input_state
.mousebinds
.insert((modifiers.into(), button, edge), callback_id);
}
Msg::CloseWindow { window_id } => { Msg::CloseWindow { window_id } => {
if let Some(window) = window_id.window(self) { if let Some(window) = window_id.window(self) {
match window { match window {
@ -146,6 +158,77 @@ impl State {
Msg::AddWindowRule { cond, rule } => { Msg::AddWindowRule { cond, rule } => {
self.window_rules.push((cond, rule)); self.window_rules.push((cond, rule));
} }
Msg::WindowMoveGrab { button } => {
// TODO: in the future, there may be movable layer surfaces
let Some((FocusTarget::Window(window), _)) =
self.surface_under(self.pointer_location) else { return };
let Some(wl_surf) = window.wl_surface() else { return };
let seat = self.seat.clone();
// We use the server one and not the client because windows like Steam don't provide
// GrabStartData, so we need to create it ourselves.
crate::grab::move_grab::move_request_server(
self,
&wl_surf,
&seat,
SERIAL_COUNTER.next_serial(),
button,
);
}
Msg::WindowResizeGrab { button } => {
// TODO: in the future, there may be movable layer surfaces
let pointer_loc = self.pointer_location;
let Some((FocusTarget::Window(window), window_loc)) =
self.surface_under(pointer_loc) else { return };
let Some(wl_surf) = window.wl_surface() else { return };
let window_geometry = window.geometry();
let window_x = window_loc.x as f64;
let window_y = window_loc.y as f64;
let window_width = window_geometry.size.w as f64;
let window_height = window_geometry.size.h as f64;
let half_width = window_x + window_width / 2.0;
let half_height = window_y + window_height / 2.0;
let full_width = window_x + window_width;
let full_height = window_y + window_height;
let edges = match pointer_loc {
Point { x, y, .. }
if (window_x..=half_width).contains(&x)
&& (window_y..=half_height).contains(&y) =>
{
ResizeEdge::TopLeft
}
Point { x, y, .. }
if (half_width..=full_width).contains(&x)
&& (window_y..=half_height).contains(&y) =>
{
ResizeEdge::TopRight
}
Point { x, y, .. }
if (window_x..=half_width).contains(&x)
&& (half_height..=full_height).contains(&y) =>
{
ResizeEdge::BottomLeft
}
Point { x, y, .. }
if (half_width..=full_width).contains(&x)
&& (half_height..=full_height).contains(&y) =>
{
ResizeEdge::BottomRight
}
_ => ResizeEdge::None,
};
crate::grab::resize_grab::resize_request_server(
self,
&wl_surf,
&self.seat.clone(),
SERIAL_COUNTER.next_serial(),
edges.into(),
button,
);
}
// Tags ---------------------------------------- // Tags ----------------------------------------
Msg::ToggleTag { tag_id } => { Msg::ToggleTag { tag_id } => {