Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
build/
__pycache__/
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ hl.plugin.hyprbars.add_button({

The replacement contains only `0x` and hexadecimal digits; no window title or other application-controlled text enters the command.

## Drag events

A titlebar drag holds the pointer button, so Hyprland's own binds never see the press or release. The plugin reports each titlebar move on socket2 instead, as custom events:

```
custom>>hyprbars:dragstart
custom>>hyprbars:dragend
```

`dragstart` comes once the pointer moves with the button held, and `dragend` when it is let go. A click on the titlebar, a button press, and a resize from the edge above the titlebar send nothing. A tool listening on socket2 can then act on where a window was dropped, for example by snapping it into a layout at a screen edge.

## Hyprland ABI

A Hyprland plugin is only compatible with the exact Hyprland build whose headers it was compiled against, and Hyprland refuses to load a mismatched build. The package in omarchy-pkgs is rebuilt whenever `hyprland` changes, and the same automated bump moves its `hyprland=` dependency to the version it was rebuilt against, so the package always demands the Hyprland it loads into.
Expand Down
43 changes: 41 additions & 2 deletions barDeco.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <hyprland/src/animation/AnimationManager.hpp>
#include <hyprland/src/protocols/LayerShell.hpp>
#include <hyprland/src/event/EventBus.hpp>
#include <hyprland/src/ipc/s2/S2.hpp>
#include <hyprland/src/layout/LayoutManager.hpp>
#include <hyprland/src/render/OpenGL.hpp>
#include <hyprland/src/state/MonitorState.hpp>
Expand All @@ -29,6 +30,17 @@
#include <hyprland/src/managers/fullscreen/FullscreenController.hpp>
#include "appName.hpp"

// A titlebar drag holds the pointer button, so the press and release never
// reach Hyprland's binds and nothing outside the plugin can tell a window is
// being moved. Report the start and end of each move on socket2, as custom
// events, so tools can act on a window dropped somewhere, such as snapping it
// into a layout when it reaches a screen edge. Top-edge resizes don't count.
static void postDragEvent(const char *name) {
// The socket is gone while Hyprland shuts down and destroys the bars.
if (const auto &socket = IPC::Socket2::sock())
socket->postEvent({.event = "custom", .data = name});
}

#include <algorithm>
#include <climits>

Expand Down Expand Up @@ -70,7 +82,11 @@ COmarchyFloatingHyprBar::COmarchyFloatingHyprBar(PHLWINDOW pWindow) : IHyprWindo
m_cRealBarColor->setUpdateCallback([&](auto) { damageEntire(); });
}

COmarchyFloatingHyprBar::~COmarchyFloatingHyprBar() { std::erase(g_pOmarchyFloatingGlobalState->bars, m_self); }
COmarchyFloatingHyprBar::~COmarchyFloatingHyprBar() {
// A window closed mid-drag never sees the release, so end its move here.
endMoveEvent();
std::erase(g_pOmarchyFloatingGlobalState->bars, m_self);
}

SDecorationPositioningInfo COmarchyFloatingHyprBar::getPositioningInfo() {
const auto HEIGHT = g_pOmarchyFloatingGlobalState->config.barHeight->value();
Expand Down Expand Up @@ -190,6 +206,7 @@ void COmarchyFloatingHyprBar::onTouchMove(Event::SCallbackInfo &info, ITouch::SM

g_layoutManager->beginDragTarget(m_pWindow.lock()->layoutTarget(), MBIND_MOVE);
m_bDraggingThis = true;
startMoveEvent();
}
}

Expand Down Expand Up @@ -237,6 +254,8 @@ void COmarchyFloatingHyprBar::handleDownEvent(Event::SCallbackInfo &info, std::o
LOG(Log::DEBUG, "[hyprbars] Dragging ended on {:x}", (uintptr_t)PWINDOW.get());
}

endMoveEvent();

m_bDraggingThis = false;
m_bDragPending = false;
m_bTouchEv = false;
Expand Down Expand Up @@ -295,8 +314,12 @@ bool COmarchyFloatingHyprBar::startTopEdgeResize(Event::SCallbackInfo &info, PHL
}

void COmarchyFloatingHyprBar::handleUpEvent(Event::SCallbackInfo &info) {
if (m_pWindow.lock() != Desktop::focusState()->window())
if (m_pWindow.lock() != Desktop::focusState()->window()) {
// Another window took focus during the drag. Still end a reported move,
// so every dragstart gets its dragend.
endMoveEvent();
return;
}

if (m_bCancelledDown)
info.cancelled = true;
Expand All @@ -312,6 +335,7 @@ void COmarchyFloatingHyprBar::handleUpEvent(Event::SCallbackInfo &info) {
LOG(Log::DEBUG, "[hyprbars] Dragging ended on {:x}", (uintptr_t)m_pWindow.lock().get());
}

endMoveEvent();
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
m_bDragPending = false;
m_bTouchEv = false;
m_touchId = 0;
Expand All @@ -338,9 +362,24 @@ void COmarchyFloatingHyprBar::handleMovement() {
g_layoutManager->beginDragTarget(window->layoutTarget(), MBIND_MOVE);
m_bDraggingThis = true;
LOG(Log::DEBUG, "[hyprbars] Dragging initiated on {:x}", (uintptr_t)m_pWindow.lock().get());
startMoveEvent();
return;
}

void COmarchyFloatingHyprBar::startMoveEvent() {
if (m_bMoveReported)
return;
m_bMoveReported = true;
postDragEvent("hyprbars:dragstart");
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
}

void COmarchyFloatingHyprBar::endMoveEvent() {
if (!m_bMoveReported)
return;
m_bMoveReported = false;
postDragEvent("hyprbars:dragend");
}

bool COmarchyFloatingHyprBar::doButtonPress(Config::INTEGER barPadding, Config::INTEGER barButtonPadding, Config::INTEGER barHeight, Vector2D COORDS,
const bool BUTTONSRIGHT) {
// check if on a button
Expand Down
3 changes: 3 additions & 0 deletions barDeco.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ class COmarchyFloatingHyprBar : public IHyprWindowDecoration {
void handleUpEvent(Event::SCallbackInfo &info);
bool startTopEdgeResize(Event::SCallbackInfo &info, PHLWINDOW window, const Vector2D &coords);
void handleMovement();
void startMoveEvent();
void endMoveEvent();
bool doButtonPress(Config::INTEGER barPadding, Config::INTEGER barButtonPadding, Config::INTEGER barHeight, Vector2D COORDS, bool BUTTONSRIGHT);

CBox assignedBoxGlobal();
Expand All @@ -110,6 +112,7 @@ class COmarchyFloatingHyprBar : public IHyprWindowDecoration {
bool m_bTouchEv = false;
bool m_bDragPending = false;
bool m_bCancelledDown = false;
bool m_bMoveReported = false;
int m_touchId = 0;

// store hover state for buttons as a bitfield
Expand Down
115 changes: 115 additions & 0 deletions tools/verify.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
import json
import os
from pathlib import Path
import socket
import subprocess
import tempfile
import threading
import time

source = Path(__file__).resolve().parent
Expand Down Expand Up @@ -84,6 +86,68 @@ def drag_to(x, y):
pointer(commands)
return client()

def pointer_in_background(commands):
helper = subprocess.Popen([str(scratch / 'pointer'), '1280', '800'], stdin=subprocess.PIPE, text=True, env=env)
helper.stdin.write('\n'.join(commands) + '\n')
helper.stdin.close()
return helper

def titlebar_press(window):
# Press on the titlebar and move a little, so the plugin starts a drag.
x, y = window['at'][0] + min(window['size'][0] // 2, 220), window['at'][1] - 15
commands = [f'move {x} {y}', 'wait 100', 'down', 'wait 120']
for i in range(1, 6):
commands += [f'move {x + 4 * i} {y + 4 * i}', 'wait 20']
return commands

def open_window(app_id):
known = {window['address'] for window in json.loads(ctl('clients', '-j'))}
process = subprocess.Popen(['foot', f'--app-id={app_id}', f'--title={app_id}', 'sleep', '90'], env=env, stdout=log, stderr=log)
for _ in range(60):
new = [window for window in json.loads(ctl('clients', '-j')) if window['address'] not in known]
if new:
return process, new[0]
time.sleep(.1)
raise RuntimeError(f'{app_id} did not map')

drag_events = []
drag_events_changed = threading.Condition()
drag_reader_error = []

def listen_for_drag_events(events):
try:
buffer = b''
while True:
chunk = events.recv(4096)
if not chunk:
raise RuntimeError('socket2 closed while recording drag events')
buffer += chunk
*lines, buffer = buffer.split(b'\n')
with drag_events_changed:
drag_events.extend(line.decode() for line in lines if line.startswith(b'custom>>hyprbars:drag'))
drag_events_changed.notify_all()
except Exception as error:
with drag_events_changed:
drag_reader_error.append(error)
drag_events_changed.notify_all()

def expect_drag_events(*expected, timeout=3, settle=.3):
# Wait until the reader has seen as many events as expected, then a little
# longer so an extra event would show up, and compare.
deadline = time.monotonic() + timeout
with drag_events_changed:
while len(drag_events) < len(expected) and not drag_reader_error and time.monotonic() < deadline:
drag_events_changed.wait(deadline - time.monotonic())
time.sleep(settle)
with drag_events_changed:
if drag_reader_error:
raise RuntimeError('drag event reader failed') from drag_reader_error[0]
seen = list(drag_events)
drag_events.clear()
assert seen == [f'custom>>hyprbars:{name}' for name in expected], seen

DRAG = ('dragstart', 'dragend')

def capture(name):
monitor = json.loads(ctl('monitors', '-j'))[0]['name']
subprocess.run(['grim', '-o', monitor, str(args.artifacts / f'{name}.png')], env=env, check=True)
Expand Down Expand Up @@ -153,6 +217,11 @@ def capture(name):
assert not ctl('configerrors').strip(), ctl('configerrors')
capture('floating')

# Record the plugin's socket2 drag events for the checks below.
events = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
events.connect(str(scratch / 'hypr' / env['HYPRLAND_INSTANCE_SIGNATURE'] / '.socket2.sock'))
threading.Thread(target=listen_for_drag_events, args=(events,), daemon=True).start()

# Omarchy draws the border around the titlebar too. Hyprland measures its
# resize band from the window's content, which puts the top of that band
# under the titlebar, so the titlebar has to start a resize from the band
Expand All @@ -173,6 +242,8 @@ def capture(name):
assert after['at'][1] + after['size'][1] == before['at'][1] + before['size'][1], (before, after)
capture('top-edge-resized')
print('PASS: dragging just above the titlebar resizes the window from its top edge', flush=True)
expect_drag_events()
print('PASS: a top-edge resize sends no drag events', flush=True)
ctl('eval', 'hl.config({ plugin = { hyprbars = { bar_precedence_over_border = false } } })')
ctl('dispatch', f'hl.dsp.window.resize({{ x = {before["size"][0]}, y = {before["size"][1]} }})')
ctl('dispatch', 'hl.dsp.window.center()')
Expand All @@ -185,13 +256,57 @@ def capture(name):
top = drag_to(650, 1)
assert top['size'] == original['size'] and top['fullscreen'] == 0, top
print('PASS: real pointer titlebar drags move the window to any edge without snapping', flush=True)
expect_drag_events(*DRAG, *DRAG)
print('PASS: each titlebar drag reports one dragstart and one dragend on socket2', flush=True)

# A window closed while its titlebar is held never sees the release.
doomed, doomed_window = open_window('omarchy-titlebars-closed-mid-drag')
ctl('dispatch', f'hl.dsp.window.move({{ x = 100, y = 100, window = "address:{doomed_window["address"]}" }})')
time.sleep(.3)
doomed_window = next(window for window in json.loads(ctl('clients', '-j')) if window['address'] == doomed_window['address'])
helper = pointer_in_background(titlebar_press(doomed_window) + ['wait 1200', 'up'])
time.sleep(.8)
ctl('dispatch', f'hl.dsp.window.close({{ window = "address:{doomed_window["address"]}" }})')
helper.wait(timeout=10)
doomed.wait(timeout=5)
expect_drag_events(*DRAG)
print('PASS: closing a window mid-drag still reports dragend', flush=True)

# Focus moving to another window mid-drag must not lose the dragend, and
# the next drag must report a fresh dragstart.
other, other_window = open_window('omarchy-titlebars-focus-mid-drag')
ctl('dispatch', f'hl.dsp.window.move({{ x = 700, y = 420, window = "address:{other_window["address"]}" }})')
ctl('dispatch', f'hl.dsp.focus({{ window = "address:{original["address"]}" }})')
time.sleep(.3)
held = next(window for window in json.loads(ctl('clients', '-j')) if window['address'] == original['address'])
helper = pointer_in_background(titlebar_press(held) + ['wait 1200', 'up'])
time.sleep(.8)
ctl('dispatch', f'hl.dsp.focus({{ window = "address:{other_window["address"]}" }})')
helper.wait(timeout=10)
expect_drag_events(*DRAG)
other.terminate()
other.wait(timeout=5)
for _ in range(30):
if len(json.loads(ctl('clients', '-j'))) == 1:
break
time.sleep(.1)
ctl('dispatch', f'hl.dsp.focus({{ window = "address:{original["address"]}" }})')
ctl('dispatch', 'hl.dsp.window.center()')
time.sleep(.3)
drag_to(650, 220)
expect_drag_events(*DRAG)
ctl('dispatch', 'hl.dsp.window.center()')
time.sleep(.3)
print('PASS: a focus change mid-drag still reports dragend, and the next drag starts fresh', flush=True)

window = client()
x, y = window['at'][0] + 120, window['at'][1] - 15
pointer([f'move {x} {y}', 'wait 450', 'down', 'up', 'wait 100', 'down', 'up'])
assert client()['fullscreen'] == 1, client()
capture('maximized')
print('PASS: titlebar double-click maximize', flush=True)
expect_drag_events()
print('PASS: titlebar clicks send no drag events', flush=True)
restored = drag_to(650, 220)
assert restored['fullscreen'] == 0 and restored['size'] == original['size'], restored
print('PASS: dragging a maximized titlebar restores its size under the pointer', flush=True)
Expand Down