Merge pull request #78 from pinnacle-comp/improve_api

Add env, mousebinds to Lua API
This commit is contained in:
Ottatop 2023-09-10 22:29:03 -05:00 committed by GitHub
commit 8499a291e2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 358 additions and 132 deletions

View file

@ -170,12 +170,23 @@ as well as any function overloads, but these should be autocompleted through the
Documentation for other branches can be reached at `https://pinnacle-comp.github.io/pinnacle/<branch name>`.
# Controls
The following controls are currently hardcoded:
- <kbd>Ctrl</kbd> + <kbd>Left click drag</kbd>: Move a window
- <kbd>Ctrl</kbd> + <kbd>Right click drag</kbd>: Resize a window
You can find the rest of the controls in the [`example_config`](api/lua/example_config.lua).
The following are the default controls in the [`example_config`](api/lua/example_config.lua).
| Binding | Action |
|----------------------------------------------|------------------------------------|
| <kbd>Ctrl</kbd> + <kbd>Mouse left drag</kbd> | Move window |
| <kbd>Ctrl</kbd> + <kbd>Mouse right drag</kbd>| Resize window |
| <kbd>Ctrl</kbd><kbd>Alt</kbd> + <kbd>q</kbd> | Quit Pinnacle |
| <kbd>Ctrl</kbd><kbd>Alt</kbd> + <kbd>c</kbd> | Close window |
| <kbd>Ctrl</kbd> + <kbd>Return</kbd> | Spawn [Alacritty](https://github.com/alacritty/alacritty) (you can change this in the config)|
| <kbd>Ctrl</kbd><kbd>Alt</kbd> + <kbd>Space</kbd> | Toggle between floating and tiled |
| <kbd>Ctrl</kbd> + <kbd>f</kbd> | Toggle fullscreen |
| <kbd>Ctrl</kbd> + <kbd>m</kbd> | Toggle maximized |
| <kbd>Ctrl</kbd> + <kbd>Space</kbd> | Cycle to the next layout |
| <kbd>Ctrl</kbd><kbd>Shift</kbd> + <kbd>Space</kbd> | Cycle to the previous layout |
| <kbd>Ctrl</kbd> + <kbd>1</kbd> to <kbd>5</kbd> | Switch to tag `1` to `5` |
| <kbd>Ctrl</kbd><kbd>Shift</kbd> + <kbd>1</kbd> to <kbd>5</kbd> | Toggle tag `1` to `5` |
| <kbd>Ctrl</kbd><kbd>Alt</kbd> + <kbd>1</kbd> to <kbd>5</kbd> | Move a window to tag `1` to `5` |
| <kbd>Ctrl</kbd><kbd>Alt</kbd><kbd>Shift</kbd> + <kbd>1</kbd> to <kbd>5</kbd> | Toggle tag `1` to `5` on a window |
# Feature Requests, Bug Reports, Contributions, and Questions
See [`CONTRIBUTING.md`](CONTRIBUTING.md).

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
@ -26,6 +28,8 @@ require("pinnacle").setup(function(pinnacle)
local terminal = "alacritty"
process.set_env("MOZ_ENABLE_WAYLAND", "1")
-- Outputs -----------------------------------------------------------------------
-- You can set your own monitor layout as I have done below for my monitors.
@ -35,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

@ -1,5 +1,31 @@
-- SPDX-License-Identifier: GPL-3.0-or-later
---@nodoc TODO: add enum, alias, and type capabilities to ldoc_gen
---@enum MouseButton
local 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,
}
---Input management.
---
---This module provides utilities to set keybinds.
@ -7,6 +33,9 @@
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.).
buttons = buttons,
}
---Set a keybind. If called with an already existing keybind, it gets replaced.
@ -63,4 +92,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,8 +14,11 @@
---@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 }?
---@field Request Request?
--Tags
---@field ToggleTag { tag_id: TagId }?

View file

@ -76,4 +76,24 @@ function process_module.spawn_once(command, callback)
process_module.spawn(command, callback)
end
---Set an environment variable for Pinnacle. All future processes spawned will have this env set.
---
---Note that this will only set the variable for Pinnacle the compositor, not the running Lua config process.
---If you need to set an environment variable for this config, place them in the `metaconfig.toml` file instead.
---
---### Example
---```lua
---process.set_env("MOZ_ENABLE_WAYLAND", "1")
---```
---@param key string
---@param value string
function process_module.set_env(key, value)
SendMsg({
SetEnv = {
key = key,
value = value,
},
})
end
return process_module

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 {
@ -108,6 +125,10 @@ pub enum Msg {
#[serde(default)]
callback_id: Option<CallbackId>,
},
SetEnv {
key: String,
value: String,
},
// Pinnacle management
/// Quit the compositor.
@ -149,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 {
@ -160,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

@ -127,13 +127,19 @@ impl XwmHandler for CalloopData {
self.state.windows.push(window.clone());
// FIXME: this breaks window closing if the popup is focused
self.state.focus_state.set_focus(window.clone());
self.state.apply_window_rules(&window);
if let Some(focused_output) = self.state.focus_state.focused_output.clone() {
self.state.update_windows(&focused_output);
if let Some(output) = window.output(&self.state) {
self.state.update_windows(&output);
}
if let WindowElement::X11(s) = &window {
tracing::debug!("new x11 win geo is {:?}", s.geometry());
}
self.state.loop_handle.insert_idle(move |data| {
data.state
.seat
@ -148,15 +154,12 @@ impl XwmHandler for CalloopData {
}
}
// fn map_window_notify(&mut self, xwm: XwmId, window: X11Surface) {
// //
// }
fn mapped_override_redirect_window(&mut self, _xwm: XwmId, window: X11Surface) {
tracing::debug!("mapped override redirect window");
let win_type = window.window_type();
tracing::debug!("window type is {win_type:?}");
let loc = window.geometry().loc;
tracing::debug!("or win geo is {:?}", window.geometry());
let window = WindowElement::X11(window);
window.with_state(|state| {
state.tags = match (

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,9 +21,8 @@ use smithay::{
keyboard::{keysyms, FilterResult},
pointer::{AxisFrame, ButtonEvent, MotionEvent},
},
reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::ResizeEdge,
utils::{Logical, Point, SERIAL_COUNTER},
wayland::{compositor, seat::WaylandFocus, shell::wlr_layer},
wayland::{seat::WaylandFocus, shell::wlr_layer},
};
use crate::state::State;
@ -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,116 +275,74 @@ 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,
);
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);
if let WindowElement::X11(surface) = &window {
if !surface.is_override_redirect() {
self.xwm
.as_mut()
.expect("no xwm")
.raise_window(surface)
.expect("failed to raise x11 win");
surface
.set_activated(true)
.expect("failed to set x11 win to activated");
}
}
} else {
// Move window to top of stack.
if let FocusTarget::Window(window) = &focus {
self.space.raise_element(window, true);
if let WindowElement::X11(surface) = &window {
if !surface.is_override_redirect() {
self.xwm
.as_mut()
.expect("no xwm")
.raise_window(surface)
.expect("failed to raise x11 win");
surface
.set_activated(true)
.expect("failed to set x11 win to activated");
}
}
}
tracing::debug!("wl_surface focus is some? {}", focus.wl_surface().is_some());
// NOTE: *Do not* set keyboard focus to an override redirect window. This leads
// | to wonky things like right-click menus not correctly getting pointer
// | clicks or showing up at all.
// TODO: use update_keyboard_focus from anvil
if !matches!(&focus, FocusTarget::Window(WindowElement::X11(surf)) if surf.is_override_redirect())
{
keyboard.set_focus(self, Some(focus.clone()), serial);
}
self.space.elements().for_each(|window| {
if let WindowElement::Wayland(window) = window {
window.toplevel().send_configure();
}
});
tracing::debug!("wl_surface focus is some? {}", focus.wl_surface().is_some());
// NOTE: *Do not* set keyboard focus to an override redirect window. This leads
// | to wonky things like right-click menus not correctly getting pointer
// | clicks or showing up at all.
// TODO: use update_keyboard_focus from anvil
if !matches!(&focus, FocusTarget::Window(WindowElement::X11(surf)) if surf.is_override_redirect())
{
keyboard.set_focus(self, Some(focus.clone()), serial);
}
self.space.elements().for_each(|window| {
if let WindowElement::Wayland(window) = window {
window.toplevel().send_configure();
}
});
if let FocusTarget::Window(window) = &focus {
tracing::debug!("setting keyboard focus to {:?}", window.class());
}
if let FocusTarget::Window(window) = &focus {
tracing::debug!("setting keyboard focus to {:?}", window.class());
}
} else {
self.space.elements().for_each(|window| match window {
@ -423,10 +380,14 @@ impl State {
.amount(Axis::Horizontal)
.unwrap_or_else(|| event.amount_discrete(Axis::Horizontal).unwrap_or(0.0) * 3.0);
let vertical_amount = event
let mut vertical_amount = event
.amount(Axis::Vertical)
.unwrap_or_else(|| event.amount_discrete(Axis::Vertical).unwrap_or(0.0) * 3.0);
if self.backend.is_winit() {
vertical_amount = -vertical_amount;
}
let horizontal_amount_discrete = event.amount_discrete(Axis::Horizontal);
let vertical_amount_discrete = event.amount_discrete(Axis::Vertical);

View file

@ -171,12 +171,6 @@ impl State {
.filter(|(_, win)| win.alive())
.all(|(_, win)| win.with_state(|state| state.loc_request_state.is_idle()));
let num_not_idle = pending_wins
.iter()
.filter(|(_, win)| win.alive())
.filter(|(_, win)| !win.with_state(|state| state.loc_request_state.is_idle()))
.count();
all_idle
},
move |dt| {

View file

@ -87,6 +87,14 @@ impl Backend {
Backend::Udev(udev) => udev.early_import(surface),
}
}
/// Returns `true` if the backend is [`Winit`].
///
/// [`Winit`]: Backend::Winit
#[must_use]
pub fn is_winit(&self) -> bool {
matches!(self, Self::Winit(..))
}
}
/// The main state of the application.

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 {
@ -69,6 +81,7 @@ impl State {
} => {
self.handle_spawn(command, callback_id);
}
Msg::SetEnv { key, value } => std::env::set_var(key, value),
Msg::SetWindowSize {
window_id,
@ -145,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 } => {