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.
local keys = input.keys
-- Mouse buttons
local buttons = input.buttons
---@type Modifier
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")
-- 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 ----------------------------------------------------------------------
-- mod_key + Alt + q quits the compositor

View file

@ -7,6 +7,32 @@
local input_module = {
--- A table with every key provided by xkbcommon.
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.
@ -63,4 +89,26 @@ function input_module.keybind(modifiers, key, action)
})
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

View file

@ -4,7 +4,7 @@
---@class _Msg
---@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
---@field CloseWindow { window_id: WindowId }?
---@field SetWindowSize { window_id: WindowId, width: integer?, height: integer? }?
@ -14,6 +14,8 @@
---@field ToggleFullscreen { window_id: WindowId }?
---@field ToggleMaximized { window_id: WindowId }?
---@field AddWindowRule { cond: _WindowRuleCondition, rule: _WindowRule }?
---@field WindowMoveGrab { button: integer }?
---@field WindowResizeGrab { button: integer }?
--
---@field Spawn { command: string[], callback_id: integer? }?
---@field SetEnv { key: string, value: string }?

View file

@ -552,4 +552,31 @@ function window_module.focused(win)
local focused = response.RequestResponse.response.WindowProps.focused
return focused
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

View file

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

View file

@ -3,7 +3,7 @@
use std::collections::HashMap;
use crate::{
api::msg::{CallbackId, Modifier, ModifierMask, OutgoingMsg},
api::msg::{CallbackId, Modifier, ModifierMask, MouseEdge, OutgoingMsg},
focus::FocusTarget,
state::{Backend, WithState},
window::WindowElement,
@ -21,7 +21,6 @@ use smithay::{
keyboard::{keysyms, FilterResult},
pointer::{AxisFrame, ButtonEvent, MotionEvent},
},
reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::ResizeEdge,
utils::{Logical, Point, SERIAL_COUNTER},
wayland::{seat::WaylandFocus, shell::wlr_layer},
};
@ -32,7 +31,7 @@ pub struct InputState {
/// A hashmap of modifier keys and keycodes to callback IDs
pub keybinds: HashMap<(ModifierMask, u32), CallbackId>,
/// 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 kill_keybind: (ModifierMask, u32),
}
@ -276,77 +275,36 @@ impl State {
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
// unfocus on windows.
if ButtonState::Pressed == button_state {
if let Some((focus, window_loc)) = 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 {
if let Some((focus, _)) = self.surface_under(pointer_loc) {
// Move window to top of stack.
if let FocusTarget::Window(window) = &focus {
self.space.raise_element(window, true);
@ -386,7 +344,6 @@ impl State {
if let FocusTarget::Window(window) = &focus {
tracing::debug!("setting keyboard focus to {:?}", window.class());
}
}
} else {
self.space.elements().for_each(|window| match window {
WindowElement::Wayland(window) => {

View file

@ -4,7 +4,8 @@ use async_process::Stdio;
use futures_lite::AsyncBufReadExt;
use smithay::{
desktop::space::SpaceElement,
utils::Rectangle,
reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::ResizeEdge,
utils::{Point, Rectangle, SERIAL_COUNTER},
wayland::{compositor, shell::xdg::XdgToplevelSurfaceData},
};
@ -12,6 +13,7 @@ use crate::{
api::msg::{
Args, CallbackId, KeyIntOrString, Msg, OutgoingMsg, Request, RequestId, RequestResponse,
},
focus::FocusTarget,
tag::Tag,
window::WindowElement,
};
@ -51,7 +53,17 @@ impl State {
.keybinds
.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 } => {
if let Some(window) = window_id.window(self) {
match window {
@ -146,6 +158,77 @@ impl State {
Msg::AddWindowRule { 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 ----------------------------------------
Msg::ToggleTag { tag_id } => {