From 1aa3de035c1c68af801e07459e3126fbe21d60b3 Mon Sep 17 00:00:00 2001 From: Jan Niklas Hasse Date: Sun, 24 Nov 2024 16:45:08 +0100 Subject: [PATCH] Add jngl::hideMouse to hide the mouse cursor using RAII --- src/jngl/input.cpp | 7 ++++++- src/jngl/input.hpp | 4 ++++ src/window.cpp | 15 +++++++++++++++ src/window.hpp | 3 +++ 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/jngl/input.cpp b/src/jngl/input.cpp index 3922fc4d7..12a483907 100644 --- a/src/jngl/input.cpp +++ b/src/jngl/input.cpp @@ -1,4 +1,4 @@ -// Copyright 2012-2021 Jan Niklas Hasse +// Copyright 2012-2024 Jan Niklas Hasse // For conditions of distribution and use, see copyright notice in LICENSE.txt #include "../windowptr.hpp" @@ -53,4 +53,9 @@ std::string getTextInput() { return pWindow->getTextInput(); } +Finally hideMouse() { + pWindow->increaseMouseHiddenCount(); + return Finally([] { pWindow->decreaseMouseHiddenCount(); }); +} + } // namespace jngl diff --git a/src/jngl/input.hpp b/src/jngl/input.hpp index 6fd68ac91..47ff8760f 100644 --- a/src/jngl/input.hpp +++ b/src/jngl/input.hpp @@ -4,6 +4,7 @@ /// @file #pragma once +#include "Finally.hpp" #include "Vec2.hpp" #include @@ -128,6 +129,9 @@ bool getRelativeMouseMode(); /// By default the mouse cursor of the OS is visible and can be hidden by passing false void setMouseVisible(bool visible); +/// Hides the mouse cursor; destroying the returned Finally object will show it again +[[nodiscard]] Finally hideMouse(); + /// Returns whether the mouse cursor of the OS is currently visible /// /// Even when this method returns true, it could still be visible outside of the window or hidden by diff --git a/src/window.cpp b/src/window.cpp index b12a09d00..9a51a5e27 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -136,6 +136,21 @@ bool Window::getRelativeMouseMode() const { return relativeMouseMode; } +void Window::increaseMouseHiddenCount() { + if (mouseHiddenCount == 0) { + setMouseVisible(false); + } + ++mouseHiddenCount; +} + +void Window::decreaseMouseHiddenCount() { + assert(mouseHiddenCount > 0); + --mouseHiddenCount; + if (mouseHiddenCount == 0) { + setMouseVisible(true); + } +} + int Window::getCanvasWidth() const { return canvasWidth; } diff --git a/src/window.hpp b/src/window.hpp index ed91e1ee2..53b3e419b 100644 --- a/src/window.hpp +++ b/src/window.hpp @@ -48,6 +48,8 @@ class Window { void SetRelativeMouseMode(bool relative); bool getRelativeMouseMode() const; void SetMouseVisible(bool visible); + void increaseMouseHiddenCount(); + void decreaseMouseHiddenCount(); bool getMouseVisible() const; bool isMultitouch() const; std::vector getTouchPositions() const; @@ -177,6 +179,7 @@ class Window { unsigned int previousStepsPerFrame = 1; double lastCheckTime; unsigned int stepsSinceLastCheck; + int mouseHiddenCount = 0; /// When VSYNC is active we will try to find out to what FPS/Hz the display is limiting us double maxFPS;