hypr-dynamic-cursors/src/cursor.cpp

503 lines
19 KiB
C++
Raw Normal View History

2024-07-03 00:38:50 +02:00
#include "config/config.hpp"
2024-07-02 15:35:37 +02:00
#include "mode/Mode.hpp"
2024-06-26 17:14:16 +02:00
#include "src/debug/Log.hpp"
2024-07-21 15:38:46 +02:00
#include "src/helpers/math/Math.hpp"
2024-06-21 14:32:42 +02:00
#include <cmath>
#include <cstdlib>
2024-06-26 17:14:16 +02:00
#include <cstring>
#include <hyprcursor/hyprcursor.hpp>
2024-06-27 17:21:39 +02:00
#include <hyprlang.hpp>
2024-07-21 15:38:46 +02:00
#include <gbm.h>
2024-06-21 14:32:42 +02:00
#define private public
#include <hyprland/src/managers/CursorManager.hpp>
2024-06-21 14:32:42 +02:00
#include <hyprland/src/managers/PointerManager.hpp>
2024-06-21 16:06:55 +02:00
#include <hyprland/src/render/OpenGL.hpp>
#include <hyprland/src/Compositor.hpp>
2024-06-21 14:32:42 +02:00
#undef private
2024-06-21 16:06:55 +02:00
#include <hyprland/src/config/ConfigValue.hpp>
#include <hyprland/src/protocols/core/Compositor.hpp>
#include <hyprland/src/protocols/core/Seat.hpp>
2024-06-21 16:06:55 +02:00
#include "cursor.hpp"
#include "renderer.hpp"
2024-06-21 14:32:42 +02:00
void tickRaw(SP<CEventLoopTimer> self, void* data) {
if (isEnabled())
g_pDynamicCursors->onTick(g_pPointerManager.get());
const int TIMEOUT = g_pHyprRenderer->m_pMostHzMonitor ? 1000.0 / g_pHyprRenderer->m_pMostHzMonitor->refreshRate : 16;
self->updateTimeout(std::chrono::milliseconds(TIMEOUT));
}
CDynamicCursors::CDynamicCursors() {
this->tick = SP<CEventLoopTimer>(new CEventLoopTimer(std::chrono::microseconds(500), tickRaw, nullptr));
g_pEventLoopManager->addTimer(this->tick);
}
CDynamicCursors::~CDynamicCursors() {
// stop and deallocate timer
g_pEventLoopManager->removeTimer(this->tick);
this->tick.reset();
// release software lock
if (zoomSoftware) {
g_pPointerManager->unlockSoftwareAll();
zoomSoftware = false;
}
}
/*
Reimplements rendering of the software cursor.
Is also largely identical to hyprlands impl, but uses our custom rendering to rotate the cursor.
*/
2024-06-21 16:36:10 +02:00
void CDynamicCursors::renderSoftware(CPointerManager* pointers, SP<CMonitor> pMonitor, timespec* now, CRegion& damage, std::optional<Vector2D> overridePos) {
static auto* const* PNEAREST = (Hyprlang::INT* const*) getConfig(CONFIG_HIGHRES_NEAREST);
2024-06-21 14:32:42 +02:00
if (!pointers->hasCursor())
return;
auto state = pointers->stateFor(pMonitor);
2024-07-02 15:35:37 +02:00
auto zoom = resultShown.scale;
2024-06-21 14:32:42 +02:00
if ((!state->hardwareFailed && state->softwareLocks <= 0)) {
if (pointers->currentCursorImage.surface)
pointers->currentCursorImage.surface->resource()->frame(now);
2024-06-21 14:32:42 +02:00
return;
}
auto box = state->box.copy();
if (overridePos.has_value()) {
box.x = overridePos->x;
box.y = overridePos->y;
}
auto texture = pointers->getCurrentCursorTexture();
bool nearest = false;
if (zoom > 1) {
// this first has to undo the hotspot transform from getCursorBoxGlobal
box.x += pointers->currentCursorImage.hotspot.x;
box.y += pointers->currentCursorImage.hotspot.y;
auto high = highres.getTexture();
if (high) {
texture = high;
auto buf = highres.getBuffer();
// we calculate a more accurate hotspot location if we have bigger shapes
box.x -= (buf->hotspot.x / buf->size.x) * pointers->currentCursorImage.size.x * zoom;
box.y -= (buf->hotspot.y / buf->size.y) * pointers->currentCursorImage.size.y * zoom;
// only use nearest-neighbour if magnifying over size
nearest = **PNEAREST == 2 && pointers->currentCursorImage.size.x * zoom > buf->size.x;
} else {
box.x -= pointers->currentCursorImage.hotspot.x * zoom;
box.y -= pointers->currentCursorImage.hotspot.y * zoom;
nearest = **PNEAREST;
}
}
2024-06-21 14:32:42 +02:00
if (!texture)
return;
2024-06-27 17:21:39 +02:00
box.w *= zoom;
box.h *= zoom;
2024-06-21 16:36:10 +02:00
2024-08-25 20:00:16 +02:00
if (box.intersection(CBox{{}, {pMonitor->vecSize}}).empty())
return;
box.scale(pMonitor->scale);
box.x = std::round(box.x);
box.y = std::round(box.y);
2024-06-21 16:36:10 +02:00
// we rotate the cursor by our calculated amount
2024-07-02 15:35:37 +02:00
box.rot = resultShown.rotation;
2024-06-21 14:32:42 +02:00
2024-06-21 16:36:10 +02:00
// now pass the hotspot to rotate around
renderCursorTextureInternalWithDamage(texture, &box, &damage, 1.F, nullptr, 0, pointers->currentCursorImage.hotspot * state->monitor->scale * zoom, nearest, resultShown.stretch.angle, resultShown.stretch.magnitude);
if (pointers->currentCursorImage.surface)
pointers->currentCursorImage.surface->resource()->frame(now);
2024-06-21 14:32:42 +02:00
}
/*
This function implements damaging the screen such that the software cursor is drawn.
It is largely identical to hyprlands implementation, but expands the damage reagion, to accomodate various rotations.
*/
2024-06-21 16:36:10 +02:00
void CDynamicCursors::damageSoftware(CPointerManager* pointers) {
2024-07-03 16:25:02 +02:00
// we damage a padding of the diagonal around the hotspot, to accomodate for all possible hotspots and rotations
2024-07-02 15:35:37 +02:00
auto zoom = resultShown.scale;
2024-06-27 17:21:39 +02:00
Vector2D size = pointers->currentCursorImage.size / pointers->currentCursorImage.scale * zoom;
2024-07-18 08:49:59 +02:00
int diagonal = size.size();
2024-07-03 16:25:02 +02:00
Vector2D padding = {diagonal, diagonal};
CBox b = CBox{pointers->pointerPos, size + (padding * 2)}.translate(-(pointers->currentCursorImage.hotspot * zoom + padding));
2024-06-21 16:36:10 +02:00
static auto PNOHW = CConfigValue<Hyprlang::INT>("cursor:no_hardware_cursors");
for (auto& mw : pointers->monitorStates) {
if (mw->monitor.expired())
continue;
if ((mw->softwareLocks > 0 || mw->hardwareFailed || *PNOHW) && b.overlaps({mw->monitor->vecPosition, mw->monitor->vecSize})) {
g_pHyprRenderer->damageBox(&b, mw->monitor->shouldSkipScheduleFrameOnMouseEvent());
break;
}
}
}
/*
This function reimplements the hardware cursor buffer drawing.
It is largely copied from hyprland, but adjusted to allow the cursor to be rotated.
*/
2024-07-21 15:38:46 +02:00
SP<Aquamarine::IBuffer> CDynamicCursors::renderHardware(CPointerManager* pointers, SP<CPointerManager::SMonitorPointerState> state, SP<CTexture> texture) {
static auto* const* PHW_DEBUG = (Hyprlang::INT* const*) getConfig(CONFIG_HW_DEBUG);
static auto* const* PNEAREST = (Hyprlang::INT* const*) getConfig(CONFIG_HIGHRES_NEAREST);
auto output = state->monitor->output;
2024-07-21 15:38:46 +02:00
auto maxSize = output->cursorPlaneSize();
auto zoom = resultShown.scale;
2024-07-03 16:25:02 +02:00
2024-07-21 15:38:46 +02:00
auto cursorSize = pointers->currentCursorImage.size * zoom;
int cursorDiagonal = cursorSize.size();
auto cursorPadding = Vector2D{cursorDiagonal, cursorDiagonal};
auto targetSize = cursorSize + cursorPadding * 2;
2024-07-21 15:38:46 +02:00
if (maxSize == Vector2D{})
return nullptr;
2024-07-21 15:38:46 +02:00
if (maxSize != Vector2D{-1, -1}) {
if (targetSize.x > maxSize.x || targetSize.y > maxSize.y) {
Debug::log(TRACE, "hardware cursor too big! {} > {}", pointers->currentCursorImage.size, maxSize);
return nullptr;
}
2024-08-25 22:58:55 +02:00
} else {
2024-07-21 15:38:46 +02:00
maxSize = targetSize;
2024-08-25 22:58:55 +02:00
if (maxSize.x < 16 || maxSize.y < 16) maxSize = {16, 16}; // fix some annoying crashes in nest
}
if (!state->monitor->cursorSwapchain || maxSize != state->monitor->cursorSwapchain->currentOptions().size || state->monitor->cursorSwapchain->currentOptions().length != 3) {
2024-07-21 15:38:46 +02:00
if (!state->monitor->cursorSwapchain)
state->monitor->cursorSwapchain = Aquamarine::CSwapchain::create(state->monitor->output->getBackend()->preferredAllocator(), state->monitor->output->getBackend());
2024-07-21 15:38:46 +02:00
auto options = state->monitor->cursorSwapchain->currentOptions();
options.size = maxSize;
// we still have to create a triple buffering swapchain, as we seem to be running into some sort of race condition
// or something. I'll continue debugging this when I find some energy again, I've spent too much time here already.
options.length = 3;
2024-07-21 15:38:46 +02:00
options.scanout = true;
options.cursor = true;
options.multigpu = state->monitor->output->getBackend()->preferredAllocator()->drmFD() != g_pCompositor->m_iDRMFD;
// We do not set the format. If it's unset (DRM_FORMAT_INVALID) then the swapchain will pick for us,
// but if it's set, we don't wanna change it.
2024-07-21 15:38:46 +02:00
if (!state->monitor->cursorSwapchain->reconfigure(options)) {
Debug::log(TRACE, "Failed to reconfigure cursor swapchain");
return nullptr;
}
}
// if we already rendered the cursor, revert the swapchain to avoid rendering the cursor over
// the current front buffer
// this flag will be reset in the preRender hook, so when we commit this buffer to KMS
// see https://github.com/hyprwm/Hyprland/commit/4c3b03516209a49244a8f044143c1162752b8a7a
// this is however still not enough, see above
if (state->cursorRendered)
state->monitor->cursorSwapchain->rollback();
state->cursorRendered = true;
2024-07-21 15:38:46 +02:00
auto buf = state->monitor->cursorSwapchain->next(nullptr);
if (!buf) {
Debug::log(TRACE, "Failed to acquire a buffer from the cursor swapchain");
return nullptr;
}
CRegion damage = {0, 0, INT16_MAX, INT16_MAX};
g_pHyprRenderer->makeEGLCurrent();
2024-10-20 11:57:32 +02:00
g_pHyprOpenGL->m_RenderData.pMonitor = state->monitor;
2024-07-21 15:38:46 +02:00
auto RBO = g_pHyprRenderer->getOrCreateRenderbuffer(buf, state->monitor->cursorSwapchain->currentOptions().format);
if (!RBO) {
// dumb copy won't work with this plugin, as we just copy the buffer, and can't apply transformations to it
Debug::log(TRACE, "Failed to create cursor RB with format {}, mod {}", buf->dmabuf().format, buf->dmabuf().modifier);
static auto PDUMB = CConfigValue<Hyprlang::INT>("cursor:allow_dumb_copy");
if (!*PDUMB)
return nullptr;
auto bufData = buf->beginDataPtr(0);
auto bufPtr = std::get<0>(bufData);
// clear buffer
memset(bufPtr, 0, std::get<2>(bufData));
if (pointers->currentCursorImage.pBuffer) {
auto texAttrs = pointers->currentCursorImage.pBuffer->shm();
2024-07-21 15:38:46 +02:00
if (!texAttrs.success) {
Debug::log(TRACE, "Cannot use dumb copy on dmabuf cursor buffers");
return nullptr;
}
auto texData = pointers->currentCursorImage.pBuffer->beginDataPtr(GBM_BO_TRANSFER_WRITE);
auto texPtr = std::get<0>(texData);
Debug::log(TRACE, "cursor texture {}x{} {} {} {}", texAttrs.size.x, texAttrs.size.y, (void*)texPtr, texAttrs.format, texAttrs.stride);
2024-07-21 15:38:46 +02:00
// copy cursor texture
for (int i = 0; i < texAttrs.size.y; i++)
memcpy(bufPtr + i * buf->dmabuf().strides[0], texPtr + i * texAttrs.stride, texAttrs.stride);
} else if (pointers->currentCursorImage.surface && pointers->currentCursorImage.surface->resource()->role->role() == SURFACE_ROLE_CURSOR) {
const auto SURFACE = pointers->currentCursorImage.surface->resource();
auto& shmBuffer = CCursorSurfaceRole::cursorPixelData(SURFACE);
Debug::log(TRACE, "cursor texture pixel data length: {}B", shmBuffer.size());
if (shmBuffer.data()) {
// copy cursor texture
// assume format is 32bpp
size_t STRIDE = 4 * SURFACE->current.bufferSize.x;
for (int i = 0; i < SURFACE->current.bufferSize.y; i++)
memcpy(bufPtr + i * buf->dmabuf().strides[0], shmBuffer.data() + i * STRIDE, STRIDE);
} else {
// if there is no data, hide the cursor
memset(bufPtr, '\0', buf->size.x * buf->size.y * 4 /* assume 32bpp */);
}
} else {
Debug::log(TRACE, "Unsupported cursor buffer/surface, falling back to sw (can't dumb copy)");
return nullptr;
2024-07-21 15:38:46 +02:00
}
buf->endDataPtr();
return buf;
}
RBO->bind();
2024-10-20 11:57:32 +02:00
g_pHyprOpenGL->beginSimple(state->monitor.lock(), damage, RBO);
if (**PHW_DEBUG)
g_pHyprOpenGL->clear(CColor{rand() / float(RAND_MAX), rand() / float(RAND_MAX), rand() / float(RAND_MAX), 1.F});
else
g_pHyprOpenGL->clear(CColor{0.F, 0.F, 0.F, 0.F});
2024-07-21 15:38:46 +02:00
// the box should start in the middle portion, rotate by our calculated amount
2024-07-21 15:38:46 +02:00
CBox xbox = {cursorPadding, Vector2D{pointers->currentCursorImage.size / pointers->currentCursorImage.scale * state->monitor->scale * zoom}.round()};
2024-07-02 15:35:37 +02:00
xbox.rot = resultShown.rotation;
// use our custom draw function
2024-07-21 15:38:46 +02:00
renderCursorTextureInternalWithDamage(texture, &xbox, &damage, 1.F, pointers->currentCursorImage.waitTimeline, pointers->currentCursorImage.waitPoint, pointers->currentCursorImage.hotspot * state->monitor->scale * zoom, zoom > 1 && **PNEAREST, resultShown.stretch.angle, resultShown.stretch.magnitude);
g_pHyprOpenGL->end();
glFlush();
2024-10-20 11:57:32 +02:00
g_pHyprOpenGL->m_RenderData.pMonitor.reset();
2024-07-21 15:38:46 +02:00
g_pHyprRenderer->onRenderbufferDestroy(RBO.get());
return buf;
}
/*
Implements the hardware cursor setting.
It is also mostly the same as stock hyprland, but with the hotspot translated more into the middle.
*/
2024-07-21 15:38:46 +02:00
bool CDynamicCursors::setHardware(CPointerManager* pointers, SP<CPointerManager::SMonitorPointerState> state, SP<Aquamarine::IBuffer> buf) {
if (!(state->monitor->output->getBackend()->capabilities() & Aquamarine::IBackendImplementation::eBackendCapabilities::AQ_BACKEND_CAPABILITY_POINTER))
return false;
2024-07-21 15:38:46 +02:00
auto PMONITOR = state->monitor.lock();
if (!PMONITOR->cursorSwapchain)
return false;
2024-07-03 16:25:02 +02:00
// we need to transform the hotspot manually as we need to indent it by the padding
2024-07-18 08:49:59 +02:00
int diagonal = pointers->currentCursorImage.size.size();
2024-07-03 16:25:02 +02:00
Vector2D padding = {diagonal, diagonal};
2024-07-21 15:38:46 +02:00
const auto HOTSPOT = CBox{((pointers->currentCursorImage.hotspot * PMONITOR->scale) + padding) * resultShown.scale, {0, 0}}
.transform(wlTransformToHyprutils(invertTransform(PMONITOR->transform)), PMONITOR->cursorSwapchain->currentOptions().size.x, PMONITOR->cursorSwapchain->currentOptions().size.y)
.pos();
Debug::log(TRACE, "[pointer] hw transformed hotspot for {}: {}", state->monitor->szName, HOTSPOT);
2024-07-21 15:38:46 +02:00
if (!state->monitor->output->setCursor(buf, HOTSPOT))
return false;
state->cursorFrontBuffer = buf;
2024-10-20 11:57:32 +02:00
g_pCompositor->scheduleFrameForMonitor(state->monitor.lock(), Aquamarine::IOutput::AQ_SCHEDULE_CURSOR_SHAPE);
return true;
}
/*
Handles cursor move events.
*/
void CDynamicCursors::onCursorMoved(CPointerManager* pointers) {
2024-08-25 22:58:55 +02:00
static auto* const* PSHAKE = (Hyprlang::INT* const*) getConfig(CONFIG_SHAKE);
static auto* const* PIGNORE_WARPS = (Hyprlang::INT* const*) getConfig(CONFIG_IGNORE_WARPS);
if (!pointers->hasCursor())
return;
const auto CURSORBOX = pointers->getCursorBoxGlobal();
bool recalc = false;
for (auto& m : g_pCompositor->m_vMonitors) {
auto state = pointers->stateFor(m);
state->box = pointers->getCursorBoxLogicalForMonitor(state->monitor.lock());
auto CROSSES = !m->logicalBox().intersection(CURSORBOX).empty();
if (!CROSSES && state->cursorFrontBuffer) {
Debug::log(TRACE, "onCursorMoved for output {}: cursor left the viewport, removing it from the backend", m->szName);
pointers->setHWCursorBuffer(state, nullptr);
continue;
} else if (CROSSES && !state->cursorFrontBuffer) {
Debug::log(TRACE, "onCursorMoved for output {}: cursor entered the output, but no front buffer, forcing recalc", m->szName);
recalc = true;
}
if (state->hardwareFailed || !state->entered)
continue;
const auto CURSORPOS = pointers->getCursorPosForMonitor(m);
2024-07-21 15:38:46 +02:00
m->output->moveCursor(CURSORPOS);
2024-06-26 17:14:16 +02:00
}
if (recalc)
pointers->updateCursorBackend();
2024-08-25 22:58:55 +02:00
// ignore warp
if (!isMove && **PIGNORE_WARPS) {
auto mode = this->currentMode();
if (mode) mode->warp(lastPos, pointers->pointerPos);
if (**PSHAKE) shake.warp(lastPos, pointers->pointerPos);
}
calculate(MOVE);
2024-08-25 22:58:55 +02:00
isMove = false;
lastPos = pointers->pointerPos;
2024-06-26 17:14:16 +02:00
}
2024-07-03 00:38:50 +02:00
void CDynamicCursors::setShape(const std::string& shape) {
g_pShapeRuleHandler->activate(shape);
highres.loadShape(shape);
2024-07-03 00:38:50 +02:00
}
void CDynamicCursors::unsetShape() {
g_pShapeRuleHandler->activate("clientside");
highres.loadShape("clientside");
}
void CDynamicCursors::updateTheme() {
highres.update();
2024-07-03 00:38:50 +02:00
}
2024-06-26 18:02:09 +02:00
/*
Handle cursor tick events.
*/
2024-06-26 17:14:16 +02:00
void CDynamicCursors::onTick(CPointerManager* pointers) {
calculate(TICK);
}
IMode* CDynamicCursors::currentMode() {
2024-07-03 00:38:50 +02:00
static auto const* PMODE = (Hyprlang::STRING const*) getConfig(CONFIG_MODE);
auto mode = g_pShapeRuleHandler->getModeOr(*PMODE);
2024-06-26 18:02:09 +02:00
2024-07-03 00:38:50 +02:00
if (mode == "rotate") return &rotate;
else if (mode == "tilt") return &tilt;
else if (mode == "stretch") return &stretch;
else return nullptr;
2024-06-26 17:14:16 +02:00
}
void CDynamicCursors::calculate(EModeUpdate type) {
2024-07-03 00:38:50 +02:00
static auto* const* PTHRESHOLD = (Hyprlang::INT* const*) getConfig(CONFIG_THRESHOLD);
static auto* const* PSHAKE = (Hyprlang::INT* const*) getConfig(CONFIG_SHAKE);
static auto* const* PSHAKE_EFFECTS = (Hyprlang::INT* const*) getConfig(CONFIG_SHAKE_EFFECTS);
2024-06-27 17:21:39 +02:00
IMode* mode = currentMode();
2024-06-26 17:14:16 +02:00
// calculate angle and zoom
if (mode) {
// reset mode if it has changed
if (mode != lastMode) mode->reset();
2024-07-02 15:35:37 +02:00
if (mode->strategy() == type) resultMode = mode->update(g_pPointerManager->pointerPos);
} else resultMode = SModeResult();
2024-06-27 17:21:39 +02:00
lastMode = mode;
if (**PSHAKE) {
2024-07-02 15:35:37 +02:00
if (type == TICK) resultShake = shake.update(g_pPointerManager->pointerPos);
2024-07-02 15:35:37 +02:00
// reset mode results if shaking
if (resultShake > 1 && !**PSHAKE_EFFECTS) resultMode = SModeResult();
} else resultShake = 1;
2024-06-29 15:38:59 +02:00
2024-07-02 15:35:37 +02:00
auto result = resultMode;
result.scale *= resultShake;
2024-06-29 15:38:59 +02:00
2024-07-02 15:35:37 +02:00
if (resultShown.hasDifference(&result, **PTHRESHOLD * (PI / 180.0), 0.01, 0.01)) {
resultShown = result;
resultShown.clamp(**PTHRESHOLD * (PI / 180.0), 0.01, 0.01); // clamp low values so it is rendered pixel-perfectly when no effect
// lock software cursors if zooming
2024-07-02 15:35:37 +02:00
if (resultShown.scale > 1) {
if (!zoomSoftware) {
g_pPointerManager->lockSoftwareAll();
zoomSoftware = true;
}
} else {
if (zoomSoftware) {
// damage so it is cleared properly
g_pPointerManager->damageIfSoftware();
g_pPointerManager->unlockSoftwareAll();
zoomSoftware = false;
}
}
2024-06-26 17:14:16 +02:00
// damage software and change hardware cursor shape
g_pPointerManager->damageIfSoftware();
2024-07-03 00:38:50 +02:00
bool entered = false;
2024-06-26 17:14:16 +02:00
for (auto& m : g_pCompositor->m_vMonitors) {
auto state = g_pPointerManager->stateFor(m);
2024-07-03 00:38:50 +02:00
if (state->entered) entered = true;
2024-06-26 17:14:16 +02:00
if (state->hardwareFailed || !state->entered)
continue;
g_pPointerManager->attemptHardwareCursor(state);
}
2024-07-03 00:38:50 +02:00
// there should always be one monitor entered
// this fixes an issue wheter the cursor shape would not properly update after change
if (!entered) {
Debug::log(LOG, "[dynamic-cursors] updating because none entered");
g_pPointerManager->recheckEnteredOutputs();
g_pPointerManager->updateCursorBackend();
}
2024-06-26 17:14:16 +02:00
}
}
2024-08-25 22:58:55 +02:00
void CDynamicCursors::setMove() {
isMove = true;
}