diff --git a/hyprctl/main.cpp b/hyprctl/main.cpp index daf8d4a84..b15d3e218 100644 --- a/hyprctl/main.cpp +++ b/hyprctl/main.cpp @@ -26,7 +26,9 @@ #include #include #include +#include using namespace Hyprutils::String; +using namespace Hyprutils::Memory; #include "Strings.hpp" @@ -206,7 +208,7 @@ int request(std::string_view arg, int minArgs = 0, bool needRoll = false) { strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); - if (connect(SERVERSOCKET, (sockaddr*)&serverAddress, SUN_LEN(&serverAddress)) < 0) { + if (connect(SERVERSOCKET, rc(&serverAddress), SUN_LEN(&serverAddress)) < 0) { log("Couldn't connect to " + socketPath + ". (4)"); return 4; } @@ -272,7 +274,7 @@ int requestIPC(std::string_view filename, std::string_view arg) { strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); - if (connect(SERVERSOCKET, (sockaddr*)&serverAddress, SUN_LEN(&serverAddress)) < 0) { + if (connect(SERVERSOCKET, rc(&serverAddress), SUN_LEN(&serverAddress)) < 0) { log("Couldn't connect to " + socketPath + ". (3)"); return 3; } @@ -475,7 +477,7 @@ int main(int argc, char** argv) { const auto INSTANCES = instances(); - if (INSTANCENO < 0 || static_cast(INSTANCENO) >= INSTANCES.size()) { + if (INSTANCENO < 0 || sc(INSTANCENO) >= INSTANCES.size()) { log("no such instance\n"); return 1; } diff --git a/hyprpm/src/core/HyprlandSocket.cpp b/hyprpm/src/core/HyprlandSocket.cpp index 50b3558c6..47142e549 100644 --- a/hyprpm/src/core/HyprlandSocket.cpp +++ b/hyprpm/src/core/HyprlandSocket.cpp @@ -6,6 +6,9 @@ #include #include #include +#include + +using namespace Hyprutils::Memory; static int getUID() { const auto UID = getuid(); @@ -46,7 +49,7 @@ std::string NHyprlandSocket::send(const std::string& cmd) { strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); - if (connect(SERVERSOCKET, (sockaddr*)&serverAddress, SUN_LEN(&serverAddress)) < 0) { + if (connect(SERVERSOCKET, rc(&serverAddress), SUN_LEN(&serverAddress)) < 0) { std::println("{}", failureString("Couldn't connect to " + socketPath + ". (4)")); return ""; } diff --git a/hyprpm/src/core/PluginManager.cpp b/hyprpm/src/core/PluginManager.cpp index a1f1b4572..9dea8bf40 100644 --- a/hyprpm/src/core/PluginManager.cpp +++ b/hyprpm/src/core/PluginManager.cpp @@ -26,8 +26,10 @@ #include #include +#include using namespace Hyprutils::String; using namespace Hyprutils::OS; +using namespace Hyprutils::Memory; static std::string execAndGet(std::string cmd) { cmd += " 2>&1"; @@ -599,7 +601,7 @@ bool CPluginManager::updateHeaders(bool force) { std::print("\n"); } else { - progress.printMessageAbove(failureString("failed to install headers with error code {} ({})", (int)HEADERSVALID, headerErrorShort(HEADERSVALID))); + progress.printMessageAbove(failureString("failed to install headers with error code {} ({})", sc(HEADERSVALID), headerErrorShort(HEADERSVALID))); progress.printMessageAbove(infoString("if the problem persists, try running hyprpm purge-cache.")); progress.m_iSteps = 5; progress.m_szCurrentMessage = "Failed"; @@ -945,7 +947,7 @@ void CPluginManager::listAllPlugins() { } void CPluginManager::notify(const eNotifyIcons icon, uint32_t color, int durationMs, const std::string& message) { - NHyprlandSocket::send("/notify " + std::to_string((int)icon) + " " + std::to_string(durationMs) + " " + std::to_string(color) + " " + message); + NHyprlandSocket::send("/notify " + std::to_string(icon) + " " + std::to_string(durationMs) + " " + std::to_string(color) + " " + message); } std::string CPluginManager::headerError(const eHeadersErrors err) { diff --git a/hyprpm/src/progress/CProgressBar.cpp b/hyprpm/src/progress/CProgressBar.cpp index 819a3f4fb..19a14d9c6 100644 --- a/hyprpm/src/progress/CProgressBar.cpp +++ b/hyprpm/src/progress/CProgressBar.cpp @@ -9,9 +9,11 @@ #include #include - +#include #include "../helpers/Colors.hpp" +using namespace Hyprutils::Memory; + static winsize getTerminalSize() { winsize w{}; ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); @@ -44,7 +46,7 @@ void CProgressBar::print() { percentDone = m_fPercentage; else { // check for divide-by-zero - percentDone = m_iMaxSteps > 0 ? static_cast(m_iSteps) / m_iMaxSteps : 0.0f; + percentDone = m_iMaxSteps > 0 ? sc(m_iSteps) / m_iMaxSteps : 0.0f; } // clamp to ensure no overflows (sanity check) percentDone = std::clamp(percentDone, 0.0f, 1.0f); @@ -54,7 +56,7 @@ void CProgressBar::print() { std::ostringstream oss; oss << ' ' << Colors::GREEN; - size_t filled = static_cast(std::floor(percentDone * BARWIDTH)); + size_t filled = std::floor(percentDone * BARWIDTH); size_t i = 0; for (; i < filled; ++i) @@ -69,7 +71,7 @@ void CProgressBar::print() { oss << Colors::RESET; if (m_fPercentage >= 0.0f) - oss << " " << std::format("{}%", static_cast(percentDone * 100.0)) << ' '; + oss << " " << std::format("{}%", sc(percentDone * 100.0)) << ' '; else oss << " " << std::format("{} / {}", m_iSteps, m_iMaxSteps) << ' '; diff --git a/hyprtester/plugin/src/main.cpp b/hyprtester/plugin/src/main.cpp index 01ec7b385..7eeb2eea0 100644 --- a/hyprtester/plugin/src/main.cpp +++ b/hyprtester/plugin/src/main.cpp @@ -72,7 +72,7 @@ class CTestKeyboard : public IKeyboard { void sendKey(uint32_t key, bool pressed) { auto event = IKeyboard::SKeyEvent{ - .timeMs = static_cast(Time::millis(Time::steadyNow())), + .timeMs = sc(Time::millis(Time::steadyNow())), .keycode = key, .state = pressed ? WL_KEYBOARD_KEY_STATE_PRESSED : WL_KEYBOARD_KEY_STATE_RELEASED, }; diff --git a/hyprtester/src/hyprctlCompat.cpp b/hyprtester/src/hyprctlCompat.cpp index 6e6cfc0f6..2c8e06449 100644 --- a/hyprtester/src/hyprctlCompat.cpp +++ b/hyprtester/src/hyprctlCompat.cpp @@ -14,6 +14,8 @@ #include #include #include +#include +using namespace Hyprutils::Memory; static int getUID() { const auto UID = getuid(); @@ -95,7 +97,7 @@ std::string getFromSocket(const std::string& cmd) { strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); - if (connect(SERVERSOCKET, (sockaddr*)&serverAddress, SUN_LEN(&serverAddress)) < 0) { + if (connect(SERVERSOCKET, rc(&serverAddress), SUN_LEN(&serverAddress)) < 0) { std::println("Couldn't connect to {}. (3)", socketPath); return ""; } diff --git a/src/Compositor.cpp b/src/Compositor.cpp index 3b8fb0a5d..8f9a64ec0 100644 --- a/src/Compositor.cpp +++ b/src/Compositor.cpp @@ -1058,7 +1058,7 @@ Vector2D CCompositor::vectorToSurfaceLocal(const Vector2D& vec, PHLWINDOW pWindo pWindow->m_wlSurface->resource()->breadthfirst( [](SP surf, const Vector2D& offset, void* data) { - const auto PDATA = (std::tuple, Vector2D>*)data; + const auto PDATA = sc, Vector2D>*>(data); if (surf == std::get<0>(*PDATA)) std::get<1>(*PDATA) = offset; }, @@ -1133,7 +1133,7 @@ void CCompositor::focusWindow(PHLWINDOW pWindow, SP pSurface g_pEventManager->postEvent(SHyprIPCEvent{"activewindow", ","}); g_pEventManager->postEvent(SHyprIPCEvent{"activewindowv2", ""}); - EMIT_HOOK_EVENT("activeWindow", (PHLWINDOW) nullptr); + EMIT_HOOK_EVENT("activeWindow", PHLWINDOW{nullptr}); g_pLayoutManager->getCurrentLayout()->onWindowFocusChange(nullptr); @@ -1206,7 +1206,7 @@ void CCompositor::focusWindow(PHLWINDOW pWindow, SP pSurface // Send an event g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindow", .data = pWindow->m_class + "," + pWindow->m_title}); - g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindowv2", .data = std::format("{:x}", (uintptr_t)pWindow.get())}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindowv2", .data = std::format("{:x}", rc(pWindow.get()))}); EMIT_HOOK_EVENT("activeWindow", pWindow); @@ -1239,7 +1239,7 @@ void CCompositor::focusSurface(SP pSurface, PHLWINDOW pWindo return; if (g_pSeatManager->m_seatGrab && !g_pSeatManager->m_seatGrab->accepts(pSurface)) { - Debug::log(LOG, "surface {:x} won't receive kb focus because grab rejected it", (uintptr_t)pSurface.get()); + Debug::log(LOG, "surface {:x} won't receive kb focus because grab rejected it", rc(pSurface.get())); return; } @@ -1253,7 +1253,7 @@ void CCompositor::focusSurface(SP pSurface, PHLWINDOW pWindo g_pSeatManager->setKeyboardFocus(nullptr); g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindow", .data = ","}); g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindowv2", .data = ""}); - EMIT_HOOK_EVENT("keyboardFocus", (SP)nullptr); + EMIT_HOOK_EVENT("keyboardFocus", SP{nullptr}); m_lastFocus.reset(); return; } @@ -1262,9 +1262,9 @@ void CCompositor::focusSurface(SP pSurface, PHLWINDOW pWindo g_pSeatManager->setKeyboardFocus(pSurface); if (pWindowOwner) - Debug::log(LOG, "Set keyboard focus to surface {:x}, with {}", (uintptr_t)pSurface.get(), pWindowOwner); + Debug::log(LOG, "Set keyboard focus to surface {:x}, with {}", rc(pSurface.get()), pWindowOwner); else - Debug::log(LOG, "Set keyboard focus to surface {:x}", (uintptr_t)pSurface.get()); + Debug::log(LOG, "Set keyboard focus to surface {:x}", rc(pSurface.get())); g_pXWaylandManager->activateSurface(pSurface, true); m_lastFocus = pSurface; @@ -1334,7 +1334,7 @@ PHLWINDOW CCompositor::getWindowFromSurface(SP pSurface) { PHLWINDOW CCompositor::getWindowFromHandle(uint32_t handle) { for (auto const& w : m_windows) { - if ((uint32_t)(((uint64_t)w.get()) & 0xFFFFFFFF) == handle) { + if (sc(rc(w.get()) & 0xFFFFFFFF) == handle) { return w; } } @@ -1868,14 +1868,14 @@ void CCompositor::updateWindowAnimatedDecorationValues(PHLWINDOW pWindow) { static auto PDIMSTRENGTH = CConfigValue("decoration:dim_strength"); static auto PDIMENABLED = CConfigValue("decoration:dim_inactive"); - auto* const ACTIVECOL = (CGradientValueData*)(PACTIVECOL.ptr())->getData(); - auto* const INACTIVECOL = (CGradientValueData*)(PINACTIVECOL.ptr())->getData(); - auto* const NOGROUPACTIVECOL = (CGradientValueData*)(PNOGROUPACTIVECOL.ptr())->getData(); - auto* const NOGROUPINACTIVECOL = (CGradientValueData*)(PNOGROUPINACTIVECOL.ptr())->getData(); - auto* const GROUPACTIVECOL = (CGradientValueData*)(PGROUPACTIVECOL.ptr())->getData(); - auto* const GROUPINACTIVECOL = (CGradientValueData*)(PGROUPINACTIVECOL.ptr())->getData(); - auto* const GROUPACTIVELOCKEDCOL = (CGradientValueData*)(PGROUPACTIVELOCKEDCOL.ptr())->getData(); - auto* const GROUPINACTIVELOCKEDCOL = (CGradientValueData*)(PGROUPINACTIVELOCKEDCOL.ptr())->getData(); + auto* const ACTIVECOL = sc((PACTIVECOL.ptr())->getData()); + auto* const INACTIVECOL = sc((PINACTIVECOL.ptr())->getData()); + auto* const NOGROUPACTIVECOL = sc((PNOGROUPACTIVECOL.ptr())->getData()); + auto* const NOGROUPINACTIVECOL = sc((PNOGROUPINACTIVECOL.ptr())->getData()); + auto* const GROUPACTIVECOL = sc((PGROUPACTIVECOL.ptr())->getData()); + auto* const GROUPINACTIVECOL = sc((PGROUPINACTIVECOL.ptr())->getData()); + auto* const GROUPACTIVELOCKEDCOL = sc((PGROUPACTIVELOCKEDCOL.ptr())->getData()); + auto* const GROUPINACTIVELOCKEDCOL = sc((PGROUPINACTIVELOCKEDCOL.ptr())->getData()); auto setBorderColor = [&](CGradientValueData grad) -> void { if (grad == pWindow->m_realBorderColor) @@ -2070,7 +2070,7 @@ PHLMONITOR CCompositor::getMonitorFromString(const std::string& name) { offsetLeft = offsetLeft < 0 ? -((-offsetLeft) % m_monitors.size()) : offsetLeft % m_monitors.size(); int currentPlace = 0; - for (int i = 0; i < (int)m_monitors.size(); i++) { + for (int i = 0; i < sc(m_monitors.size()); i++) { if (m_monitors[i] == m_lastMonitor) { currentPlace = i; break; @@ -2085,9 +2085,9 @@ PHLMONITOR CCompositor::getMonitorFromString(const std::string& name) { currentPlace = currentPlace % m_monitors.size(); } - if (currentPlace != std::clamp(currentPlace, 0, (int)m_monitors.size() - 1)) { + if (currentPlace != std::clamp(currentPlace, 0, sc(m_monitors.size()) - 1)) { Debug::log(WARN, "Error in getMonitorFromString: Vaxry's code sucks."); - currentPlace = std::clamp(currentPlace, 0, (int)m_monitors.size() - 1); + currentPlace = std::clamp(currentPlace, 0, sc(m_monitors.size()) - 1); } return m_monitors[currentPlace]; @@ -2102,7 +2102,7 @@ PHLMONITOR CCompositor::getMonitorFromString(const std::string& name) { return nullptr; } - if (monID > -1 && monID < (MONITORID)m_monitors.size()) { + if (monID > -1 && monID < sc(m_monitors.size())) { return getMonitorFromID(monID); } else { Debug::log(ERR, "Error in getMonitorFromString: invalid arg 1"); @@ -2194,8 +2194,8 @@ void CCompositor::moveWorkspaceToMonitor(PHLWORKSPACE pWorkspace, PHLMONITOR pMo } } else *w->m_realPosition = Vector2D{ - (pMonitor->m_size.x != 0) ? (int)w->m_realPosition->goal().x % (int)pMonitor->m_size.x : 0, - (pMonitor->m_size.y != 0) ? (int)w->m_realPosition->goal().y % (int)pMonitor->m_size.y : 0, + (pMonitor->m_size.x != 0) ? sc(w->m_realPosition->goal().x) % sc(pMonitor->m_size.x) : 0, + (pMonitor->m_size.y != 0) ? sc(w->m_realPosition->goal().y) % sc(pMonitor->m_size.y) : 0, }; } @@ -2297,8 +2297,9 @@ void CCompositor::updateFullscreenFadeOnWorkspace(PHLWORKSPACE pWorkspace) { } void CCompositor::changeWindowFullscreenModeClient(const PHLWINDOW PWINDOW, const eFullscreenMode MODE, const bool ON) { - setWindowFullscreenClient(PWINDOW, - (eFullscreenMode)(ON ? (uint8_t)PWINDOW->m_fullscreenState.client | (uint8_t)MODE : ((uint8_t)PWINDOW->m_fullscreenState.client & (uint8_t)~MODE))); + setWindowFullscreenClient( + PWINDOW, + sc(ON ? sc(PWINDOW->m_fullscreenState.client) | sc(MODE) : (sc(PWINDOW->m_fullscreenState.client) & sc(~MODE)))); } void CCompositor::setWindowFullscreenInternal(const PHLWINDOW PWINDOW, const eFullscreenMode MODE) { @@ -2322,14 +2323,14 @@ void CCompositor::setWindowFullscreenState(const PHLWINDOW PWINDOW, SFullscreenS if (!validMapped(PWINDOW) || g_pCompositor->m_unsafeState) return; - state.internal = std::clamp(state.internal, (eFullscreenMode)0, FSMODE_MAX); - state.client = std::clamp(state.client, (eFullscreenMode)0, FSMODE_MAX); + state.internal = std::clamp(state.internal, sc(0), FSMODE_MAX); + state.client = std::clamp(state.client, sc(0), FSMODE_MAX); const auto PMONITOR = PWINDOW->m_monitor.lock(); const auto PWORKSPACE = PWINDOW->m_workspace; - const eFullscreenMode CURRENT_EFFECTIVE_MODE = (eFullscreenMode)std::bit_floor((uint8_t)PWINDOW->m_fullscreenState.internal); - const eFullscreenMode EFFECTIVE_MODE = (eFullscreenMode)std::bit_floor((uint8_t)state.internal); + const eFullscreenMode CURRENT_EFFECTIVE_MODE = sc(std::bit_floor(sc(PWINDOW->m_fullscreenState.internal))); + const eFullscreenMode EFFECTIVE_MODE = sc(std::bit_floor(sc(state.internal))); if (PWINDOW->m_isFloating && CURRENT_EFFECTIVE_MODE == FSMODE_NONE && EFFECTIVE_MODE != FSMODE_NONE) g_pHyprRenderer->damageWindow(PWINDOW); @@ -2369,7 +2370,7 @@ void CCompositor::setWindowFullscreenState(const PHLWINDOW PWINDOW, SFullscreenS PWORKSPACE->m_fullscreenMode = EFFECTIVE_MODE; PWORKSPACE->m_hasFullscreenWindow = EFFECTIVE_MODE != FSMODE_NONE; - g_pEventManager->postEvent(SHyprIPCEvent{.event = "fullscreen", .data = std::to_string((int)EFFECTIVE_MODE != FSMODE_NONE)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "fullscreen", .data = std::to_string(sc(EFFECTIVE_MODE) != FSMODE_NONE)}); EMIT_HOOK_EVENT("fullscreen", PWINDOW); PWINDOW->updateDynamicRules(); @@ -2520,7 +2521,7 @@ PHLWINDOW CCompositor::getWindowByRegex(const std::string& regexp_) { break; } case MODE_ADDRESS: { - std::string addr = std::format("0x{:x}", (uintptr_t)w.get()); + std::string addr = std::format("0x{:x}", rc(w.get())); if (matchCheck != addr) continue; break; @@ -2844,7 +2845,7 @@ PHLWINDOW CCompositor::getForceFocus() { } void CCompositor::arrangeMonitors() { - static auto* const PXWLFORCESCALEZERO = (Hyprlang::INT* const*)g_pConfigManager->getConfigValuePtr("xwayland:force_zero_scaling"); + static auto* const PXWLFORCESCALEZERO = rc(g_pConfigManager->getConfigValuePtr("xwayland:force_zero_scaling")); std::vector toArrange(m_monitors.begin(), m_monitors.end()); std::vector arranged; @@ -3000,12 +3001,12 @@ void CCompositor::setPreferredScaleForSurface(SP pSurface, d const auto PSURFACE = CWLSurface::fromResource(pSurface); if (!PSURFACE) { - Debug::log(WARN, "Orphaned CWLSurfaceResource {:x} in setPreferredScaleForSurface", (uintptr_t)pSurface.get()); + Debug::log(WARN, "Orphaned CWLSurfaceResource {:x} in setPreferredScaleForSurface", rc(pSurface.get())); return; } PSURFACE->m_lastScaleFloat = scale; - PSURFACE->m_lastScaleInt = static_cast(std::ceil(scale)); + PSURFACE->m_lastScaleInt = sc(std::ceil(scale)); } void CCompositor::setPreferredTransformForSurface(SP pSurface, wl_output_transform transform) { @@ -3013,7 +3014,7 @@ void CCompositor::setPreferredTransformForSurface(SP pSurfac const auto PSURFACE = CWLSurface::fromResource(pSurface); if (!PSURFACE) { - Debug::log(WARN, "Orphaned CWLSurfaceResource {:x} in setPreferredTransformForSurface", (uintptr_t)pSurface.get()); + Debug::log(WARN, "Orphaned CWLSurfaceResource {:x} in setPreferredTransformForSurface", rc(pSurface.get())); return; } diff --git a/src/config/ConfigDataValues.hpp b/src/config/ConfigDataValues.hpp index d17e76729..72602df3a 100644 --- a/src/config/ConfigDataValues.hpp +++ b/src/config/ConfigDataValues.hpp @@ -78,7 +78,7 @@ class CGradientValueData : public ICustomConfigValueData { result += std::format("{:x} ", c.getAsHex()); } - result += std::format("{}deg", (int)(m_angle * 180.0 / M_PI)); + result += std::format("{}deg", sc(m_angle * 180.0 / M_PI)); return result; } }; diff --git a/src/config/ConfigManager.cpp b/src/config/ConfigManager.cpp index d6a0b7d46..0615a1d42 100644 --- a/src/config/ConfigManager.cpp +++ b/src/config/ConfigManager.cpp @@ -63,7 +63,7 @@ static Hyprlang::CParseResult configHandleGradientSet(const char* VALUE, void** if (!*data) *data = new CGradientValueData(); - const auto DATA = reinterpret_cast(*data); + const auto DATA = sc(*data); CVarList varlist(V, 0, ' '); DATA->m_colors.clear(); @@ -119,7 +119,7 @@ static Hyprlang::CParseResult configHandleGradientSet(const char* VALUE, void** static void configHandleGradientDestroy(void** data) { if (*data) - delete reinterpret_cast(*data); + delete sc(*data); } static Hyprlang::CParseResult configHandleGapSet(const char* VALUE, void** data) { @@ -128,7 +128,7 @@ static Hyprlang::CParseResult configHandleGapSet(const char* VALUE, void** data) if (!*data) *data = new CCssGapData(); - const auto DATA = reinterpret_cast(*data); + const auto DATA = sc(*data); CVarList varlist(V); Hyprlang::CParseResult result; @@ -144,14 +144,14 @@ static Hyprlang::CParseResult configHandleGapSet(const char* VALUE, void** data) static void configHandleGapDestroy(void** data) { if (*data) - delete reinterpret_cast(*data); + delete sc(*data); } static Hyprlang::CParseResult configHandleFontWeightSet(const char* VALUE, void** data) { if (!*data) *data = new CFontWeightConfigValueData(); - const auto DATA = reinterpret_cast(*data); + const auto DATA = sc(*data); Hyprlang::CParseResult result; try { @@ -166,7 +166,7 @@ static Hyprlang::CParseResult configHandleFontWeightSet(const char* VALUE, void* static void configHandleFontWeightDestroy(void** data) { if (*data) - delete reinterpret_cast(*data); + delete sc(*data); } static Hyprlang::CParseResult handleExec(const char* c, const char* v) { @@ -540,7 +540,7 @@ CConfigManager::CConfigManager() { registerConfigVar("debug:disable_logs", Hyprlang::INT{1}); registerConfigVar("debug:disable_time", Hyprlang::INT{1}); registerConfigVar("debug:enable_stdout_logs", Hyprlang::INT{0}); - registerConfigVar("debug:damage_tracking", {(Hyprlang::INT)DAMAGE_TRACKING_FULL}); + registerConfigVar("debug:damage_tracking", {sc(DAMAGE_TRACKING_FULL)}); registerConfigVar("debug:manual_crash", Hyprlang::INT{0}); registerConfigVar("debug:suppress_errors", Hyprlang::INT{0}); registerConfigVar("debug:error_limit", Hyprlang::INT{5}); @@ -863,8 +863,8 @@ CConfigManager::CConfigManager() { "https://wiki.hypr.land/Configuring/Variables/#debug"); } - Debug::m_disableLogs = reinterpret_cast(m_config->getConfigValuePtr("debug:disable_logs")->getDataStaticPtr()); - Debug::m_disableTime = reinterpret_cast(m_config->getConfigValuePtr("debug:disable_time")->getDataStaticPtr()); + Debug::m_disableLogs = rc(m_config->getConfigValuePtr("debug:disable_logs")->getDataStaticPtr()); + Debug::m_disableTime = rc(m_config->getConfigValuePtr("debug:disable_time")->getDataStaticPtr()); if (g_pEventLoopManager && ERR.has_value()) g_pEventLoopManager->doLater([ERR] { g_pHyprError->queueCreate(ERR.value(), CHyprColor{1.0, 0.1, 0.1, 1.0}); }); @@ -1233,7 +1233,7 @@ void CConfigManager::postConfigReload(const Hyprlang::CParseResult& result) { if (Debug::m_disableStdout && m_isFirstLaunch) Debug::log(LOG, "Disabling stdout logs! Check the log for further logs."); - Debug::m_coloredLogs = reinterpret_cast(m_config->getConfigValuePtr("debug:colored_stdout_logs")->getDataStaticPtr()); + Debug::m_coloredLogs = rc(m_config->getConfigValuePtr("debug:colored_stdout_logs")->getDataStaticPtr()); for (auto const& m : g_pCompositor->m_monitors) { // mark blur dirty @@ -1362,18 +1362,18 @@ SMonitorRule CConfigManager::getMonitorRuleFor(const PHLMONITOR PMONITOR) { } if (CONFIG->committedProperties & OUTPUT_HEAD_COMMITTED_TRANSFORM) { - Debug::log(LOG, " > overriding transform: {} -> {}", (uint8_t)rule.transform, (uint8_t)CONFIG->transform); + Debug::log(LOG, " > overriding transform: {} -> {}", sc(rule.transform), sc(CONFIG->transform)); rule.transform = CONFIG->transform; } if (CONFIG->committedProperties & OUTPUT_HEAD_COMMITTED_SCALE) { - Debug::log(LOG, " > overriding scale: {} -> {}", (uint8_t)rule.scale, (uint8_t)CONFIG->scale); + Debug::log(LOG, " > overriding scale: {} -> {}", sc(rule.scale), sc(CONFIG->scale)); rule.scale = CONFIG->scale; } if (CONFIG->committedProperties & OUTPUT_HEAD_COMMITTED_ADAPTIVE_SYNC) { Debug::log(LOG, " > overriding vrr: {} -> {}", rule.vrr.value_or(0), CONFIG->adaptiveSync); - rule.vrr = (int)CONFIG->adaptiveSync; + rule.vrr = sc(CONFIG->adaptiveSync); } return rule; @@ -1534,14 +1534,14 @@ std::vector> CConfigManager::getMatchingRules(PHLWINDOW pWindow, if (ARGS[0] == "*") internalMode = std::nullopt; else if (isNumber(ARGS[0])) - internalMode = (eFullscreenMode)std::stoi(ARGS[0]); + internalMode = sc(std::stoi(ARGS[0])); else throw std::runtime_error("szFullscreenState internal mode not valid"); if (ARGS[1] == "*") clientMode = std::nullopt; else if (isNumber(ARGS[1])) - clientMode = (eFullscreenMode)std::stoi(ARGS[1]); + clientMode = sc(std::stoi(ARGS[1])); else throw std::runtime_error("szFullscreenState client mode not valid"); @@ -1634,7 +1634,7 @@ std::vector> CConfigManager::getMatchingRules(PHLWINDOW pWindow, hasFullscreen = true; } - std::vector PIDs = {(uint64_t)pWindow->getPID()}; + std::vector PIDs = {sc(pWindow->getPID())}; while (getPPIDof(PIDs.back()) > 10) PIDs.push_back(getPPIDof(PIDs.back())); @@ -1661,7 +1661,7 @@ std::vector> CConfigManager::getMatchingRules(PHLLS pLS) { for (auto const& lr : m_layerRules) { if (lr->m_targetNamespace.starts_with("address:0x")) { - if (std::format("address:0x{:x}", (uintptr_t)pLS.get()) != lr->m_targetNamespace) + if (std::format("address:0x{:x}", rc(pLS.get())) != lr->m_targetNamespace) continue; } else if (!lr->m_targetNamespaceRegex.passes(pLS->m_layerSurface->m_layerNamespace)) continue; @@ -1804,7 +1804,7 @@ void CConfigManager::ensureMonitorStatus() { } void CConfigManager::ensureVRR(PHLMONITOR pMonitor) { - static auto PVRR = reinterpret_cast(getConfigValuePtr("misc:vrr")); + static auto PVRR = rc(getConfigValuePtr("misc:vrr")); static auto ensureVRRForDisplay = [&](PHLMONITOR m) -> void { if (!m->m_output || m->m_createdByUser) @@ -2061,7 +2061,7 @@ static bool parseModeLine(const std::string& modeline, drmModeModeInfo& mode) { }; // clang-format on - for (; argno < static_cast(args.size()); argno++) { + for (; argno < sc(args.size()); argno++) { auto key = args[argno]; std::ranges::transform(key, key.begin(), ::tolower); @@ -2107,7 +2107,7 @@ bool CMonitorRuleParser::parseMode(const std::string& value) { m_rule.resolution = Vector2D(-1, -3); else if (parseModeLine(value, m_rule.drmMode)) { m_rule.resolution = Vector2D(m_rule.drmMode.hdisplay, m_rule.drmMode.vdisplay); - m_rule.refreshRate = float(m_rule.drmMode.vrefresh) / 1000; + m_rule.refreshRate = sc(m_rule.drmMode.vrefresh) / 1000; } else { if (!value.contains("x")) { @@ -2200,7 +2200,7 @@ bool CMonitorRuleParser::parseTransform(const std::string& value) { m_error += "invalid transform "; return false; } - m_rule.transform = (wl_output_transform)TSF; + m_rule.transform = sc(TSF); return true; } @@ -2534,7 +2534,7 @@ std::optional CConfigManager::handleBind(const std::string& command const int DESCR_OFFSET = hasDescription ? 1 : 0; if ((ARGS.size() < 3 && !mouse) || (ARGS.size() < 3 && mouse)) return "bind: too few args"; - else if ((ARGS.size() > (size_t)4 + DESCR_OFFSET && !mouse) || (ARGS.size() > (size_t)3 + DESCR_OFFSET && mouse)) + else if ((ARGS.size() > sc(4) + DESCR_OFFSET && !mouse) || (ARGS.size() > sc(3) + DESCR_OFFSET && mouse)) return "bind: too many args"; std::set KEYSYMS; @@ -2870,7 +2870,7 @@ void CConfigManager::updateBlurredLS(const std::string& name, const bool forceBl for (auto const& lsl : m->m_layerSurfaceLayers) { for (auto const& ls : lsl) { if (BYADDRESS) { - if (std::format("0x{:x}", (uintptr_t)ls.get()) == matchName) + if (std::format("0x{:x}", rc(ls.get())) == matchName) ls->m_forceBlur = forceBlur; } else if (ls->m_namespace == matchName) ls->m_forceBlur = forceBlur; @@ -3027,7 +3027,7 @@ std::optional CConfigManager::handleSource(const std::string& comma return "source= path " + rawpath + " bogus!"; } - std::unique_ptr glob_buf{static_cast(calloc(1, sizeof(glob_t))), // allocate and zero-initialize + std::unique_ptr glob_buf{sc(calloc(1, sizeof(glob_t))), // allocate and zero-initialize [](glob_t* g) { if (g) { globfree(g); // free internal resources allocated by glob() @@ -3191,7 +3191,7 @@ std::string SConfigOptionDescription::jsonify() const { const auto V = std::any_cast(CONFIGVALUE); currentValue = std::format("{}, {}", V.x, V.y); } else if (typeid(void*) == std::type_index(CONFIGVALUE.type())) { - const auto DATA = (ICustomConfigValueData*)std::any_cast(CONFIGVALUE); + const auto DATA = sc(std::any_cast(CONFIGVALUE)); currentValue = DATA->toString(); } @@ -3264,7 +3264,7 @@ std::string SConfigOptionDescription::jsonify() const { {} }} }})#", - value, escapeJSONStrings(description), (uint16_t)type, (uint32_t)flags, parseData()); + value, escapeJSONStrings(description), sc(type), sc(flags), parseData()); return json; } diff --git a/src/config/ConfigValue.hpp b/src/config/ConfigValue.hpp index a159bf8cc..1da359b60 100644 --- a/src/config/ConfigValue.hpp +++ b/src/config/ConfigValue.hpp @@ -29,7 +29,7 @@ class CConfigValue { } T* ptr() const { - return *(T* const*)p_; + return *rc(p_); } T operator*() const { @@ -48,26 +48,26 @@ inline std::string* CConfigValue::ptr() const { template <> inline std::string CConfigValue::operator*() const { - return std::string{*(Hyprlang::STRING*)p_}; + return std::string{*rc(p_)}; } template <> inline Hyprlang::STRING* CConfigValue::ptr() const { - return (Hyprlang::STRING*)p_; + return rc(*p_); } template <> inline Hyprlang::STRING CConfigValue::operator*() const { - return *(Hyprlang::STRING*)p_; + return *rc(p_); } template <> inline Hyprlang::CUSTOMTYPE* CConfigValue::ptr() const { - return *(Hyprlang::CUSTOMTYPE* const*)p_; + return *rc(p_); } template <> inline Hyprlang::CUSTOMTYPE CConfigValue::operator*() const { RASSERT(false, "Impossible to implement operator* of CConfigValue, use ptr()"); return *ptr(); -} +} \ No newline at end of file diff --git a/src/config/ConfigWatcher.cpp b/src/config/ConfigWatcher.cpp index 2ec1c05d6..f3a8a2cad 100644 --- a/src/config/ConfigWatcher.cpp +++ b/src/config/ConfigWatcher.cpp @@ -72,15 +72,15 @@ void CConfigWatcher::onInotifyEvent() { if (bytesRead <= 0) return; - for (size_t offset = 0; offset < (size_t)bytesRead;) { - const auto* ev = (const inotify_event*)(buffer.data() + offset); + for (size_t offset = 0; offset < sc(bytesRead);) { + const auto* ev = rc(buffer.data() + offset); - if (offset + sizeof(inotify_event) > (size_t)bytesRead) { + if (offset + sizeof(inotify_event) > sc(bytesRead)) { Debug::log(ERR, "CConfigWatcher: malformed inotify event, truncated header"); break; } - if (offset + sizeof(inotify_event) + ev->len > (size_t)(bytesRead)) { + if (offset + sizeof(inotify_event) + ev->len > sc(bytesRead)) { Debug::log(ERR, "CConfigWatcher: malformed inotify event, truncated name field"); break; } diff --git a/src/debug/CrashReporter.cpp b/src/debug/CrashReporter.cpp index 38552c51f..f52062bef 100644 --- a/src/debug/CrashReporter.cpp +++ b/src/debug/CrashReporter.cpp @@ -206,8 +206,8 @@ void NCrashReporter::createAndSaveCrash(int sig) { // convert in memory address to VMA address Dl_info info; struct link_map* linkMap; - dladdr1((void*)CALLSTACK[i].adr, &info, (void**)&linkMap, RTLD_DL_LINKMAP); - size_t vmaAddr = (size_t)CALLSTACK[i].adr - linkMap->l_addr; + dladdr1(CALLSTACK[i].adr, &info, rc(&linkMap), RTLD_DL_LINKMAP); + size_t vmaAddr = rc(CALLSTACK[i].adr) - linkMap->l_addr; #else // musl doesn't define dladdr1 size_t vmaAddr = (size_t)CALLSTACK[i].adr; diff --git a/src/debug/HyprCtl.cpp b/src/debug/HyprCtl.cpp index 3b83d3230..758138fda 100644 --- a/src/debug/HyprCtl.cpp +++ b/src/debug/HyprCtl.cpp @@ -155,12 +155,13 @@ std::string CHyprCtl::getMonitorData(Hyprutils::Memory::CSharedPointer }},)#", m->m_id, escapeJSONStrings(m->m_name), escapeJSONStrings(m->m_shortDescription), escapeJSONStrings(m->m_output->make), escapeJSONStrings(m->m_output->model), - escapeJSONStrings(m->m_output->serial), (int)m->m_pixelSize.x, m->m_pixelSize.y, (int)m->m_output->physicalSize.x, (int)m->m_output->physicalSize.y, m->m_refreshRate, - (int)m->m_position.x, (int)m->m_position.y, m->activeWorkspaceID(), (!m->m_activeWorkspace ? "" : escapeJSONStrings(m->m_activeWorkspace->m_name)), - m->activeSpecialWorkspaceID(), escapeJSONStrings(m->m_activeSpecialWorkspace ? m->m_activeSpecialWorkspace->m_name : ""), (int)m->m_reservedTopLeft.x, - (int)m->m_reservedTopLeft.y, (int)m->m_reservedBottomRight.x, (int)m->m_reservedBottomRight.y, m->m_scale, (int)m->m_transform, - (m == g_pCompositor->m_lastMonitor ? "true" : "false"), (m->m_dpmsStatus ? "true" : "false"), (m->m_output->state->state().adaptiveSync ? "true" : "false"), - (uint64_t)m->m_solitaryClient.get(), (m->m_tearingState.activelyTearing ? "true" : "false"), (uint64_t)m->m_lastScanout.get(), (m->m_enabled ? "false" : "true"), + escapeJSONStrings(m->m_output->serial), sc(m->m_pixelSize.x), m->m_pixelSize.y, sc(m->m_output->physicalSize.x), sc(m->m_output->physicalSize.y), + m->m_refreshRate, sc(m->m_position.x), sc(m->m_position.y), m->activeWorkspaceID(), + (!m->m_activeWorkspace ? "" : escapeJSONStrings(m->m_activeWorkspace->m_name)), m->activeSpecialWorkspaceID(), + escapeJSONStrings(m->m_activeSpecialWorkspace ? m->m_activeSpecialWorkspace->m_name : ""), sc(m->m_reservedTopLeft.x), sc(m->m_reservedTopLeft.y), + sc(m->m_reservedBottomRight.x), sc(m->m_reservedBottomRight.y), m->m_scale, sc(m->m_transform), (m == g_pCompositor->m_lastMonitor ? "true" : "false"), + (m->m_dpmsStatus ? "true" : "false"), (m->m_output->state->state().adaptiveSync ? "true" : "false"), rc(m->m_solitaryClient.get()), + (m->m_tearingState.activelyTearing ? "true" : "false"), rc(m->m_lastScanout.get()), (m->m_enabled ? "false" : "true"), formatToString(m->m_output->state->state().drmFormat), m->m_mirrorOf ? std::format("{}", m->m_mirrorOf->m_id) : "none", availableModesForOutput(m, format)); } else { @@ -169,13 +170,13 @@ std::string CHyprCtl::getMonitorData(Hyprutils::Memory::CSharedPointer "special workspace: {} ({})\n\treserved: {} {} {} {}\n\tscale: {:.2f}\n\ttransform: {}\n\tfocused: {}\n\t" "dpmsStatus: {}\n\tvrr: {}\n\tsolitary: {:x}\n\tactivelyTearing: {}\n\tdirectScanoutTo: {:x}\n\tdisabled: {}\n\tcurrentFormat: {}\n\tmirrorOf: " "{}\n\tavailableModes: {}\n\n", - m->m_name, m->m_id, (int)m->m_pixelSize.x, (int)m->m_pixelSize.y, m->m_refreshRate, (int)m->m_position.x, (int)m->m_position.y, m->m_shortDescription, - m->m_output->make, m->m_output->model, (int)m->m_output->physicalSize.x, (int)m->m_output->physicalSize.y, m->m_output->serial, m->activeWorkspaceID(), + m->m_name, m->m_id, sc(m->m_pixelSize.x), sc(m->m_pixelSize.y), m->m_refreshRate, sc(m->m_position.x), sc(m->m_position.y), m->m_shortDescription, + m->m_output->make, m->m_output->model, sc(m->m_output->physicalSize.x), sc(m->m_output->physicalSize.y), m->m_output->serial, m->activeWorkspaceID(), (!m->m_activeWorkspace ? "" : m->m_activeWorkspace->m_name), m->activeSpecialWorkspaceID(), (m->m_activeSpecialWorkspace ? m->m_activeSpecialWorkspace->m_name : ""), - (int)m->m_reservedTopLeft.x, (int)m->m_reservedTopLeft.y, (int)m->m_reservedBottomRight.x, (int)m->m_reservedBottomRight.y, m->m_scale, (int)m->m_transform, - (m == g_pCompositor->m_lastMonitor ? "yes" : "no"), (int)m->m_dpmsStatus, m->m_output->state->state().adaptiveSync, (uint64_t)m->m_solitaryClient.get(), - m->m_tearingState.activelyTearing, (uint64_t)m->m_lastScanout.get(), !m->m_enabled, formatToString(m->m_output->state->state().drmFormat), - m->m_mirrorOf ? std::format("{}", m->m_mirrorOf->m_id) : "none", availableModesForOutput(m, format)); + sc(m->m_reservedTopLeft.x), sc(m->m_reservedTopLeft.y), sc(m->m_reservedBottomRight.x), sc(m->m_reservedBottomRight.y), m->m_scale, + sc(m->m_transform), (m == g_pCompositor->m_lastMonitor ? "yes" : "no"), sc(m->m_dpmsStatus), m->m_output->state->state().adaptiveSync, + rc(m->m_solitaryClient.get()), m->m_tearingState.activelyTearing, rc(m->m_lastScanout.get()), !m->m_enabled, + formatToString(m->m_output->state->state().drmFormat), m->m_mirrorOf ? std::format("{}", m->m_mirrorOf->m_id) : "none", availableModesForOutput(m, format)); } return result; @@ -235,9 +236,9 @@ static std::string getGroupedData(PHLWINDOW w, eHyprCtlOutputFormat format) { PHLWINDOW curr = head; while (true) { if (isJson) - result << std::format("\"0x{:x}\"", (uintptr_t)curr.get()); + result << std::format("\"0x{:x}\"", rc(curr.get())); else - result << std::format("{:x}", (uintptr_t)curr.get()); + result << std::format("{:x}", rc(curr.get())); curr = curr->m_groupData.pNextWindow.lock(); // We've wrapped around to the start, break out without trailing comma if (curr == head) @@ -289,12 +290,12 @@ std::string CHyprCtl::getWindowData(PHLWINDOW w, eHyprCtlOutputFormat format) { "xdgTag": "{}", "xdgDescription": "{}" }},)#", - (uintptr_t)w.get(), (w->m_isMapped ? "true" : "false"), (w->isHidden() ? "true" : "false"), (int)w->m_realPosition->goal().x, (int)w->m_realPosition->goal().y, - (int)w->m_realSize->goal().x, (int)w->m_realSize->goal().y, w->m_workspace ? w->workspaceID() : WORKSPACE_INVALID, - escapeJSONStrings(!w->m_workspace ? "" : w->m_workspace->m_name), ((int)w->m_isFloating == 1 ? "true" : "false"), (w->m_isPseudotiled ? "true" : "false"), - (int64_t)w->monitorID(), escapeJSONStrings(w->m_class), escapeJSONStrings(w->m_title), escapeJSONStrings(w->m_initialClass), escapeJSONStrings(w->m_initialTitle), - w->getPID(), ((int)w->m_isX11 == 1 ? "true" : "false"), (w->m_pinned ? "true" : "false"), (uint8_t)w->m_fullscreenState.internal, (uint8_t)w->m_fullscreenState.client, - getGroupedData(w, format), getTagsData(w, format), (uintptr_t)w->m_swallowed.get(), getFocusHistoryID(w), + rc(w.get()), (w->m_isMapped ? "true" : "false"), (w->isHidden() ? "true" : "false"), sc(w->m_realPosition->goal().x), + sc(w->m_realPosition->goal().y), sc(w->m_realSize->goal().x), sc(w->m_realSize->goal().y), w->m_workspace ? w->workspaceID() : WORKSPACE_INVALID, + escapeJSONStrings(!w->m_workspace ? "" : w->m_workspace->m_name), (sc(w->m_isFloating) == 1 ? "true" : "false"), (w->m_isPseudotiled ? "true" : "false"), + w->monitorID(), escapeJSONStrings(w->m_class), escapeJSONStrings(w->m_title), escapeJSONStrings(w->m_initialClass), escapeJSONStrings(w->m_initialTitle), w->getPID(), + (sc(w->m_isX11) == 1 ? "true" : "false"), (w->m_pinned ? "true" : "false"), sc(w->m_fullscreenState.internal), sc(w->m_fullscreenState.client), + getGroupedData(w, format), getTagsData(w, format), rc(w->m_swallowed.get()), getFocusHistoryID(w), (g_pInputManager->isWindowInhibiting(w, false) ? "true" : "false"), escapeJSONStrings(w->xdgTag().value_or("")), escapeJSONStrings(w->xdgDescription().value_or(""))); } else { return std::format( @@ -303,11 +304,12 @@ std::string CHyprCtl::getWindowData(PHLWINDOW w, eHyprCtlOutputFormat format) { "{}\n\txwayland: {}\n\tpinned: " "{}\n\tfullscreen: {}\n\tfullscreenClient: {}\n\tgrouped: {}\n\ttags: {}\n\tswallowing: {:x}\n\tfocusHistoryID: {}\n\tinhibitingIdle: {}\n\txdgTag: " "{}\n\txdgDescription: {}\n\n", - (uintptr_t)w.get(), w->m_title, (int)w->m_isMapped, (int)w->isHidden(), (int)w->m_realPosition->goal().x, (int)w->m_realPosition->goal().y, - (int)w->m_realSize->goal().x, (int)w->m_realSize->goal().y, w->m_workspace ? w->workspaceID() : WORKSPACE_INVALID, (!w->m_workspace ? "" : w->m_workspace->m_name), - (int)w->m_isFloating, (int)w->m_isPseudotiled, (int64_t)w->monitorID(), w->m_class, w->m_title, w->m_initialClass, w->m_initialTitle, w->getPID(), (int)w->m_isX11, - (int)w->m_pinned, (uint8_t)w->m_fullscreenState.internal, (uint8_t)w->m_fullscreenState.client, getGroupedData(w, format), getTagsData(w, format), - (uintptr_t)w->m_swallowed.get(), getFocusHistoryID(w), (int)g_pInputManager->isWindowInhibiting(w, false), w->xdgTag().value_or(""), w->xdgDescription().value_or("")); + rc(w.get()), w->m_title, sc(w->m_isMapped), sc(w->isHidden()), sc(w->m_realPosition->goal().x), sc(w->m_realPosition->goal().y), + sc(w->m_realSize->goal().x), sc(w->m_realSize->goal().y), w->m_workspace ? w->workspaceID() : WORKSPACE_INVALID, + (!w->m_workspace ? "" : w->m_workspace->m_name), sc(w->m_isFloating), sc(w->m_isPseudotiled), w->monitorID(), w->m_class, w->m_title, w->m_initialClass, + w->m_initialTitle, w->getPID(), sc(w->m_isX11), sc(w->m_pinned), sc(w->m_fullscreenState.internal), sc(w->m_fullscreenState.client), + getGroupedData(w, format), getTagsData(w, format), rc(w->m_swallowed.get()), getFocusHistoryID(w), sc(g_pInputManager->isWindowInhibiting(w, false)), + w->xdgTag().value_or(""), w->xdgDescription().value_or("")); } } @@ -357,12 +359,12 @@ std::string CHyprCtl::getWorkspaceData(PHLWORKSPACE w, eHyprCtlOutputFormat form }})#", w->m_id, escapeJSONStrings(w->m_name), escapeJSONStrings(PMONITOR ? PMONITOR->m_name : "?"), escapeJSONStrings(PMONITOR ? std::to_string(PMONITOR->m_id) : "null"), w->getWindows(), w->m_hasFullscreenWindow ? "true" : "false", - (uintptr_t)PLASTW.get(), PLASTW ? escapeJSONStrings(PLASTW->m_title) : "", w->isPersistent() ? "true" : "false"); + rc(PLASTW.get()), PLASTW ? escapeJSONStrings(PLASTW->m_title) : "", w->isPersistent() ? "true" : "false"); } else { return std::format( "workspace ID {} ({}) on monitor {}:\n\tmonitorID: {}\n\twindows: {}\n\thasfullscreen: {}\n\tlastwindow: 0x{:x}\n\tlastwindowtitle: {}\n\tispersistent: {}\n\n", - w->m_id, w->m_name, PMONITOR ? PMONITOR->m_name : "?", PMONITOR ? std::to_string(PMONITOR->m_id) : "null", w->getWindows(), (int)w->m_hasFullscreenWindow, - (uintptr_t)PLASTW.get(), PLASTW ? PLASTW->m_title : "", (int)w->isPersistent()); + w->m_id, w->m_name, PMONITOR ? PMONITOR->m_name : "?", PMONITOR ? std::to_string(PMONITOR->m_id) : "null", w->getWindows(), sc(w->m_hasFullscreenWindow), + rc(PLASTW.get()), PLASTW ? PLASTW->m_title : "", sc(w->isPersistent())); } } @@ -370,19 +372,19 @@ static std::string getWorkspaceRuleData(const SWorkspaceRule& r, eHyprCtlOutputF const auto boolToString = [](const bool b) -> std::string { return b ? "true" : "false"; }; if (format == eHyprCtlOutputFormat::FORMAT_JSON) { const std::string monitor = r.monitor.empty() ? "" : std::format(",\n \"monitor\": \"{}\"", escapeJSONStrings(r.monitor)); - const std::string default_ = (bool)(r.isDefault) ? std::format(",\n \"default\": {}", boolToString(r.isDefault)) : ""; - const std::string persistent = (bool)(r.isPersistent) ? std::format(",\n \"persistent\": {}", boolToString(r.isPersistent)) : ""; - const std::string gapsIn = (bool)(r.gapsIn) ? + const std::string default_ = sc(r.isDefault) ? std::format(",\n \"default\": {}", boolToString(r.isDefault)) : ""; + const std::string persistent = sc(r.isPersistent) ? std::format(",\n \"persistent\": {}", boolToString(r.isPersistent)) : ""; + const std::string gapsIn = sc(r.gapsIn) ? std::format(",\n \"gapsIn\": [{}, {}, {}, {}]", r.gapsIn.value().m_top, r.gapsIn.value().m_right, r.gapsIn.value().m_bottom, r.gapsIn.value().m_left) : ""; - const std::string gapsOut = (bool)(r.gapsOut) ? + const std::string gapsOut = sc(r.gapsOut) ? std::format(",\n \"gapsOut\": [{}, {}, {}, {}]", r.gapsOut.value().m_top, r.gapsOut.value().m_right, r.gapsOut.value().m_bottom, r.gapsOut.value().m_left) : ""; - const std::string borderSize = (bool)(r.borderSize) ? std::format(",\n \"borderSize\": {}", r.borderSize.value()) : ""; - const std::string border = (bool)(r.noBorder) ? std::format(",\n \"border\": {}", boolToString(!r.noBorder.value())) : ""; - const std::string rounding = (bool)(r.noRounding) ? std::format(",\n \"rounding\": {}", boolToString(!r.noRounding.value())) : ""; - const std::string decorate = (bool)(r.decorate) ? std::format(",\n \"decorate\": {}", boolToString(r.decorate.value())) : ""; - const std::string shadow = (bool)(r.noShadow) ? std::format(",\n \"shadow\": {}", boolToString(!r.noShadow.value())) : ""; + const std::string borderSize = sc(r.borderSize) ? std::format(",\n \"borderSize\": {}", r.borderSize.value()) : ""; + const std::string border = sc(r.noBorder) ? std::format(",\n \"border\": {}", boolToString(!r.noBorder.value())) : ""; + const std::string rounding = sc(r.noRounding) ? std::format(",\n \"rounding\": {}", boolToString(!r.noRounding.value())) : ""; + const std::string decorate = sc(r.decorate) ? std::format(",\n \"decorate\": {}", boolToString(r.decorate.value())) : ""; + const std::string shadow = sc(r.noShadow) ? std::format(",\n \"shadow\": {}", boolToString(!r.noShadow.value())) : ""; const std::string defaultName = r.defaultName.has_value() ? std::format(",\n \"defaultName\": \"{}\"", escapeJSONStrings(r.defaultName.value())) : ""; std::string result = @@ -394,19 +396,20 @@ static std::string getWorkspaceRuleData(const SWorkspaceRule& r, eHyprCtlOutputF return result; } else { const std::string monitor = std::format("\tmonitor: {}\n", r.monitor.empty() ? "" : escapeJSONStrings(r.monitor)); - const std::string default_ = std::format("\tdefault: {}\n", (bool)(r.isDefault) ? boolToString(r.isDefault) : ""); - const std::string persistent = std::format("\tpersistent: {}\n", (bool)(r.isPersistent) ? boolToString(r.isPersistent) : ""); - const std::string gapsIn = (bool)(r.gapsIn) ? std::format("\tgapsIn: {} {} {} {}\n", std::to_string(r.gapsIn.value().m_top), std::to_string(r.gapsIn.value().m_right), - std::to_string(r.gapsIn.value().m_bottom), std::to_string(r.gapsIn.value().m_left)) : - std::format("\tgapsIn: \n"); - const std::string gapsOut = (bool)(r.gapsOut) ? std::format("\tgapsOut: {} {} {} {}\n", std::to_string(r.gapsOut.value().m_top), std::to_string(r.gapsOut.value().m_right), - std::to_string(r.gapsOut.value().m_bottom), std::to_string(r.gapsOut.value().m_left)) : - std::format("\tgapsOut: \n"); - const std::string borderSize = std::format("\tborderSize: {}\n", (bool)(r.borderSize) ? std::to_string(r.borderSize.value()) : ""); - const std::string border = std::format("\tborder: {}\n", (bool)(r.noBorder) ? boolToString(!r.noBorder.value()) : ""); - const std::string rounding = std::format("\trounding: {}\n", (bool)(r.noRounding) ? boolToString(!r.noRounding.value()) : ""); - const std::string decorate = std::format("\tdecorate: {}\n", (bool)(r.decorate) ? boolToString(r.decorate.value()) : ""); - const std::string shadow = std::format("\tshadow: {}\n", (bool)(r.noShadow) ? boolToString(!r.noShadow.value()) : ""); + const std::string default_ = std::format("\tdefault: {}\n", sc(r.isDefault) ? boolToString(r.isDefault) : ""); + const std::string persistent = std::format("\tpersistent: {}\n", sc(r.isPersistent) ? boolToString(r.isPersistent) : ""); + const std::string gapsIn = sc(r.gapsIn) ? std::format("\tgapsIn: {} {} {} {}\n", std::to_string(r.gapsIn.value().m_top), std::to_string(r.gapsIn.value().m_right), + std::to_string(r.gapsIn.value().m_bottom), std::to_string(r.gapsIn.value().m_left)) : + std::format("\tgapsIn: \n"); + const std::string gapsOut = sc(r.gapsOut) ? + std::format("\tgapsOut: {} {} {} {}\n", std::to_string(r.gapsOut.value().m_top), std::to_string(r.gapsOut.value().m_right), std::to_string(r.gapsOut.value().m_bottom), + std::to_string(r.gapsOut.value().m_left)) : + std::format("\tgapsOut: \n"); + const std::string borderSize = std::format("\tborderSize: {}\n", sc(r.borderSize) ? std::to_string(r.borderSize.value()) : ""); + const std::string border = std::format("\tborder: {}\n", sc(r.noBorder) ? boolToString(!r.noBorder.value()) : ""); + const std::string rounding = std::format("\trounding: {}\n", sc(r.noRounding) ? boolToString(!r.noRounding.value()) : ""); + const std::string decorate = std::format("\tdecorate: {}\n", sc(r.decorate) ? boolToString(r.decorate.value()) : ""); + const std::string shadow = std::format("\tshadow: {}\n", sc(r.noShadow) ? boolToString(!r.noShadow.value()) : ""); const std::string defaultName = std::format("\tdefaultName: {}\n", r.defaultName.value_or("")); std::string result = std::format("Workspace rule {}:\n{}{}{}{}{}{}{}{}{}{}{}\n", escapeJSONStrings(r.workspaceString), monitor, default_, persistent, gapsIn, gapsOut, @@ -515,8 +518,8 @@ static std::string layersRequest(eHyprCtlOutputFormat format, std::string reques "namespace": "{}", "pid": {} }},)#", - (uintptr_t)layer.get(), layer->m_geometry.x, layer->m_geometry.y, layer->m_geometry.width, layer->m_geometry.height, escapeJSONStrings(layer->m_namespace), - layer->getPID()); + rc(layer.get()), layer->m_geometry.x, layer->m_geometry.y, layer->m_geometry.width, layer->m_geometry.height, + escapeJSONStrings(layer->m_namespace), layer->getPID()); } trimTrailingComma(result); @@ -547,7 +550,7 @@ static std::string layersRequest(eHyprCtlOutputFormat format, std::string reques result += std::format("\tLayer level {} ({}):\n", layerLevel, levelNames[layerLevel]); for (auto const& layer : level) { - result += std::format("\t\tLayer {:x}: xywh: {} {} {} {}, namespace: {}, pid: {}\n", (uintptr_t)layer.get(), layer->m_geometry.x, layer->m_geometry.y, + result += std::format("\t\tLayer {:x}: xywh: {} {} {} {}, namespace: {}, pid: {}\n", rc(layer.get()), layer->m_geometry.x, layer->m_geometry.y, layer->m_geometry.width, layer->m_geometry.height, layer->m_namespace, layer->getPID()); } @@ -628,7 +631,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque "name": "{}", "defaultSpeed": {:.5f} }},)#", - (uintptr_t)m.get(), escapeJSONStrings(m->m_hlName), + rc(m.get()), escapeJSONStrings(m->m_hlName), m->aq() && m->aq()->getLibinputHandle() ? libinput_device_config_accel_get_default_speed(m->aq()->getLibinputHandle()) : 0.f); } @@ -652,7 +655,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque "numLock": {}, "main": {} }},)#", - (uintptr_t)k.get(), escapeJSONStrings(k->m_hlName), escapeJSONStrings(k->m_currentRules.rules), escapeJSONStrings(k->m_currentRules.model), + rc(k.get()), escapeJSONStrings(k->m_hlName), escapeJSONStrings(k->m_currentRules.rules), escapeJSONStrings(k->m_currentRules.model), escapeJSONStrings(k->m_currentRules.layout), escapeJSONStrings(k->m_currentRules.variant), escapeJSONStrings(k->m_currentRules.options), escapeJSONStrings(KM), (getModState(k, XKB_MOD_NAME_CAPS) ? "true" : "false"), (getModState(k, XKB_MOD_NAME_NUM) ? "true" : "false"), (k->m_active ? "true" : "false")); } @@ -672,7 +675,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque "name": "{}" }} }},)#", - (uintptr_t)d.get(), (uintptr_t)d->m_parent.get(), escapeJSONStrings(d->m_parent ? d->m_parent->m_hlName : "")); + rc(d.get()), rc(d->m_parent.get()), escapeJSONStrings(d->m_parent ? d->m_parent->m_hlName : "")); } for (auto const& d : g_pInputManager->m_tablets) { @@ -681,7 +684,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque "address": "0x{:x}", "name": "{}" }},)#", - (uintptr_t)d.get(), escapeJSONStrings(d->m_hlName)); + rc(d.get()), escapeJSONStrings(d->m_hlName)); } for (auto const& d : g_pInputManager->m_tabletTools) { @@ -690,7 +693,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque "address": "0x{:x}", "type": "tabletTool", }},)#", - (uintptr_t)d.get()); + rc(d.get())); } trimTrailingComma(result); @@ -704,7 +707,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque "address": "0x{:x}", "name": "{}" }},)#", - (uintptr_t)d.get(), escapeJSONStrings(d->m_hlName)); + rc(d.get()), escapeJSONStrings(d->m_hlName)); } trimTrailingComma(result); @@ -718,7 +721,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque "address": "0x{:x}", "name": "{}" }},)#", - (uintptr_t)&d, escapeJSONStrings(d.pDevice ? d.pDevice->getName() : "")); + rc(&d), escapeJSONStrings(d.pDevice ? d.pDevice->getName() : "")); } trimTrailingComma(result); @@ -730,7 +733,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque result += "mice:\n"; for (auto const& m : g_pInputManager->m_pointers) { - result += std::format("\tMouse at {:x}:\n\t\t{}\n\t\t\tdefault speed: {:.5f}\n", (uintptr_t)m.get(), m->m_hlName, + result += std::format("\tMouse at {:x}:\n\t\t{}\n\t\t\tdefault speed: {:.5f}\n", rc(m.get()), m->m_hlName, (m->aq() && m->aq()->getLibinputHandle() ? libinput_device_config_accel_get_default_speed(m->aq()->getLibinputHandle()) : 0.f)); } @@ -740,7 +743,7 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque const auto KM = k->getActiveLayout(); result += std::format("\tKeyboard at {:x}:\n\t\t{}\n\t\t\trules: r \"{}\", m \"{}\", l \"{}\", v \"{}\", o \"{}\"\n\t\t\tactive keymap: {}\n\t\t\tcapsLock: " "{}\n\t\t\tnumLock: {}\n\t\t\tmain: {}\n", - (uintptr_t)k.get(), k->m_hlName, k->m_currentRules.rules, k->m_currentRules.model, k->m_currentRules.layout, k->m_currentRules.variant, + rc(k.get()), k->m_hlName, k->m_currentRules.rules, k->m_currentRules.model, k->m_currentRules.layout, k->m_currentRules.variant, k->m_currentRules.options, KM, (getModState(k, XKB_MOD_NAME_CAPS) ? "yes" : "no"), (getModState(k, XKB_MOD_NAME_NUM) ? "yes" : "no"), (k->m_active ? "yes" : "no")); } @@ -748,27 +751,28 @@ static std::string devicesRequest(eHyprCtlOutputFormat format, std::string reque result += "\n\nTablets:\n"; for (auto const& d : g_pInputManager->m_tabletPads) { - result += std::format("\tTablet Pad at {:x} (belongs to {:x} -> {})\n", (uintptr_t)d.get(), (uintptr_t)d->m_parent.get(), d->m_parent ? d->m_parent->m_hlName : ""); + result += + std::format("\tTablet Pad at {:x} (belongs to {:x} -> {})\n", rc(d.get()), rc(d->m_parent.get()), d->m_parent ? d->m_parent->m_hlName : ""); } for (auto const& d : g_pInputManager->m_tablets) { - result += std::format("\tTablet at {:x}:\n\t\t{}\n\t\t\tsize: {}x{}mm\n", (uintptr_t)d.get(), d->m_hlName, d->aq()->physicalSize.x, d->aq()->physicalSize.y); + result += std::format("\tTablet at {:x}:\n\t\t{}\n\t\t\tsize: {}x{}mm\n", rc(d.get()), d->m_hlName, d->aq()->physicalSize.x, d->aq()->physicalSize.y); } for (auto const& d : g_pInputManager->m_tabletTools) { - result += std::format("\tTablet Tool at {:x}\n", (uintptr_t)d.get()); + result += std::format("\tTablet Tool at {:x}\n", rc(d.get())); } result += "\n\nTouch:\n"; for (auto const& d : g_pInputManager->m_touches) { - result += std::format("\tTouch Device at {:x}:\n\t\t{}\n", (uintptr_t)d.get(), d->m_hlName); + result += std::format("\tTouch Device at {:x}:\n\t\t{}\n", rc(d.get()), d->m_hlName); } result += "\n\nSwitches:\n"; for (auto const& d : g_pInputManager->m_switches) { - result += std::format("\tSwitch Device at {:x}:\n\t\t{}\n", (uintptr_t)&d, d.pDevice ? d.pDevice->getName() : ""); + result += std::format("\tSwitch Device at {:x}:\n\t\t{}\n", rc(&d), d.pDevice ? d.pDevice->getName() : ""); } } @@ -781,7 +785,7 @@ static std::string animationsRequest(eHyprCtlOutputFormat format, std::string re ret += "animations:\n"; for (auto const& ac : g_pConfigManager->getAnimationConfig()) { - ret += std::format("\n\tname: {}\n\t\toverriden: {}\n\t\tbezier: {}\n\t\tenabled: {}\n\t\tspeed: {:.2f}\n\t\tstyle: {}\n", ac.first, (int)ac.second->overridden, + ret += std::format("\n\tname: {}\n\t\toverriden: {}\n\t\tbezier: {}\n\t\tenabled: {}\n\t\tspeed: {:.2f}\n\t\tstyle: {}\n", ac.first, sc(ac.second->overridden), ac.second->internalBezier, ac.second->internalEnabled, ac.second->internalSpeed, ac.second->internalStyle); } @@ -1083,7 +1087,7 @@ std::string systemInfoRequest(eHyprCtlOutputFormat format, std::string request) for (const auto& m : g_pCompositor->m_monitors) { result += std::format("\n\tPanel {}: {}x{}, {} {} {} {} -> backend {}\n\t\texplicit {}\n\t\tedid:\n\t\t\thdr {}\n\t\t\tchroma {}\n\t\t\tbt2020 {}\n\t\tvrr capable " "{}\n\t\tnon-desktop {}\n\t\t", - m->m_name, (int)m->m_pixelSize.x, (int)m->m_pixelSize.y, m->m_output->name, m->m_output->make, m->m_output->model, m->m_output->serial, + m->m_name, sc(m->m_pixelSize.x), sc(m->m_pixelSize.y), m->m_output->name, m->m_output->make, m->m_output->model, m->m_output->serial, backend(m->m_output->getBackend()->type()), check(m->m_output->supportsExplicit), check(m->m_output->parsedEDID.hdrMetadata.has_value()), check(m->m_output->parsedEDID.chromaticityCoords.has_value()), check(m->m_output->parsedEDID.supportsBT2020), check(m->m_output->vrrCapable), check(m->m_output->nonDesktop)); @@ -1105,7 +1109,7 @@ static std::string dispatchRequest(eHyprCtlOutputFormat format, std::string in) const auto DISPATCHSTR = in.substr(0, in.find_first_of(' ')); auto DISPATCHARG = std::string(); - if ((int)in.find_first_of(' ') != -1) + if (sc(in.find_first_of(' ')) != -1) DISPATCHARG = in.substr(in.find_first_of(' ') + 1); const auto DISPATCHER = g_pKeybindManager->m_dispatchers.find(DISPATCHSTR); @@ -1222,7 +1226,7 @@ static std::string cursorPosRequest(eHyprCtlOutputFormat format, std::string req const auto CURSORPOS = g_pInputManager->getMouseCoordsInternal().floor(); if (format == eHyprCtlOutputFormat::FORMAT_NORMAL) { - return std::format("{}, {}", (int)CURSORPOS.x, (int)CURSORPOS.y); + return std::format("{}, {}", sc(CURSORPOS.x), sc(CURSORPOS.y)); } else { return std::format(R"#( {{ @@ -1230,7 +1234,7 @@ static std::string cursorPosRequest(eHyprCtlOutputFormat format, std::string req "y": {} }} )#", - (int)CURSORPOS.x, (int)CURSORPOS.y); + sc(CURSORPOS.x), sc(CURSORPOS.y)); } return "error"; @@ -1259,7 +1263,7 @@ static std::string dispatchBatch(eHyprCtlOutputFormat format, std::string reques } } - return reply.substr(0, std::max(static_cast(reply.size() - DELIMITER.size()), 0)); + return reply.substr(0, std::max(sc(reply.size() - DELIMITER.size()), 0)); } static std::string dispatchSetCursor(eHyprCtlOutputFormat format, std::string request) { @@ -1315,7 +1319,7 @@ static std::string switchXKBLayoutRequest(eHyprCtlOutputFormat format, std::stri requestedLayout = std::stoi(CMD); } catch (std::exception& e) { return "invalid arg 2"; } - if (requestedLayout < 0 || (uint64_t)requestedLayout > LAYOUTS - 1) { + if (requestedLayout < 0 || sc(requestedLayout) > LAYOUTS - 1) { return "layout idx out of range of " + std::to_string(LAYOUTS); } @@ -1433,7 +1437,7 @@ static std::string dispatchGetOption(eHyprCtlOutputFormat format, std::string re else if (TYPE == typeid(Hyprlang::STRING)) return std::format("str: {}\nset: {}", std::any_cast(VAL), VAR->m_bSetByUser); else if (TYPE == typeid(void*)) - return std::format("custom type: {}\nset: {}", ((ICustomConfigValueData*)std::any_cast(VAL))->toString(), VAR->m_bSetByUser); + return std::format("custom type: {}\nset: {}", sc(std::any_cast(VAL))->toString(), VAR->m_bSetByUser); } else { if (TYPE == typeid(Hyprlang::INT)) return std::format(R"({{"option": "{}", "int": {}, "set": {} }})", curitem, std::any_cast(VAL), VAR->m_bSetByUser); @@ -1445,7 +1449,7 @@ static std::string dispatchGetOption(eHyprCtlOutputFormat format, std::string re else if (TYPE == typeid(Hyprlang::STRING)) return std::format(R"({{"option": "{}", "str": "{}", "set": {} }})", curitem, escapeJSONStrings(std::any_cast(VAL)), VAR->m_bSetByUser); else if (TYPE == typeid(void*)) - return std::format(R"({{"option": "{}", "custom": "{}", "set": {} }})", curitem, ((ICustomConfigValueData*)std::any_cast(VAL))->toString(), VAR->m_bSetByUser); + return std::format(R"({{"option": "{}", "custom": "{}", "set": {} }})", curitem, sc(std::any_cast(VAL))->toString(), VAR->m_bSetByUser); } return "invalid type (internal error)"; @@ -1587,7 +1591,7 @@ static std::string dispatchPlugin(eHyprCtlOutputFormat format, std::string reque "version": "{}", "description": "{}" }},)#", - escapeJSONStrings(p->m_name), escapeJSONStrings(p->m_author), (uintptr_t)p->m_handle, escapeJSONStrings(p->m_version), escapeJSONStrings(p->m_description)); + escapeJSONStrings(p->m_name), escapeJSONStrings(p->m_author), rc(p->m_handle), escapeJSONStrings(p->m_version), escapeJSONStrings(p->m_description)); } trimTrailingComma(result); result += "]"; @@ -1596,7 +1600,7 @@ static std::string dispatchPlugin(eHyprCtlOutputFormat format, std::string reque return "no plugins loaded"; for (auto const& p : PLUGINS) { - result += std::format("\nPlugin {} by {}:\n\tHandle: {:x}\n\tVersion: {}\n\tDescription: {}\n", p->m_name, p->m_author, (uintptr_t)p->m_handle, p->m_version, + result += std::format("\nPlugin {} by {}:\n\tHandle: {:x}\n\tVersion: {}\n\tDescription: {}\n", p->m_name, p->m_author, rc(p->m_handle), p->m_version, p->m_description); } } @@ -1659,7 +1663,7 @@ static std::string dispatchNotify(eHyprCtlOutputFormat format, std::string reque const auto MESSAGE = vars.join(" ", msgidx); - g_pHyprNotificationOverlay->addNotification(MESSAGE, color, time, (eIcons)icon, fontsize); + g_pHyprNotificationOverlay->addNotification(MESSAGE, color, time, sc(icon), fontsize); return "ok"; } @@ -1937,7 +1941,7 @@ static int hyprCtlFDTick(int fd, uint32_t mask, void* data) { sockaddr_in clientAddress; socklen_t clientSize = sizeof(clientAddress); - const auto ACCEPTEDCONNECTION = accept4(g_pHyprCtl->m_socketFD.get(), (sockaddr*)&clientAddress, &clientSize, SOCK_CLOEXEC); + const auto ACCEPTEDCONNECTION = accept4(g_pHyprCtl->m_socketFD.get(), rc(&clientAddress), &clientSize, SOCK_CLOEXEC); std::array readBuffer; @@ -2033,7 +2037,7 @@ void CHyprCtl::startHyprCtlSocket() { snprintf(SERVERADDRESS.sun_path, sizeof(SERVERADDRESS.sun_path), "%s", m_socketPath.c_str()); - if (bind(m_socketFD.get(), (sockaddr*)&SERVERADDRESS, SUN_LEN(&SERVERADDRESS)) < 0) { + if (bind(m_socketFD.get(), rc(&SERVERADDRESS), SUN_LEN(&SERVERADDRESS)) < 0) { Debug::log(ERR, "Couldn't start the Hyprland Socket. (2) IPC will not work."); return; } diff --git a/src/debug/HyprDebugOverlay.cpp b/src/debug/HyprDebugOverlay.cpp index 1b6c2f831..4140d1b36 100644 --- a/src/debug/HyprDebugOverlay.cpp +++ b/src/debug/HyprDebugOverlay.cpp @@ -18,7 +18,7 @@ void CHyprMonitorDebugOverlay::renderData(PHLMONITOR pMonitor, float durationUs) m_lastRenderTimes.emplace_back(durationUs / 1000.f); - if (m_lastRenderTimes.size() > (long unsigned int)pMonitor->m_refreshRate) + if (m_lastRenderTimes.size() > sc(pMonitor->m_refreshRate)) m_lastRenderTimes.pop_front(); if (!m_monitor) @@ -33,7 +33,7 @@ void CHyprMonitorDebugOverlay::renderDataNoOverlay(PHLMONITOR pMonitor, float du m_lastRenderTimesNoOverlay.emplace_back(durationUs / 1000.f); - if (m_lastRenderTimesNoOverlay.size() > (long unsigned int)pMonitor->m_refreshRate) + if (m_lastRenderTimesNoOverlay.size() > sc(pMonitor->m_refreshRate)) m_lastRenderTimesNoOverlay.pop_front(); if (!m_monitor) @@ -48,7 +48,7 @@ void CHyprMonitorDebugOverlay::frameData(PHLMONITOR pMonitor) { m_lastFrametimes.emplace_back(std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - m_lastFrame).count() / 1000.f); - if (m_lastFrametimes.size() > (long unsigned int)pMonitor->m_refreshRate) + if (m_lastFrametimes.size() > sc(pMonitor->m_refreshRate)) m_lastFrametimes.pop_front(); m_lastFrame = std::chrono::high_resolution_clock::now(); @@ -59,7 +59,7 @@ void CHyprMonitorDebugOverlay::frameData(PHLMONITOR pMonitor) { // anim data too const auto PMONITORFORTICKS = g_pHyprRenderer->m_mostHzMonitor ? g_pHyprRenderer->m_mostHzMonitor.lock() : g_pCompositor->m_lastMonitor.lock(); if (PMONITORFORTICKS == pMonitor) { - if (m_lastAnimationTicks.size() > (long unsigned int)PMONITORFORTICKS->m_refreshRate) + if (m_lastAnimationTicks.size() > sc(PMONITORFORTICKS->m_refreshRate)) m_lastAnimationTicks.pop_front(); m_lastAnimationTicks.push_back(g_pAnimationManager->m_lastTickTimeMs); @@ -175,7 +175,7 @@ int CHyprMonitorDebugOverlay::draw(int offset) { else cairo_set_source_rgba(g_pDebugOverlay->m_cairo, 1.f, 0.2f, 0.2f, 1.f); - text = std::format("{} FPS", (int)FPS); + text = std::format("{} FPS", sc(FPS)); showText(text.c_str(), 16); cairo_set_source_rgba(g_pDebugOverlay->m_cairo, 1.f, 1.f, 1.f, 1.f); @@ -199,8 +199,8 @@ int CHyprMonitorDebugOverlay::draw(int offset) { cairo_get_current_point(cr, &posX, &posY); g_pHyprRenderer->damageBox(m_lastDrawnBox); - m_lastDrawnBox = {(int)g_pCompositor->m_monitors.front()->m_position.x + MARGIN_LEFT - 1, (int)g_pCompositor->m_monitors.front()->m_position.y + offset + MARGIN_TOP - 1, - (int)maxTextW + 2, posY - offset - MARGIN_TOP + 2}; + m_lastDrawnBox = {sc(g_pCompositor->m_monitors.front()->m_position.x) + MARGIN_LEFT - 1, + sc(g_pCompositor->m_monitors.front()->m_position.y) + offset + MARGIN_TOP - 1, sc(maxTextW) + 2, posY - offset - MARGIN_TOP + 2}; g_pHyprRenderer->damageBox(m_lastDrawnBox); return posY - offset; diff --git a/src/debug/HyprNotificationOverlay.cpp b/src/debug/HyprNotificationOverlay.cpp index 1e244446b..4c3c05209 100644 --- a/src/debug/HyprNotificationOverlay.cpp +++ b/src/debug/HyprNotificationOverlay.cpp @@ -58,7 +58,7 @@ void CHyprNotificationOverlay::dismissNotifications(const int amount) { if (amount == -1) m_notifications.clear(); else { - const int AMT = std::min(amount, static_cast(m_notifications.size())); + const int AMT = std::min(amount, sc(m_notifications.size())); for (int i = 0; i < AMT; ++i) { m_notifications.erase(m_notifications.begin()); @@ -94,7 +94,7 @@ CBox CHyprNotificationOverlay::drawNotifications(PHLMONITOR pMonitor) { for (auto const& notif : m_notifications) { const auto ICONPADFORNOTIF = notif->icon == ICON_NONE ? 0 : ICON_PAD; - const auto FONTSIZE = std::clamp((int)(notif->fontSize * ((pMonitor->m_pixelSize.x * SCALE) / 1920.f)), 8, 40); + const auto FONTSIZE = std::clamp(sc(notif->fontSize * ((pMonitor->m_pixelSize.x * SCALE) / 1920.f)), 8, 40); // first rect (bg, col) const float FIRSTRECTANIMP = @@ -189,7 +189,7 @@ CBox CHyprNotificationOverlay::drawNotifications(PHLMONITOR pMonitor) { // cleanup notifs std::erase_if(m_notifications, [](const auto& notif) { return notif->started.getMillis() > notif->timeMs; }); - return CBox{(int)(pMonitor->m_position.x + pMonitor->m_size.x - maxWidth - 20), (int)pMonitor->m_position.y, (int)maxWidth + 20, (int)offsetY + 10}; + return CBox{sc(pMonitor->m_position.x + pMonitor->m_size.x - maxWidth - 20), sc(pMonitor->m_position.y), sc(maxWidth) + 20, sc(offsetY) + 10}; } void CHyprNotificationOverlay::draw(PHLMONITOR pMonitor) { diff --git a/src/desktop/LayerSurface.cpp b/src/desktop/LayerSurface.cpp index de808e2aa..de38a843d 100644 --- a/src/desktop/LayerSurface.cpp +++ b/src/desktop/LayerSurface.cpp @@ -46,7 +46,8 @@ PHLLS CLayerSurface::create(SP resource) { pLS->m_alpha->setValueAndWarp(0.f); - Debug::log(LOG, "LayerSurface {:x} (namespace {} layer {}) created on monitor {}", (uintptr_t)resource.get(), resource->m_layerNamespace, (int)pLS->m_layer, pMonitor->m_name); + Debug::log(LOG, "LayerSurface {:x} (namespace {} layer {}) created on monitor {}", rc(resource.get()), resource->m_layerNamespace, sc(pLS->m_layer), + pMonitor->m_name); return pLS; } @@ -84,7 +85,7 @@ CLayerSurface::~CLayerSurface() { } void CLayerSurface::onDestroy() { - Debug::log(LOG, "LayerSurface {:x} destroyed", (uintptr_t)m_layerSurface.get()); + Debug::log(LOG, "LayerSurface {:x} destroyed", rc(m_layerSurface.get())); const auto PMONITOR = m_monitor.lock(); @@ -130,7 +131,7 @@ void CLayerSurface::onDestroy() { } void CLayerSurface::onMap() { - Debug::log(LOG, "LayerSurface {:x} mapped", (uintptr_t)m_layerSurface.get()); + Debug::log(LOG, "LayerSurface {:x} mapped", rc(m_layerSurface.get())); m_mapped = true; m_interactivity = m_layerSurface->m_current.interactivity; @@ -196,7 +197,7 @@ void CLayerSurface::onMap() { } void CLayerSurface::onUnmap() { - Debug::log(LOG, "LayerSurface {:x} unmapped", (uintptr_t)m_layerSurface.get()); + Debug::log(LOG, "LayerSurface {:x} unmapped", rc(m_layerSurface.get())); g_pEventManager->postEvent(SHyprIPCEvent{.event = "closelayer", .data = m_layerSurface->m_layerNamespace}); EMIT_HOOK_EVENT("closeLayer", m_self.lock()); @@ -249,8 +250,8 @@ void CLayerSurface::onUnmap() { CBox geomFixed = {m_geometry.x + PMONITOR->m_position.x, m_geometry.y + PMONITOR->m_position.y, m_geometry.width, m_geometry.height}; g_pHyprRenderer->damageBox(geomFixed); - geomFixed = {m_geometry.x + (int)PMONITOR->m_position.x, m_geometry.y + (int)PMONITOR->m_position.y, (int)m_layerSurface->m_surface->m_current.size.x, - (int)m_layerSurface->m_surface->m_current.size.y}; + geomFixed = {m_geometry.x + sc(PMONITOR->m_position.x), m_geometry.y + sc(PMONITOR->m_position.y), sc(m_layerSurface->m_surface->m_current.size.x), + sc(m_layerSurface->m_surface->m_current.size.y)}; g_pHyprRenderer->damageBox(geomFixed); g_pInputManager->simulateMouseMovement(); @@ -596,7 +597,7 @@ int CLayerSurface::popupsCount() { return 0; int no = -1; // we have one dummy - m_popupHead->breadthfirst([](WP p, void* data) { *(int*)data += 1; }, &no); + m_popupHead->breadthfirst([](WP p, void* data) { *sc(data) += 1; }, &no); return no; } diff --git a/src/desktop/Popup.cpp b/src/desktop/Popup.cpp index 2b0fdbf84..7dc8ad533 100644 --- a/src/desktop/Popup.cpp +++ b/src/desktop/Popup.cpp @@ -90,7 +90,7 @@ void CPopup::initAllSignals() { void CPopup::onNewPopup(SP popup) { const auto& POPUP = m_children.emplace_back(CPopup::create(popup, m_self)); POPUP->m_self = POPUP; - Debug::log(LOG, "New popup at {:x}", (uintptr_t)this); + Debug::log(LOG, "New popup at {:x}", rc(this)); } void CPopup::onDestroy() { @@ -104,7 +104,7 @@ void CPopup::onDestroy() { m_wlSurface.reset(); if (m_fadingOut && m_alpha->isBeingAnimated()) { - Debug::log(LOG, "popup {:x}: skipping full destroy, animating", (uintptr_t)this); + Debug::log(LOG, "popup {:x}: skipping full destroy, animating", rc(this)); return; } @@ -112,7 +112,7 @@ void CPopup::onDestroy() { } void CPopup::fullyDestroy() { - Debug::log(LOG, "popup {:x} fully destroying", (uintptr_t)this); + Debug::log(LOG, "popup {:x} fully destroying", rc(this)); g_pHyprRenderer->makeEGLCurrent(); std::erase_if(g_pHyprOpenGL->m_popupFramebuffers, [&](const auto& other) { return other.first.expired() || other.first == m_self; }); @@ -151,7 +151,7 @@ void CPopup::onMap() { m_alpha->setValueAndWarp(0.F); *m_alpha = 1.F; - Debug::log(LOG, "popup {:x}: mapped", (uintptr_t)this); + Debug::log(LOG, "popup {:x}: mapped", rc(this)); } void CPopup::onUnmap() { @@ -164,7 +164,7 @@ void CPopup::onUnmap() { return; } - Debug::log(LOG, "popup {:x}: unmapped", (uintptr_t)this); + Debug::log(LOG, "popup {:x}: unmapped", rc(this)); // if the popup committed a different size right now, we also need to damage the old size. const Vector2D MAX_DAMAGE_SIZE = {std::max(m_lastSize.x, m_resource->m_surface->m_surface->m_current.size.x), @@ -266,7 +266,7 @@ void CPopup::onCommit(bool ignoreSiblings) { } void CPopup::onReposition() { - Debug::log(LOG, "Popup {:x} requests reposition", (uintptr_t)this); + Debug::log(LOG, "Popup {:x} requests reposition", rc(this)); m_requestedReposition = true; diff --git a/src/desktop/WLSurface.cpp b/src/desktop/WLSurface.cpp index d1483db23..d868e1a90 100644 --- a/src/desktop/WLSurface.cpp +++ b/src/desktop/WLSurface.cpp @@ -148,7 +148,7 @@ void CWLSurface::destroy() { m_resource.reset(); - Debug::log(LOG, "CWLSurface {:x} called destroy()", (uintptr_t)this); + Debug::log(LOG, "CWLSurface {:x} called destroy()", rc(this)); } void CWLSurface::init() { @@ -161,7 +161,7 @@ void CWLSurface::init() { m_listeners.destroy = m_resource->m_events.destroy.listen([this] { destroy(); }); - Debug::log(LOG, "CWLSurface {:x} called init()", (uintptr_t)this); + Debug::log(LOG, "CWLSurface {:x} called init()", rc(this)); } PHLWINDOW CWLSurface::getWindow() const { diff --git a/src/desktop/WLSurface.hpp b/src/desktop/WLSurface.hpp index 3aed50461..4d26d5092 100644 --- a/src/desktop/WLSurface.hpp +++ b/src/desktop/WLSurface.hpp @@ -58,7 +58,7 @@ class CWLSurface { // track surface data and avoid dupes float m_lastScaleFloat = 0; int m_lastScaleInt = 0; - wl_output_transform m_lastTransform = (wl_output_transform)-1; + wl_output_transform m_lastTransform = sc(-1); // CWLSurface& operator=(SP pSurface) { diff --git a/src/desktop/Window.cpp b/src/desktop/Window.cpp index a42a27fe9..e9c386ce8 100644 --- a/src/desktop/Window.cpp +++ b/src/desktop/Window.cpp @@ -163,7 +163,7 @@ SBoxExtents CWindow::getFullWindowExtents() { if (!popup->m_wlSurface || !popup->m_wlSurface->resource()) return; - CBox* pSurfaceExtents = (CBox*)data; + CBox* pSurfaceExtents = sc(data); CBox surf = CBox{popup->coordsRelativeToParent(), popup->size()}; pSurfaceExtents->x = std::min(surf.x, pSurfaceExtents->x); pSurfaceExtents->y = std::min(surf.y, pSurfaceExtents->y); @@ -215,7 +215,7 @@ CBox CWindow::getWindowIdealBoundingBoxIgnoreReserved() { POS = PMONITOR->m_position; SIZE = PMONITOR->m_size; - return CBox{(int)POS.x, (int)POS.y, (int)SIZE.x, (int)SIZE.y}; + return CBox{sc(POS.x), sc(POS.y), sc(SIZE.x), sc(SIZE.y)}; } if (DELTALESSTHAN(POS.y - PMONITOR->m_position.y, PMONITOR->m_reservedTopLeft.y, 1)) { @@ -233,7 +233,7 @@ CBox CWindow::getWindowIdealBoundingBoxIgnoreReserved() { SIZE.y += PMONITOR->m_reservedBottomRight.y; } - return CBox{(int)POS.x, (int)POS.y, (int)SIZE.x, (int)SIZE.y}; + return CBox{sc(POS.x), sc(POS.y), sc(SIZE.x), sc(SIZE.y)}; } SBoxExtents CWindow::getWindowExtentsUnified(uint64_t properties) { @@ -450,8 +450,8 @@ void CWindow::moveToWorkspace(PHLWORKSPACE pWorkspace) { g_pCompositor->updateAllWindowsAnimatedDecorationValues(); if (valid(pWorkspace)) { - g_pEventManager->postEvent(SHyprIPCEvent{.event = "movewindow", .data = std::format("{:x},{}", (uintptr_t)this, pWorkspace->m_name)}); - g_pEventManager->postEvent(SHyprIPCEvent{.event = "movewindowv2", .data = std::format("{:x},{},{}", (uintptr_t)this, pWorkspace->m_id, pWorkspace->m_name)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "movewindow", .data = std::format("{:x},{}", rc(this), pWorkspace->m_name)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "movewindowv2", .data = std::format("{:x},{},{}", rc(this), pWorkspace->m_id, pWorkspace->m_name)}); EMIT_HOOK_EVENT("moveWindow", (std::vector{m_self.lock(), pWorkspace})); } @@ -603,7 +603,7 @@ void CWindow::onBorderAngleAnimEnd(WP pav) { if (PAV->getStyle() != "loop" || !PAV->enabled()) return; - const auto PANIMVAR = dynamic_cast*>(PAV.get()); + const auto PANIMVAR = dc*>(PAV.get()); PANIMVAR->setCallbackOnEnd(nullptr); // we remove the callback here because otherwise setvalueandwarp will recurse this @@ -785,7 +785,7 @@ void CWindow::applyDynamicRule(const SP& r) { const CVarList VARS(r->m_rule, 0, ' '); if (auto search = NWindowProperties::intWindowProperties.find(VARS[1]); search != NWindowProperties::intWindowProperties.end()) { try { - *(search->second(m_self.lock())) = CWindowOverridableVar(Hyprlang::INT(std::stoi(VARS[2])), priority); + *(search->second(m_self.lock())) = CWindowOverridableVar(sc(std::stoi(VARS[2])), priority); } catch (std::exception& e) { Debug::log(ERR, "Rule \"{}\" failed with: {}", r->m_rule, e.what()); } } else if (auto search = NWindowProperties::floatWindowProperties.find(VARS[1]); search != NWindowProperties::floatWindowProperties.end()) { try { @@ -793,7 +793,7 @@ void CWindow::applyDynamicRule(const SP& r) { } catch (std::exception& e) { Debug::log(ERR, "Rule \"{}\" failed with: {}", r->m_rule, e.what()); } } else if (auto search = NWindowProperties::boolWindowProperties.find(VARS[1]); search != NWindowProperties::boolWindowProperties.end()) { try { - *(search->second(m_self.lock())) = CWindowOverridableVar(VARS[2].empty() ? true : (bool)std::stoi(VARS[2]), priority); + *(search->second(m_self.lock())) = CWindowOverridableVar(VARS[2].empty() ? true : sc(std::stoi(VARS[2])), priority); } catch (std::exception& e) { Debug::log(ERR, "Rule \"{}\" failed with: {}", r->m_rule, e.what()); } } break; @@ -852,16 +852,16 @@ bool CWindow::isInCurvedCorner(double x, double y) { double y1 = m_realPosition->value().y + m_realSize->value().y - ROUNDING; if (x < x0 && y < y0) { - return std::pow(x0 - x, ROUNDINGPOWER) + std::pow(y0 - y, ROUNDINGPOWER) > std::pow((double)ROUNDING, ROUNDINGPOWER); + return std::pow(x0 - x, ROUNDINGPOWER) + std::pow(y0 - y, ROUNDINGPOWER) > std::pow(sc(ROUNDING), ROUNDINGPOWER); } if (x > x1 && y < y0) { - return std::pow(x - x1, ROUNDINGPOWER) + std::pow(y0 - y, ROUNDINGPOWER) > std::pow((double)ROUNDING, ROUNDINGPOWER); + return std::pow(x - x1, ROUNDINGPOWER) + std::pow(y0 - y, ROUNDINGPOWER) > std::pow(sc(ROUNDING), ROUNDINGPOWER); } if (x < x0 && y > y1) { - return std::pow(x0 - x, ROUNDINGPOWER) + std::pow(y - y1, ROUNDINGPOWER) > std::pow((double)ROUNDING, ROUNDINGPOWER); + return std::pow(x0 - x, ROUNDINGPOWER) + std::pow(y - y1, ROUNDINGPOWER) > std::pow(sc(ROUNDING), ROUNDINGPOWER); } if (x > x1 && y > y1) { - return std::pow(x - x1, ROUNDINGPOWER) + std::pow(y - y1, ROUNDINGPOWER) > std::pow((double)ROUNDING, ROUNDINGPOWER); + return std::pow(x - x1, ROUNDINGPOWER) + std::pow(y - y1, ROUNDINGPOWER) > std::pow(sc(ROUNDING), ROUNDINGPOWER); } return false; @@ -887,7 +887,7 @@ void CWindow::applyGroupRules() { void CWindow::createGroup() { if (m_groupData.deny) { - Debug::log(LOG, "createGroup: window:{:x},title:{} is denied as a group, ignored", (uintptr_t)this, this->m_title); + Debug::log(LOG, "createGroup: window:{:x},title:{} is denied as a group, ignored", rc(this), this->m_title); return; } @@ -906,14 +906,14 @@ void CWindow::createGroup() { g_pLayoutManager->getCurrentLayout()->recalculateMonitor(monitorID()); g_pCompositor->updateAllWindowsAnimatedDecorationValues(); - g_pEventManager->postEvent(SHyprIPCEvent{.event = "togglegroup", .data = std::format("1,{:x}", (uintptr_t)this)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "togglegroup", .data = std::format("1,{:x}", rc(this))}); } } void CWindow::destroyGroup() { if (m_groupData.pNextWindow == m_self) { if (m_groupRules & GROUP_SET_ALWAYS) { - Debug::log(LOG, "destoryGroup: window:{:x},title:{} has rule [group set always], ignored", (uintptr_t)this, this->m_title); + Debug::log(LOG, "destoryGroup: window:{:x},title:{} has rule [group set always], ignored", rc(this), this->m_title); return; } m_groupData.pNextWindow.reset(); @@ -926,7 +926,7 @@ void CWindow::destroyGroup() { g_pLayoutManager->getCurrentLayout()->recalculateMonitor(monitorID()); g_pCompositor->updateAllWindowsAnimatedDecorationValues(); - g_pEventManager->postEvent(SHyprIPCEvent{.event = "togglegroup", .data = std::format("0,{:x}", (uintptr_t)this)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "togglegroup", .data = std::format("0,{:x}", rc(this))}); return; } @@ -940,7 +940,7 @@ void CWindow::destroyGroup() { curr->setHidden(false); members.push_back(curr); - addresses += std::format("{:x},", (uintptr_t)curr.get()); + addresses += std::format("{:x},", rc(curr.get())); } while (curr.get() != this); for (auto const& w : members) { @@ -1003,7 +1003,7 @@ int CWindow::getGroupSize() { bool CWindow::canBeGroupedInto(PHLWINDOW pWindow) { static auto ALLOWGROUPMERGE = CConfigValue("group:merge_groups_on_drag"); bool isGroup = m_groupData.pNextWindow; - bool disallowDragIntoGroup = g_pInputManager->m_wasDraggingWindow && isGroup && !bool(*ALLOWGROUPMERGE); + bool disallowDragIntoGroup = g_pInputManager->m_wasDraggingWindow && isGroup && !sc(*ALLOWGROUPMERGE); return !g_pKeybindManager->m_groupsLocked // global group lock disengaged && ((m_groupRules & GROUP_INVADE && m_firstMap) // window ignore local group locks, or || (!pWindow->getGroupHead()->m_groupData.locked // target unlocked @@ -1323,7 +1323,7 @@ int CWindow::popupsCount() { return 0; int no = -1; - m_popupHead->breadthfirst([](WP p, void* d) { *((int*)d) += 1; }, &no); + m_popupHead->breadthfirst([](WP p, void* d) { *sc(d) += 1; }, &no); return no; } @@ -1332,7 +1332,7 @@ int CWindow::surfacesCount() { return 1; int no = 0; - m_wlSurface->resource()->breadthfirst([](SP r, const Vector2D& offset, void* d) { *((int*)d) += 1; }, &no); + m_wlSurface->resource()->breadthfirst([](SP r, const Vector2D& offset, void* d) { *sc(d) += 1; }, &no); return no; } @@ -1350,7 +1350,7 @@ bool CWindow::isFullscreen() { } bool CWindow::isEffectiveInternalFSMode(const eFullscreenMode MODE) { - return (eFullscreenMode)std::bit_floor((uint8_t)m_fullscreenState.internal) == MODE; + return sc(std::bit_floor(sc(m_fullscreenState.internal))) == MODE; } WORKSPACEID CWindow::workspaceID() { @@ -1415,7 +1415,7 @@ void CWindow::activate(bool force) { m_isUrgent = true; - g_pEventManager->postEvent(SHyprIPCEvent{.event = "urgent", .data = std::format("{:x}", (uintptr_t)this)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "urgent", .data = std::format("{:x}", rc(this))}); EMIT_HOOK_EVENT("urgent", m_self.lock()); if (!force && (!m_windowData.focusOnActivate.valueOr(*PFOCUSONACTIVATE) || (m_suppressedEvents & SUPPRESS_ACTIVATE_FOCUSONLY) || (m_suppressedEvents & SUPPRESS_ACTIVATE))) @@ -1470,17 +1470,17 @@ void CWindow::onUpdateMeta() { if (m_title != NEWTITLE) { m_title = NEWTITLE; - g_pEventManager->postEvent(SHyprIPCEvent{.event = "windowtitle", .data = std::format("{:x}", (uintptr_t)this)}); - g_pEventManager->postEvent(SHyprIPCEvent{.event = "windowtitlev2", .data = std::format("{:x},{}", (uintptr_t)this, m_title)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "windowtitle", .data = std::format("{:x}", rc(this))}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "windowtitlev2", .data = std::format("{:x},{}", rc(this), m_title)}); EMIT_HOOK_EVENT("windowTitle", m_self.lock()); if (m_self == g_pCompositor->m_lastWindow) { // if it's the active, let's post an event to update others g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindow", .data = m_class + "," + m_title}); - g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindowv2", .data = std::format("{:x}", (uintptr_t)this)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindowv2", .data = std::format("{:x}", rc(this))}); EMIT_HOOK_EVENT("activeWindow", m_self.lock()); } - Debug::log(LOG, "Window {:x} set title to {}", (uintptr_t)this, m_title); + Debug::log(LOG, "Window {:x} set title to {}", rc(this), m_title); doUpdate = true; } @@ -1490,11 +1490,11 @@ void CWindow::onUpdateMeta() { if (m_self == g_pCompositor->m_lastWindow) { // if it's the active, let's post an event to update others g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindow", .data = m_class + "," + m_title}); - g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindowv2", .data = std::format("{:x}", (uintptr_t)this)}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "activewindowv2", .data = std::format("{:x}", rc(this))}); EMIT_HOOK_EVENT("activeWindow", m_self.lock()); } - Debug::log(LOG, "Window {:x} set class to {}", (uintptr_t)this, m_class); + Debug::log(LOG, "Window {:x} set class to {}", rc(this), m_class); doUpdate = true; } @@ -1549,7 +1549,7 @@ void CWindow::onResourceChangeX11() { // could be first assoc and we need to catch the class onUpdateMeta(); - Debug::log(LOG, "xwayland window {:x} -> association to {:x}", (uintptr_t)m_xwaylandSurface.get(), (uintptr_t)m_wlSurface->resource().get()); + Debug::log(LOG, "xwayland window {:x} -> association to {:x}", rc(m_xwaylandSurface.get()), rc(m_wlSurface->resource().get())); } void CWindow::onX11ConfigureRequest(CBox box) { @@ -1766,8 +1766,8 @@ void CWindow::updateX11SurfaceScale() { void CWindow::sendWindowSize(bool force) { const auto PMONITOR = m_monitor.lock(); - Debug::log(TRACE, "sendWindowSize: window:{:x},title:{} with real pos {}, real size {} (force: {})", (uintptr_t)this, this->m_title, m_realPosition->goal(), m_realSize->goal(), - force); + Debug::log(TRACE, "sendWindowSize: window:{:x},title:{} with real pos {}, real size {} (force: {})", rc(this), this->m_title, m_realPosition->goal(), + m_realSize->goal(), force); // TODO: this should be decoupled from setWindowSize IMO const auto REPORTPOS = realToReportPosition(); @@ -1799,7 +1799,7 @@ void CWindow::setContentType(NContentType::eContentType contentType) { m_wlSurface->resource()->m_contentType = PROTO::contentType->getContentType(m_wlSurface->resource()); // else disallow content type change if proto is used? - Debug::log(INFO, "ContentType for window {}", (int)contentType); + Debug::log(INFO, "ContentType for window {}", sc(contentType)); m_wlSurface->resource()->m_contentType->m_value = contentType; } diff --git a/src/desktop/Window.hpp b/src/desktop/Window.hpp index 8f4216725..8f234a4b2 100644 --- a/src/desktop/Window.hpp +++ b/src/desktop/Window.hpp @@ -106,8 +106,8 @@ struct SWindowData { CWindowOverridableVar noFollowMouse = false; CWindowOverridableVar noScreenShare = false; - CWindowOverridableVar borderSize = {std::string("general:border_size"), Hyprlang::INT(0), std::nullopt}; - CWindowOverridableVar rounding = {std::string("decoration:rounding"), Hyprlang::INT(0), std::nullopt}; + CWindowOverridableVar borderSize = {std::string("general:border_size"), sc(0), std::nullopt}; + CWindowOverridableVar rounding = {std::string("decoration:rounding"), sc(0), std::nullopt}; CWindowOverridableVar roundingPower = {std::string("decoration:rounding_power")}; CWindowOverridableVar scrollMouse = {std::string("input:scroll_factor")}; @@ -531,12 +531,12 @@ struct std::formatter : std::formatter { auto format(PHLWINDOW const& w, FormatContext& ctx) const { auto&& out = ctx.out(); if (formatAddressOnly) - return std::format_to(out, "{:x}", (uintptr_t)w.get()); + return std::format_to(out, "{:x}", rc(w.get())); if (!w) return std::format_to(out, "[Window nullptr]"); std::format_to(out, "["); - std::format_to(out, "Window {:x}: title: \"{}\"", (uintptr_t)w.get(), w->m_title); + std::format_to(out, "Window {:x}: title: \"{}\"", rc(w.get()), w->m_title); if (formatWorkspace) std::format_to(out, ", workspace: {}", w->m_workspace ? w->workspaceID() : WORKSPACE_INVALID); if (formatMonitor) diff --git a/src/desktop/Workspace.cpp b/src/desktop/Workspace.cpp index c14d6e38e..1782950a3 100644 --- a/src/desktop/Workspace.cpp +++ b/src/desktop/Workspace.cpp @@ -316,7 +316,7 @@ bool CWorkspace::matchesStaticSelector(const std::string& selector_) { const auto SHOULDBESPECIAL = configStringToInt(prop); - if (SHOULDBESPECIAL && (bool)*SHOULDBESPECIAL != m_isSpecialWorkspace) + if (SHOULDBESPECIAL && sc(*SHOULDBESPECIAL) != m_isSpecialWorkspace) return false; continue; } @@ -410,11 +410,11 @@ bool CWorkspace::matchesStaticSelector(const std::string& selector_) { int count; if (wantsCountGroup) - count = getGroups(wantsOnlyTiled == -1 ? std::nullopt : std::optional((bool)wantsOnlyTiled), + count = getGroups(wantsOnlyTiled == -1 ? std::nullopt : std::optional(sc(wantsOnlyTiled)), wantsOnlyPinned ? std::optional(wantsOnlyPinned) : std::nullopt, wantsCountVisible ? std::optional(wantsCountVisible) : std::nullopt); else - count = getWindows(wantsOnlyTiled == -1 ? std::nullopt : std::optional((bool)wantsOnlyTiled), + count = getWindows(wantsOnlyTiled == -1 ? std::nullopt : std::optional(sc(wantsOnlyTiled)), wantsOnlyPinned ? std::optional(wantsOnlyPinned) : std::nullopt, wantsCountVisible ? std::optional(wantsCountVisible) : std::nullopt); @@ -447,10 +447,10 @@ bool CWorkspace::matchesStaticSelector(const std::string& selector_) { WORKSPACEID count; if (wantsCountGroup) count = - getGroups(wantsOnlyTiled == -1 ? std::nullopt : std::optional((bool)wantsOnlyTiled), + getGroups(wantsOnlyTiled == -1 ? std::nullopt : std::optional(sc(wantsOnlyTiled)), wantsOnlyPinned ? std::optional(wantsOnlyPinned) : std::nullopt, wantsCountVisible ? std::optional(wantsCountVisible) : std::nullopt); else - count = getWindows(wantsOnlyTiled == -1 ? std::nullopt : std::optional((bool)wantsOnlyTiled), + count = getWindows(wantsOnlyTiled == -1 ? std::nullopt : std::optional(sc(wantsOnlyTiled)), wantsOnlyPinned ? std::optional(wantsOnlyPinned) : std::nullopt, wantsCountVisible ? std::optional(wantsCountVisible) : std::nullopt); diff --git a/src/devices/IKeyboard.cpp b/src/devices/IKeyboard.cpp index 0a22eb6ea..4f2281b7f 100644 --- a/src/devices/IKeyboard.cpp +++ b/src/devices/IKeyboard.cpp @@ -120,7 +120,7 @@ void IKeyboard::setKeymap(const SStringRuleNames& rules) { const auto IDX = xkb_map_mod_get_index(m_xkbKeymap, XKB_MOD_NAME_NUM); if (IDX != XKB_MOD_INVALID) - m_modifiersState.locked |= (uint32_t)1 << IDX; + m_modifiersState.locked |= sc(1) << IDX; // 0 to avoid mods getting stuck if depressed during reload updateModifiers(0, 0, m_modifiersState.locked, m_modifiersState.group); @@ -188,7 +188,7 @@ void IKeyboard::updateXKBTranslationState(xkb_keymap* const keymap) { m_xkbSymState = nullptr; if (keymap) { - Debug::log(LOG, "Updating keyboard {:x}'s translation state from a provided keymap", (uintptr_t)this); + Debug::log(LOG, "Updating keyboard {:x}'s translation state from a provided keymap", rc(this)); m_xkbStaticState = xkb_state_new(keymap); m_xkbState = xkb_state_new(keymap); m_xkbSymState = xkb_state_new(keymap); @@ -203,7 +203,7 @@ void IKeyboard::updateXKBTranslationState(xkb_keymap* const keymap) { for (uint32_t i = 0; i < LAYOUTSNUM; ++i) { if (xkb_state_layout_index_is_active(STATE, i, XKB_STATE_LAYOUT_EFFECTIVE) == 1) { - Debug::log(LOG, "Updating keyboard {:x}'s translation state from an active index {}", (uintptr_t)this, i); + Debug::log(LOG, "Updating keyboard {:x}'s translation state from an active index {}", rc(this), i); CVarList keyboardLayouts(m_currentRules.layout, 0, ','); CVarList keyboardModels(m_currentRules.model, 0, ','); @@ -246,7 +246,7 @@ void IKeyboard::updateXKBTranslationState(xkb_keymap* const keymap) { } } - Debug::log(LOG, "Updating keyboard {:x}'s translation state from an unknown index", (uintptr_t)this); + Debug::log(LOG, "Updating keyboard {:x}'s translation state from an unknown index", rc(this)); xkb_rule_names rules = { .rules = m_currentRules.rules.c_str(), @@ -289,7 +289,7 @@ std::optional IKeyboard::getLEDs() { return {}; uint32_t leds = 0; - for (uint32_t i = 0; i < std::min((size_t)LED_COUNT, m_ledIndexes.size()); ++i) { + for (uint32_t i = 0; i < std::min(sc(LED_COUNT), m_ledIndexes.size()); ++i) { if (xkb_state_led_index_is_active(m_xkbState, m_ledIndexes[i])) leds |= (1 << i); } diff --git a/src/devices/Mouse.cpp b/src/devices/Mouse.cpp index b9cf9ffc6..403b0895d 100644 --- a/src/devices/Mouse.cpp +++ b/src/devices/Mouse.cpp @@ -54,9 +54,9 @@ CMouse::CMouse(SP mouse_) : m_mouse(mouse_) { m_listeners.axis = m_mouse->events.axis.listen([this](const Aquamarine::IPointer::SAxisEvent& event) { m_pointerEvents.axis.emit(SAxisEvent{ .timeMs = event.timeMs, - .source = (wl_pointer_axis_source)event.source, - .axis = (wl_pointer_axis)event.axis, - .relativeDirection = (wl_pointer_axis_relative_direction)event.direction, + .source = sc(event.source), + .axis = sc(event.axis), + .relativeDirection = sc(event.direction), .delta = event.delta, .deltaDiscrete = event.discrete, .mouse = true, diff --git a/src/events/Windows.cpp b/src/events/Windows.cpp index 7a741b587..99a9c038e 100644 --- a/src/events/Windows.cpp +++ b/src/events/Windows.cpp @@ -41,7 +41,7 @@ static void setVector2DAnimToMove(WP pav) { if (!PAV) return; - CAnimatedVariable* animvar = dynamic_cast*>(PAV.get()); + CAnimatedVariable* animvar = dc*>(PAV.get()); animvar->setConfig(g_pConfigManager->getAnimationPropertyConfig("windowsMove")); const auto PHLWINDOW = animvar->m_Context.pWindow.lock(); @@ -50,7 +50,7 @@ static void setVector2DAnimToMove(WP pav) { } void Events::listener_mapWindow(void* owner, void* data) { - PHLWINDOW PWINDOW = ((CWindow*)owner)->m_self.lock(); + PHLWINDOW PWINDOW = sc(owner)->m_self.lock(); static auto PINACTIVEALPHA = CConfigValue("decoration:inactive_opacity"); static auto PACTIVEALPHA = CConfigValue("decoration:active_opacity"); @@ -223,7 +223,7 @@ void Events::listener_mapWindow(void* owner, void* data) { try { clientMode = std::stoi(ARGS[1]); } catch (std::exception& e) { clientMode = 0; } - requestedFSState = SFullscreenState{.internal = (eFullscreenMode)internalMode, .client = (eFullscreenMode)clientMode}; + requestedFSState = SFullscreenState{.internal = sc(internalMode), .client = sc(clientMode)}; break; } case CWindowRule::RULE_SUPPRESSEVENT: { @@ -527,13 +527,13 @@ void Events::listener_mapWindow(void* owner, void* data) { if (ONSCREEN) { int borderSize = PWINDOW->getRealBorderSize(); - posX = std::clamp(posX, (int)(PMONITOR->m_reservedTopLeft.x + borderSize), - std::max((int)(PMONITOR->m_size.x - PMONITOR->m_reservedBottomRight.x - PWINDOW->m_realSize->goal().x - borderSize), - (int)(PMONITOR->m_reservedTopLeft.x + borderSize + 1))); + posX = std::clamp(posX, sc(PMONITOR->m_reservedTopLeft.x + borderSize), + std::max(sc(PMONITOR->m_size.x - PMONITOR->m_reservedBottomRight.x - PWINDOW->m_realSize->goal().x - borderSize), + sc(PMONITOR->m_reservedTopLeft.x + borderSize + 1))); - posY = std::clamp(posY, (int)(PMONITOR->m_reservedTopLeft.y + borderSize), - std::max((int)(PMONITOR->m_size.y - PMONITOR->m_reservedBottomRight.y - PWINDOW->m_realSize->goal().y - borderSize), - (int)(PMONITOR->m_reservedTopLeft.y + borderSize + 1))); + posY = std::clamp(posY, sc(PMONITOR->m_reservedTopLeft.y + borderSize), + std::max(sc(PMONITOR->m_size.y - PMONITOR->m_reservedBottomRight.y - PWINDOW->m_realSize->goal().y - borderSize), + sc(PMONITOR->m_reservedTopLeft.y + borderSize + 1))); } Debug::log(LOG, "Rule move, applying to {}", PWINDOW); @@ -631,9 +631,9 @@ void Events::listener_mapWindow(void* owner, void* data) { } if (requestedClientFSMode.has_value() && (PWINDOW->m_suppressedEvents & SUPPRESS_FULLSCREEN)) - requestedClientFSMode = (eFullscreenMode)((uint8_t)requestedClientFSMode.value_or(FSMODE_NONE) & ~(uint8_t)FSMODE_FULLSCREEN); + requestedClientFSMode = sc(sc(requestedClientFSMode.value_or(FSMODE_NONE)) & ~sc(FSMODE_FULLSCREEN)); if (requestedClientFSMode.has_value() && (PWINDOW->m_suppressedEvents & SUPPRESS_MAXIMIZE)) - requestedClientFSMode = (eFullscreenMode)((uint8_t)requestedClientFSMode.value_or(FSMODE_NONE) & ~(uint8_t)FSMODE_MAXIMIZED); + requestedClientFSMode = sc(sc(requestedClientFSMode.value_or(FSMODE_NONE)) & ~sc(FSMODE_MAXIMIZED)); if (!PWINDOW->m_noInitialFocus && (requestedInternalFSMode.has_value() || requestedClientFSMode.has_value() || requestedFSState.has_value())) { // fix fullscreen on requested (basically do a switcheroo) @@ -717,7 +717,7 @@ void Events::listener_mapWindow(void* owner, void* data) { } void Events::listener_unmapWindow(void* owner, void* data) { - PHLWINDOW PWINDOW = ((CWindow*)owner)->m_self.lock(); + PHLWINDOW PWINDOW = sc(owner)->m_self.lock(); Debug::log(LOG, "{:c} unmapped", PWINDOW); @@ -826,7 +826,7 @@ void Events::listener_unmapWindow(void* owner, void* data) { if (PWINDOW == g_pCompositor->m_lastWindow.lock() || !g_pCompositor->m_lastWindow.lock()) { g_pEventManager->postEvent(SHyprIPCEvent{"activewindow", ","}); g_pEventManager->postEvent(SHyprIPCEvent{"activewindowv2", ""}); - EMIT_HOOK_EVENT("activeWindow", (PHLWINDOW) nullptr); + EMIT_HOOK_EVENT("activeWindow", PHLWINDOW{nullptr}); } } else { Debug::log(LOG, "Unmapped was not focused, ignoring a refocus."); @@ -855,7 +855,7 @@ void Events::listener_unmapWindow(void* owner, void* data) { } void Events::listener_commitWindow(void* owner, void* data) { - PHLWINDOW PWINDOW = ((CWindow*)owner)->m_self.lock(); + PHLWINDOW PWINDOW = sc(owner)->m_self.lock(); if (!PWINDOW->m_isX11 && PWINDOW->m_xdgSurface->m_initialCommit) { Vector2D predSize = g_pLayoutManager->getCurrentLayout()->predictSizeForNewWindow(PWINDOW); @@ -922,7 +922,7 @@ void Events::listener_commitWindow(void* owner, void* data) { } void Events::listener_destroyWindow(void* owner, void* data) { - PHLWINDOW PWINDOW = ((CWindow*)owner)->m_self.lock(); + PHLWINDOW PWINDOW = sc(owner)->m_self.lock(); Debug::log(LOG, "{:c} destroyed, queueing.", PWINDOW); @@ -953,7 +953,7 @@ void Events::listener_destroyWindow(void* owner, void* data) { } void Events::listener_activateX11(void* owner, void* data) { - PHLWINDOW PWINDOW = ((CWindow*)owner)->m_self.lock(); + PHLWINDOW PWINDOW = sc(owner)->m_self.lock(); Debug::log(LOG, "X11 Activate request for window {}", PWINDOW); @@ -978,7 +978,7 @@ void Events::listener_activateX11(void* owner, void* data) { } void Events::listener_unmanagedSetGeometry(void* owner, void* data) { - PHLWINDOW PWINDOW = ((CWindow*)owner)->m_self.lock(); + PHLWINDOW PWINDOW = sc(owner)->m_self.lock(); if (!PWINDOW->m_isMapped || !PWINDOW->m_xwaylandSurface || !PWINDOW->m_xwaylandSurface->m_overrideRedirect) return; diff --git a/src/helpers/AsyncDialogBox.cpp b/src/helpers/AsyncDialogBox.cpp index 250b2f5a2..6257dcb0d 100644 --- a/src/helpers/AsyncDialogBox.cpp +++ b/src/helpers/AsyncDialogBox.cpp @@ -44,7 +44,7 @@ CAsyncDialogBox::CAsyncDialogBox(const std::string& title, const std::string& de } static int onFdWrite(int fd, uint32_t mask, void* data) { - auto box = (CAsyncDialogBox*)data; + auto box = sc(data); // lock the box to prevent a UAF auto lock = box->lockSelf(); @@ -68,7 +68,7 @@ void CAsyncDialogBox::onWrite(int fd, uint32_t mask) { } while ((ret = read(m_pipeReadFd.get(), buf.data(), 1023)) > 0) { - m_stdout += std::string_view{(char*)buf.data(), (size_t)ret}; + m_stdout += std::string_view{(buf.data()), sc(ret)}; } // restore the flags (otherwise libwayland won't give us a hangup) diff --git a/src/helpers/Color.cpp b/src/helpers/Color.cpp index 42ae1fd4c..d8f3b02b4 100644 --- a/src/helpers/Color.cpp +++ b/src/helpers/Color.cpp @@ -25,7 +25,7 @@ CHyprColor::CHyprColor(const Hyprgraphics::CColor& color, float a_) : a(a_) { } uint32_t CHyprColor::getAsHex() const { - return (uint32_t)(a * 255.f) * 0x1000000 + (uint32_t)(r * 255.f) * 0x10000 + (uint32_t)(g * 255.f) * 0x100 + (uint32_t)(b * 255.f) * 0x1; + return sc(a * 255.f) * 0x1000000 + sc(r * 255.f) * 0x10000 + sc(g * 255.f) * 0x100 + sc(b * 255.f) * 0x1; } Hyprgraphics::CColor::SSRGB CHyprColor::asRGB() const { diff --git a/src/helpers/Format.cpp b/src/helpers/Format.cpp index c3d721859..e03569a6b 100644 --- a/src/helpers/Format.cpp +++ b/src/helpers/Format.cpp @@ -222,7 +222,7 @@ const SPixelFormat* NFormatUtils::getPixelFormatFromDRM(DRMFormat drm) { const SPixelFormat* NFormatUtils::getPixelFormatFromGL(uint32_t glFormat, uint32_t glType, bool alpha) { for (auto const& fmt : GLES3_FORMATS) { - if (fmt.glFormat == (int)glFormat && fmt.glType == (int)glType && fmt.withAlpha == alpha) + if (fmt.glFormat == sc(glFormat) && fmt.glType == sc(glType) && fmt.withAlpha == alpha) return &fmt; } diff --git a/src/helpers/MiscFunctions.cpp b/src/helpers/MiscFunctions.cpp index 57bb0f9bc..2a1e06719 100644 --- a/src/helpers/MiscFunctions.cpp +++ b/src/helpers/MiscFunctions.cpp @@ -87,7 +87,7 @@ std::string escapeJSONStrings(const std::string& str) { case '\t': oss << "\\t"; break; default: if ('\x00' <= c && c <= '\x1f') { - oss << "\\u" << std::hex << std::setw(4) << std::setfill('0') << static_cast(c); + oss << "\\u" << std::hex << std::setw(4) << std::setfill('0') << sc(c); } else { oss << c; } @@ -213,7 +213,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { if (!PLUSMINUSRESULT.has_value()) return {WORKSPACE_INVALID}; - result.id = (int)PLUSMINUSRESULT.value(); + result.id = sc(PLUSMINUSRESULT.value()); WORKSPACEID remains = result.id; @@ -251,7 +251,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { remains -= 1; // traverse valid workspaces until we reach the remains - if ((size_t)remains < namedWSes.size()) { + if (sc(remains) < namedWSes.size()) { result.id = namedWSes[remains]; } else { remains -= namedWSes.size(); @@ -272,7 +272,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { char walkDir = in[1]; // sanitize. 0 means invalid oob in - - predictedWSID = std::max(predictedWSID, static_cast(0)); + predictedWSID = std::max(predictedWSID, sc(0)); // Count how many invalidWSes are in between (how bad the prediction was) WORKSPACEID beginID = in[1] == '+' ? activeWSID + 1 : predictedWSID; @@ -295,7 +295,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { } currentItem += remains; - currentItem = std::max(currentItem, static_cast(0)); + currentItem = std::max(currentItem, sc(0)); if (currentItem >= namedWSes.size()) { // At the seam between namedWSes and normal WSes. Behave like r+[diff] at imaginary ws 0 size_t diff = currentItem - (namedWSes.size() - 1); @@ -332,7 +332,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { // Need remainingWSes more auto namedWSIdx = namedWSes.size() - remainingWSes; // Sanitze - namedWSIdx = std::clamp(namedWSIdx, static_cast(0), namedWSes.size() - static_cast(1)); + namedWSIdx = std::clamp(namedWSIdx, sc(0), namedWSes.size() - sc(1)); finalWSID = namedWSes[namedWSIdx]; } else { // Couldn't find valid workspace in negative direction, search last first one back up positive direction @@ -376,10 +376,10 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { if (!PLUSMINUSRESULT.has_value()) return {WORKSPACE_INVALID}; - result.id = (int)PLUSMINUSRESULT.value(); + result.id = sc(PLUSMINUSRESULT.value()); // result now has +/- what we should move on mon - int remains = (int)result.id; + int remains = sc(result.id); std::vector validWSes; for (auto const& ws : g_pCompositor->getWorkspaces()) { @@ -400,7 +400,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { // clamp if (currentItem < 0) { currentItem = 0; - } else if (currentItem >= (ssize_t)validWSes.size()) { + } else if (currentItem >= sc(validWSes.size())) { currentItem = validWSes.size() - 1; } } else { @@ -409,7 +409,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { // get the current item WORKSPACEID activeWSID = g_pCompositor->m_lastMonitor->m_activeWorkspace ? g_pCompositor->m_lastMonitor->m_activeWorkspace->m_id : 1; - for (ssize_t i = 0; i < (ssize_t)validWSes.size(); i++) { + for (ssize_t i = 0; i < sc(validWSes.size()); i++) { if (validWSes[i] == activeWSID) { currentItem = i; break; @@ -420,7 +420,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { currentItem += remains; // sanitize - if (currentItem >= (ssize_t)validWSes.size()) { + if (currentItem >= sc(validWSes.size())) { currentItem = currentItem % validWSes.size(); } else if (currentItem < 0) { currentItem = validWSes.size() + currentItem; @@ -436,7 +436,7 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { if (!PLUSMINUSRESULT.has_value()) return {WORKSPACE_INVALID}; - result.id = std::max((int)PLUSMINUSRESULT.value(), 1); + result.id = std::max(sc(PLUSMINUSRESULT.value()), 1); } else { Debug::log(ERR, "Relative workspace on no mon!"); return {WORKSPACE_INVALID}; @@ -642,7 +642,7 @@ std::expected configStringToInt(const std::string& VALUE) a = std::round(std::stof(trim(rolling.substr(0, rolling.find(',')))) * 255.f); } catch (std::exception& e) { return std::unexpected("failed parsing " + VALUEWITHOUTFUNC); } - return a * (Hyprlang::INT)0x1000000 + *r * (Hyprlang::INT)0x10000 + *g * (Hyprlang::INT)0x100 + *b; + return a * sc(0x1000000) + *r * sc(0x10000) + *g * sc(0x100) + *b; } else if (VALUEWITHOUTFUNC.length() == 8) { const auto RGBA = parseHex(VALUEWITHOUTFUNC); @@ -670,7 +670,7 @@ std::expected configStringToInt(const std::string& VALUE) if (!r || !g || !b) return std::unexpected("failed parsing " + VALUEWITHOUTFUNC); - return (Hyprlang::INT)0xFF000000 + *r * (Hyprlang::INT)0x10000 + *g * (Hyprlang::INT)0x100 + *b; + return sc(0xFF000000) + *r * sc(0x10000) + *g * sc(0x100) + *b; } else if (VALUEWITHOUTFUNC.length() == 6) { auto r = parseHex(VALUEWITHOUTFUNC); return r ? *r + 0xFF000000 : r; @@ -717,7 +717,7 @@ Vector2D configStringToVector2D(const std::string& VALUE) { if (std::getline(iss, token)) throw std::invalid_argument("Invalid string format"); - return Vector2D((double)x, (double)y); + return Vector2D(sc(x), sc(y)); } double normalizeAngleRad(double ang) { @@ -910,7 +910,7 @@ std::expected binaryNameForPid(pid_t pid) { sysctl(mib, miblen, &exe, &sz, NULL, 0); std::string path = exe; #else - std::string path = std::format("/proc/{}/exe", (uint64_t)pid); + std::string path = std::format("/proc/{}/exe", sc(pid)); #endif std::error_code ec; diff --git a/src/helpers/Monitor.cpp b/src/helpers/Monitor.cpp index 561eab8c8..37f650a1b 100644 --- a/src/helpers/Monitor.cpp +++ b/src/helpers/Monitor.cpp @@ -213,7 +213,7 @@ void CMonitor::onConnect(bool noRule) { m_damage.setSize(m_transformedSize); - Debug::log(LOG, "Added new monitor with name {} at {:j0} with size {:j0}, pointer {:x}", m_output->name, m_position, m_pixelSize, (uintptr_t)m_output.get()); + Debug::log(LOG, "Added new monitor with name {} at {:j0} with size {:j0}, pointer {:x}", m_output->name, m_position, m_pixelSize, rc(m_output.get())); setupDefaultWS(monitorRule); @@ -577,7 +577,7 @@ bool CMonitor::applyMonitorRule(SMonitorRule* pMonitorRule, bool force) { addBest3Modes([](auto const& a, auto const& b) { if (std::round(a->refreshRate) > std::round(b->refreshRate)) return true; - else if (DELTALESSTHAN((float)a->refreshRate, (float)b->refreshRate, 1.F) && a->pixelSize.x > b->pixelSize.x && a->pixelSize.y > b->pixelSize.y) + else if (DELTALESSTHAN(sc(a->refreshRate), sc(b->refreshRate), 1.F) && a->pixelSize.x > b->pixelSize.x && a->pixelSize.y > b->pixelSize.y) return true; return false; }); @@ -770,7 +770,7 @@ bool CMonitor::applyMonitorRule(SMonitorRule* pMonitorRule, bool force) { bool set10bit = false; - for (auto const& fmt : formats[(int)!RULE->enable10bit]) { + for (auto const& fmt : formats[sc(!RULE->enable10bit)]) { m_output->state->setFormat(fmt.second); m_prevDrmFormat = m_drmFormat; m_drmFormat = fmt.second; @@ -902,8 +902,8 @@ bool CMonitor::applyMonitorRule(SMonitorRule* pMonitorRule, bool force) { // reload to fix mirrors g_pConfigManager->m_wantsMonitorReload = true; - Debug::log(LOG, "Monitor {} data dump: res {:X}@{:.2f}Hz, scale {:.2f}, transform {}, pos {:X}, 10b {}", m_name, m_pixelSize, m_refreshRate, m_scale, (int)m_transform, - m_position, (int)m_enabled10bit); + Debug::log(LOG, "Monitor {} data dump: res {:X}@{:.2f}Hz, scale {:.2f}, transform {}, pos {:X}, 10b {}", m_name, m_pixelSize, m_refreshRate, m_scale, sc(m_transform), + m_position, sc(m_enabled10bit)); EMIT_HOOK_EVENT("monitorLayoutChanged", nullptr); @@ -1003,7 +1003,7 @@ void CMonitor::setupDefaultWS(const SMonitorRule& monitorRule) { auto PNEWWORKSPACE = g_pCompositor->getWorkspaceByID(wsID); - Debug::log(LOG, "New monitor: WORKSPACEID {}, exists: {}", wsID, (int)(PNEWWORKSPACE != nullptr)); + Debug::log(LOG, "New monitor: WORKSPACEID {}, exists: {}", wsID, sc(PNEWWORKSPACE != nullptr)); if (PNEWWORKSPACE) { // workspace exists, move it to the newly connected monitor @@ -1078,7 +1078,7 @@ void CMonitor::setMirror(const std::string& mirrorOf) { setupDefaultWS(RULE); - applyMonitorRule((SMonitorRule*)&RULE, true); // will apply the offset and stuff + applyMonitorRule(const_cast(&RULE), true); // will apply the offset and stuff } else { PHLMONITOR BACKUPMON = nullptr; for (auto const& m : g_pCompositor->m_monitors) { @@ -1469,7 +1469,8 @@ bool CMonitor::attemptDirectScanout() { if (!params.success || !PSURFACE->m_current.texture->m_eglImage /* dmabuf */) return false; - Debug::log(TRACE, "attemptDirectScanout: surface {:x} passed, will attempt, buffer {}", (uintptr_t)PSURFACE.get(), (uintptr_t)PSURFACE->m_current.buffer.m_buffer.get()); + Debug::log(TRACE, "attemptDirectScanout: surface {:x} passed, will attempt, buffer {}", rc(PSURFACE.get()), + rc(PSURFACE->m_current.buffer.m_buffer.get())); auto PBUFFER = PSURFACE->m_current.buffer.m_buffer; @@ -1532,7 +1533,7 @@ bool CMonitor::attemptDirectScanout() { if (m_lastScanout.expired()) { m_lastScanout = PCANDIDATE; - Debug::log(LOG, "Entered a direct scanout to {:x}: \"{}\"", (uintptr_t)PCANDIDATE.get(), PCANDIDATE->m_title); + Debug::log(LOG, "Entered a direct scanout to {:x}: \"{}\"", rc(PCANDIDATE.get()), PCANDIDATE->m_title); } m_scanoutNeedsCursorUpdate = false; diff --git a/src/helpers/SdDaemon.cpp b/src/helpers/SdDaemon.cpp index 1cf15741b..d914eecf9 100644 --- a/src/helpers/SdDaemon.cpp +++ b/src/helpers/SdDaemon.cpp @@ -47,7 +47,7 @@ int NSystemd::sdNotify(int unsetEnvironment, const char* state) { if (unixAddr.sun_path[0] == '@') unixAddr.sun_path[0] = '\0'; - if (connect(fd, (const sockaddr*)&unixAddr, sizeof(struct sockaddr_un)) < 0) + if (connect(fd, rc(&unixAddr), sizeof(struct sockaddr_un)) < 0) return -errno; // arbitrary value which seems to be enough for s-d messages diff --git a/src/helpers/math/Math.cpp b/src/helpers/math/Math.cpp index d111690ec..f927701cc 100644 --- a/src/helpers/math/Math.cpp +++ b/src/helpers/math/Math.cpp @@ -1,4 +1,5 @@ #include "Math.hpp" +#include "../memory/Memory.hpp" Hyprutils::Math::eTransform wlTransformToHyprutils(wl_output_transform t) { switch (t) { @@ -17,7 +18,7 @@ Hyprutils::Math::eTransform wlTransformToHyprutils(wl_output_transform t) { wl_output_transform invertTransform(wl_output_transform tr) { if ((tr & WL_OUTPUT_TRANSFORM_90) && !(tr & WL_OUTPUT_TRANSFORM_FLIPPED)) - tr = (wl_output_transform)(tr ^ (int)WL_OUTPUT_TRANSFORM_180); + tr = sc(tr ^ sc(WL_OUTPUT_TRANSFORM_180)); return tr; } diff --git a/src/hyprerror/HyprError.cpp b/src/hyprerror/HyprError.cpp index 8b1bc0804..f16780fef 100644 --- a/src/hyprerror/HyprError.cpp +++ b/src/hyprerror/HyprError.cpp @@ -51,7 +51,7 @@ void CHyprError::createQueued() { const auto SCALE = PMONITOR->m_scale; - const auto FONTSIZE = std::clamp((int)(10.f * ((PMONITOR->m_pixelSize.x * SCALE) / 1920.f)), 8, 40); + const auto FONTSIZE = std::clamp(sc(10.f * ((PMONITOR->m_pixelSize.x * SCALE) / 1920.f)), 8, 40); const auto CAIROSURFACE = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, PMONITOR->m_pixelSize.x, PMONITOR->m_pixelSize.y); @@ -82,7 +82,7 @@ void CHyprError::createQueued() { const double X = PAD; const double Y = TOPBAR ? PAD : PMONITOR->m_pixelSize.y - HEIGHT - PAD; - m_damageBox = {0, 0, (int)PMONITOR->m_pixelSize.x, (int)HEIGHT + (int)PAD * 2}; + m_damageBox = {0, 0, sc(PMONITOR->m_pixelSize.x), sc(HEIGHT) + sc(PAD) * 2}; cairo_new_sub_path(CAIRO); cairo_arc(CAIRO, X + WIDTH - RADIUS, Y + RADIUS, RADIUS, -90 * DEGREES, 0 * DEGREES); @@ -195,8 +195,8 @@ void CHyprError::draw() { CBox monbox = {0, 0, PMONITOR->m_pixelSize.x, PMONITOR->m_pixelSize.y}; - m_damageBox.x = (int)PMONITOR->m_position.x; - m_damageBox.y = (int)PMONITOR->m_position.y; + m_damageBox.x = sc(PMONITOR->m_position.x); + m_damageBox.y = sc(PMONITOR->m_position.y); if (m_fadeOpacity->isBeingAnimated() || m_monitorChanged) g_pHyprRenderer->damageBox(m_damageBox); diff --git a/src/layout/DwindleLayout.cpp b/src/layout/DwindleLayout.cpp index d844ea41b..78ce1f192 100644 --- a/src/layout/DwindleLayout.cpp +++ b/src/layout/DwindleLayout.cpp @@ -139,8 +139,8 @@ void CHyprDwindleLayout::applyNodeDataToWindow(SDwindleNodeData* pNode, bool for static auto PGAPSINDATA = CConfigValue("general:gaps_in"); static auto PGAPSOUTDATA = CConfigValue("general:gaps_out"); - auto* const PGAPSIN = (CCssGapData*)(PGAPSINDATA.ptr())->getData(); - auto* const PGAPSOUT = (CCssGapData*)(PGAPSOUTDATA.ptr())->getData(); + auto* const PGAPSIN = sc((PGAPSINDATA.ptr())->getData()); + auto* const PGAPSOUT = sc((PGAPSOUTDATA.ptr())->getData()); auto gapsIn = WORKSPACERULE.gapsIn.value_or(*PGAPSIN); auto gapsOut = WORKSPACERULE.gapsOut.value_or(*PGAPSOUT); @@ -179,9 +179,9 @@ void CHyprDwindleLayout::applyNodeDataToWindow(SDwindleNodeData* pNode, bool for } } - const auto GAPOFFSETTOPLEFT = Vector2D((double)(DISPLAYLEFT ? gapsOut.m_left : gapsIn.m_left), (double)(DISPLAYTOP ? gapsOut.m_top : gapsIn.m_top)); + const auto GAPOFFSETTOPLEFT = Vector2D(sc(DISPLAYLEFT ? gapsOut.m_left : gapsIn.m_left), sc(DISPLAYTOP ? gapsOut.m_top : gapsIn.m_top)); - const auto GAPOFFSETBOTTOMRIGHT = Vector2D((double)(DISPLAYRIGHT ? gapsOut.m_right : gapsIn.m_right), (double)(DISPLAYBOTTOM ? gapsOut.m_bottom : gapsIn.m_bottom)); + const auto GAPOFFSETBOTTOMRIGHT = Vector2D(sc(DISPLAYRIGHT ? gapsOut.m_right : gapsIn.m_right), sc(DISPLAYBOTTOM ? gapsOut.m_bottom : gapsIn.m_bottom)); calcPos = calcPos + GAPOFFSETTOPLEFT + ratioPadding / 2; calcSize = calcSize - GAPOFFSETTOPLEFT - GAPOFFSETBOTTOMRIGHT - ratioPadding; diff --git a/src/layout/DwindleLayout.hpp b/src/layout/DwindleLayout.hpp index ca6106054..23f19956a 100644 --- a/src/layout/DwindleLayout.hpp +++ b/src/layout/DwindleLayout.hpp @@ -100,7 +100,7 @@ struct std::formatter : std::formatter { auto out = ctx.out(); if (!node) return std::format_to(out, "[Node nullptr]"); - std::format_to(out, "[Node {:x}: workspace: {}, pos: {:j2}, size: {:j2}", (uintptr_t)node, node->workspaceID, node->box.pos(), node->box.size()); + std::format_to(out, "[Node {:x}: workspace: {}, pos: {:j2}, size: {:j2}", rc(node), node->workspaceID, node->box.pos(), node->box.size()); if (!node->isNode && !node->pWindow.expired()) std::format_to(out, ", window: {:x}", node->pWindow.lock()); return std::format_to(out, "]"); diff --git a/src/layout/IHyprLayout.cpp b/src/layout/IHyprLayout.cpp index aacb9c454..464825c4e 100644 --- a/src/layout/IHyprLayout.cpp +++ b/src/layout/IHyprLayout.cpp @@ -435,7 +435,7 @@ void IHyprLayout::performSnap(Vector2D& sourcePos, Vector2D& sourceSize, PHLWIND const auto WSID = DRAGGINGWINDOW->workspaceID(); const bool HASFULLSCREEN = DRAGGINGWINDOW->m_workspace && DRAGGINGWINDOW->m_workspace->m_hasFullscreenWindow; - const auto* GAPSIN = *SNAPRESPECTGAPS ? (CCssGapData*)PGAPSIN.ptr()->getData() : &GAPSNONE; + const auto* GAPSIN = *SNAPRESPECTGAPS ? sc(PGAPSIN.ptr()->getData()) : &GAPSNONE; const double GAPSX = GAPSIN->m_left + GAPSIN->m_right; const double GAPSY = GAPSIN->m_top + GAPSIN->m_bottom; @@ -497,7 +497,7 @@ void IHyprLayout::performSnap(Vector2D& sourcePos, Vector2D& sourceSize, PHLWIND const auto EXTENTNONE = SBoxExtents{{0, 0}, {0, 0}}; const auto* EXTENTDIFF = *SNAPBORDEROVERLAP ? &EXTENTS : &EXTENTNONE; const auto MON = DRAGGINGWINDOW->m_monitor.lock(); - const auto* GAPSOUT = *SNAPRESPECTGAPS ? (CCssGapData*)PGAPSOUT.ptr()->getData() : &GAPSNONE; + const auto* GAPSOUT = *SNAPRESPECTGAPS ? sc(PGAPSOUT.ptr()->getData()) : &GAPSNONE; SRange monX = {MON->m_position.x + MON->m_reservedTopLeft.x + GAPSOUT->m_left, MON->m_position.x + MON->m_size.x - MON->m_reservedBottomRight.x - GAPSOUT->m_right}; SRange monY = {MON->m_position.y + MON->m_reservedTopLeft.y + GAPSOUT->m_top, MON->m_position.y + MON->m_size.y - MON->m_reservedBottomRight.y - GAPSOUT->m_bottom}; @@ -745,7 +745,7 @@ void IHyprLayout::changeWindowFloatingMode(PHLWINDOW pWindow) { const auto TILED = isWindowTiled(pWindow); // event - g_pEventManager->postEvent(SHyprIPCEvent{"changefloatingmode", std::format("{:x},{}", (uintptr_t)pWindow.get(), (int)TILED)}); + g_pEventManager->postEvent(SHyprIPCEvent{"changefloatingmode", std::format("{:x},{}", rc(pWindow.get()), sc(TILED))}); EMIT_HOOK_EVENT("changeFloatingMode", pWindow); if (!TILED) { diff --git a/src/layout/MasterLayout.cpp b/src/layout/MasterLayout.cpp index 53dc5c2f1..d5a89c94b 100644 --- a/src/layout/MasterLayout.cpp +++ b/src/layout/MasterLayout.cpp @@ -392,7 +392,7 @@ void CHyprMasterLayout::calculateWorkspace(PHLWORKSPACE pWorkspace) { nextX = (WSSIZE.x - WIDTH) / 2; PMASTERNODE->size = Vector2D(WIDTH, WSSIZE.y); - PMASTERNODE->position = WSPOS + Vector2D((double)nextX, 0.0); + PMASTERNODE->position = WSPOS + Vector2D(nextX, 0.0); } else { PMASTERNODE->size = WSSIZE; PMASTERNODE->position = WSPOS; @@ -661,8 +661,8 @@ void CHyprMasterLayout::applyNodeDataToWindow(SMasterNodeData* pNode) { static auto PANIMATE = CConfigValue("misc:animate_manual_resizes"); static auto PGAPSINDATA = CConfigValue("general:gaps_in"); static auto PGAPSOUTDATA = CConfigValue("general:gaps_out"); - auto* PGAPSIN = (CCssGapData*)(PGAPSINDATA.ptr())->getData(); - auto* PGAPSOUT = (CCssGapData*)(PGAPSOUTDATA.ptr())->getData(); + auto* PGAPSIN = sc((PGAPSINDATA.ptr())->getData()); + auto* PGAPSOUT = sc((PGAPSOUTDATA.ptr())->getData()); auto gapsIn = WORKSPACERULE.gapsIn.value_or(*PGAPSIN); auto gapsOut = WORKSPACERULE.gapsOut.value_or(*PGAPSOUT); @@ -680,9 +680,9 @@ void CHyprMasterLayout::applyNodeDataToWindow(SMasterNodeData* pNode) { auto calcPos = PWINDOW->m_position; auto calcSize = PWINDOW->m_size; - const auto OFFSETTOPLEFT = Vector2D((double)(DISPLAYLEFT ? gapsOut.m_left : gapsIn.m_left), (double)(DISPLAYTOP ? gapsOut.m_top : gapsIn.m_top)); + const auto OFFSETTOPLEFT = Vector2D(sc(DISPLAYLEFT ? gapsOut.m_left : gapsIn.m_left), sc(DISPLAYTOP ? gapsOut.m_top : gapsIn.m_top)); - const auto OFFSETBOTTOMRIGHT = Vector2D((double)(DISPLAYRIGHT ? gapsOut.m_right : gapsIn.m_right), (double)(DISPLAYBOTTOM ? gapsOut.m_bottom : gapsIn.m_bottom)); + const auto OFFSETBOTTOMRIGHT = Vector2D(sc(DISPLAYRIGHT ? gapsOut.m_right : gapsIn.m_right), sc(DISPLAYBOTTOM ? gapsOut.m_bottom : gapsIn.m_bottom)); calcPos = calcPos + OFFSETTOPLEFT; calcSize = calcSize - OFFSETTOPLEFT - OFFSETBOTTOMRIGHT; @@ -1382,10 +1382,10 @@ void CHyprMasterLayout::runOrientationCycle(SLayoutMessageHeader& header, CVarLi } } - if (nextOrPrev >= (int)cycle.size()) - nextOrPrev = nextOrPrev % (int)cycle.size(); + if (nextOrPrev >= sc(cycle.size())) + nextOrPrev = nextOrPrev % sc(cycle.size()); else if (nextOrPrev < 0) - nextOrPrev = cycle.size() + (nextOrPrev % (int)cycle.size()); + nextOrPrev = cycle.size() + (nextOrPrev % sc(cycle.size())); PWORKSPACEDATA->orientation = cycle.at(nextOrPrev); recalculateMonitor(header.pWindow->monitorID()); @@ -1393,7 +1393,7 @@ void CHyprMasterLayout::runOrientationCycle(SLayoutMessageHeader& header, CVarLi void CHyprMasterLayout::buildOrientationCycleVectorFromEOperation(std::vector& cycle) { for (int i = 0; i <= ORIENTATION_CENTER; ++i) { - cycle.push_back((eOrientation)i); + cycle.push_back(sc(i)); } } diff --git a/src/layout/MasterLayout.hpp b/src/layout/MasterLayout.hpp index 20743690e..4da31a8d1 100644 --- a/src/layout/MasterLayout.hpp +++ b/src/layout/MasterLayout.hpp @@ -100,7 +100,7 @@ struct std::formatter : std::formatter { auto out = ctx.out(); if (!node) return std::format_to(out, "[Node nullptr]"); - std::format_to(out, "[Node {:x}: workspace: {}, pos: {:j2}, size: {:j2}", (uintptr_t)node, node->workspaceID, node->position, node->size); + std::format_to(out, "[Node {:x}: workspace: {}, pos: {:j2}, size: {:j2}", rc(node), node->workspaceID, node->position, node->size); if (node->isMaster) std::format_to(out, ", master"); if (!node->pWindow.expired()) diff --git a/src/managers/AnimationManager.cpp b/src/managers/AnimationManager.cpp index a5ede0e51..aac4a869d 100644 --- a/src/managers/AnimationManager.cpp +++ b/src/managers/AnimationManager.cpp @@ -228,17 +228,17 @@ void CHyprAnimationManager::tick() { switch (PAV->m_Type) { case AVARTYPE_FLOAT: { - auto pTypedAV = dynamic_cast*>(PAV.get()); + auto pTypedAV = dc*>(PAV.get()); RASSERT(pTypedAV, "Failed to upcast animated float"); handleUpdate(*pTypedAV, warp); } break; case AVARTYPE_VECTOR: { - auto pTypedAV = dynamic_cast*>(PAV.get()); + auto pTypedAV = dc*>(PAV.get()); RASSERT(pTypedAV, "Failed to upcast animated Vector2D"); handleUpdate(*pTypedAV, warp); } break; case AVARTYPE_COLOR: { - auto pTypedAV = dynamic_cast*>(PAV.get()); + auto pTypedAV = dc*>(PAV.get()); RASSERT(pTypedAV, "Failed to upcast animated CHyprColor"); handleUpdate(*pTypedAV, warp); } break; @@ -268,7 +268,7 @@ void CHyprAnimationManager::scheduleTick() { const auto TOPRES = std::clamp(refreshDelayMs - SINCEPRES, 1.1f, 1000.f); // we can't send 0, that will disarm it - m_animationTimer->updateTimeout(std::chrono::milliseconds((int)std::floor(TOPRES))); + m_animationTimer->updateTimeout(std::chrono::milliseconds(sc(std::floor(TOPRES)))); } void CHyprAnimationManager::onTicked() { diff --git a/src/managers/AnimationManager.hpp b/src/managers/AnimationManager.hpp index 07e30c900..b5e420360 100644 --- a/src/managers/AnimationManager.hpp +++ b/src/managers/AnimationManager.hpp @@ -22,7 +22,7 @@ class CHyprAnimationManager : public Hyprutils::Animation::CAnimationManager { constexpr const eAnimatedVarType EAVTYPE = typeToeAnimatedVarType; const auto PAV = makeShared>(); - PAV->create(EAVTYPE, static_cast(this), PAV, v); + PAV->create(EAVTYPE, sc(this), PAV, v); PAV->setConfig(pConfig); PAV->m_Context.eDamagePolicy = policy; diff --git a/src/managers/CursorManager.cpp b/src/managers/CursorManager.cpp index 84e2e6d85..442da4432 100644 --- a/src/managers/CursorManager.cpp +++ b/src/managers/CursorManager.cpp @@ -7,7 +7,7 @@ #include "../helpers/Monitor.hpp" static int cursorAnimTimer(SP self, void* data) { - const auto cursorMgr = reinterpret_cast(data); + const auto cursorMgr = sc(data); cursorMgr->tickAnimatedCursor(); return 1; } @@ -22,13 +22,13 @@ static void hcLogger(enum eHyprcursorLogLevel level, char* message) { CCursorBuffer::CCursorBuffer(cairo_surface_t* surf, const Vector2D& size_, const Vector2D& hot_) : m_hotspot(hot_), m_stride(cairo_image_surface_get_stride(surf)) { size = size_; - m_data = std::vector((uint8_t*)cairo_image_surface_get_data(surf), ((uint8_t*)cairo_image_surface_get_data(surf)) + (cairo_image_surface_get_height(surf) * m_stride)); + m_data = std::vector(cairo_image_surface_get_data(surf), cairo_image_surface_get_data(surf) + (cairo_image_surface_get_height(surf) * m_stride)); } CCursorBuffer::CCursorBuffer(const uint8_t* pixelData, const Vector2D& size_, const Vector2D& hot_) : m_hotspot(hot_), m_stride(4 * size_.x) { size = size_; - m_data = std::vector(pixelData, pixelData + ((int)size_.y * m_stride)); + m_data = std::vector(pixelData, pixelData + (sc(size_.y) * m_stride)); } Aquamarine::eBufferCapability CCursorBuffer::caps() { @@ -167,7 +167,7 @@ void CCursorManager::setCursorFromName(const std::string& name) { auto xcursor = m_xcursor->getShape(name, m_size, m_cursorScale); auto& icon = xcursor->images.front(); - auto buf = makeShared((uint8_t*)icon.pixels.data(), icon.size, icon.hotspot); + auto buf = makeShared(rc(icon.pixels.data()), icon.size, icon.hotspot); setCursorBuffer(buf, icon.hotspot / scale, scale); m_currentXcursor = xcursor; @@ -233,18 +233,18 @@ void CCursorManager::tickAnimatedCursor() { if (!m_hyprcursor->valid() && m_currentXcursor->images.size() > 1) { m_currentAnimationFrame++; - if ((size_t)m_currentAnimationFrame >= m_currentXcursor->images.size()) + if (sc(m_currentAnimationFrame) >= m_currentXcursor->images.size()) m_currentAnimationFrame = 0; float scale = std::ceil(m_cursorScale); auto& icon = m_currentXcursor->images.at(m_currentAnimationFrame); - auto buf = makeShared((uint8_t*)icon.pixels.data(), icon.size, icon.hotspot); + auto buf = makeShared(rc(icon.pixels.data()), icon.size, icon.hotspot); setCursorBuffer(buf, icon.hotspot / scale, scale); setAnimationTimer(m_currentAnimationFrame, m_currentXcursor->images[m_currentAnimationFrame].delay); } else if (m_currentCursorShapeData.images.size() > 1) { m_currentAnimationFrame++; - if ((size_t)m_currentAnimationFrame >= m_currentCursorShapeData.images.size()) + if (sc(m_currentAnimationFrame) >= m_currentCursorShapeData.images.size()) m_currentAnimationFrame = 0; auto hotspot = @@ -281,7 +281,7 @@ void CCursorManager::setXWaylandCursor() { auto xcursor = m_xcursor->getShape("left_ptr", m_size, 1); auto& icon = xcursor->images.front(); - g_pXWayland->setCursor((uint8_t*)icon.pixels.data(), icon.size.x * 4, icon.size, icon.hotspot); + g_pXWayland->setCursor(rc(icon.pixels.data()), icon.size.x * 4, icon.size, icon.hotspot); } } diff --git a/src/managers/DonationNagManager.cpp b/src/managers/DonationNagManager.cpp index 249fbdcf5..826439b2c 100644 --- a/src/managers/DonationNagManager.cpp +++ b/src/managers/DonationNagManager.cpp @@ -69,7 +69,7 @@ CDonationNagManager::CDonationNagManager() { // don't nag if the last nag was less than a month ago. This is // mostly for first-time nags, as other nags happen in specific time frames shorter than a month if (EPOCH - state.epoch < MONTH_IN_SECONDS) { - Debug::log(LOG, "DonationNag: last nag was {} days ago, too early for a nag.", (int)std::round((EPOCH - state.epoch) / (double)DAY_IN_SECONDS)); + Debug::log(LOG, "DonationNag: last nag was {} days ago, too early for a nag.", sc(std::round((EPOCH - state.epoch) / sc(DAY_IN_SECONDS)))); return; } diff --git a/src/managers/EventManager.cpp b/src/managers/EventManager.cpp index e0d8704ba..c4c6c5d78 100644 --- a/src/managers/EventManager.cpp +++ b/src/managers/EventManager.cpp @@ -26,7 +26,7 @@ CEventManager::CEventManager() : m_socketFD(socket(AF_UNIX, SOCK_STREAM | SOCK_C strncpy(SERVERADDRESS.sun_path, PATH.c_str(), sizeof(SERVERADDRESS.sun_path) - 1); - if (bind(m_socketFD.get(), (sockaddr*)&SERVERADDRESS, SUN_LEN(&SERVERADDRESS)) < 0) { + if (bind(m_socketFD.get(), rc(&SERVERADDRESS), SUN_LEN(&SERVERADDRESS)) < 0) { Debug::log(ERR, "Couldn't bind the Hyprland Socket 2. (3) IPC will not work."); return; } @@ -70,7 +70,7 @@ int CEventManager::onServerEvent(int fd, uint32_t mask) { sockaddr_in clientAddress; socklen_t clientSize = sizeof(clientAddress); - CFileDescriptor ACCEPTEDCONNECTION{accept4(m_socketFD.get(), (sockaddr*)&clientAddress, &clientSize, SOCK_CLOEXEC | SOCK_NONBLOCK)}; + CFileDescriptor ACCEPTEDCONNECTION{accept4(m_socketFD.get(), rc(&clientAddress), &clientSize, SOCK_CLOEXEC | SOCK_NONBLOCK)}; if (!ACCEPTEDCONNECTION.isValid()) { if (errno != EAGAIN) { Debug::log(ERR, "Socket2 failed receiving connection, errno: {}", errno); diff --git a/src/managers/HookSystemManager.cpp b/src/managers/HookSystemManager.cpp index 2f1f3a27c..a5623f08b 100644 --- a/src/managers/HookSystemManager.cpp +++ b/src/managers/HookSystemManager.cpp @@ -62,7 +62,7 @@ void CHookSystemManager::emit(std::vector* const callbacks, SCal } catch (std::exception& e) { // TODO: this works only once...? faultyHandles.push_back(cb.handle); - Debug::log(ERR, "[hookSystem] Hook from plugin {:x} caused a SIGSEGV, queueing for unloading.", (uintptr_t)cb.handle); + Debug::log(ERR, "[hookSystem] Hook from plugin {:x} caused a SIGSEGV, queueing for unloading.", rc(cb.handle)); } } diff --git a/src/managers/KeybindManager.cpp b/src/managers/KeybindManager.cpp index 64180e282..bb1222adb 100644 --- a/src/managers/KeybindManager.cpp +++ b/src/managers/KeybindManager.cpp @@ -779,7 +779,7 @@ SDispatchResult CKeybindManager::handleKeybinds(const uint32_t modmask, const SP // call the dispatcher Debug::log(LOG, "Keybind triggered, calling dispatcher ({}, {}, {}, {})", modmask, key.keyName, key.keysym, DISPATCHER->first); - m_passPressed = (int)pressed; + m_passPressed = sc(pressed); // if the dispatchers says to pass event then we will if (k->handler == "mouse") @@ -942,7 +942,7 @@ uint64_t CKeybindManager::spawnWithRules(std::string args, PHLWORKSPACE pInitial const auto RULESLIST = CVarList(RULES, 0, ';'); for (auto const& r : RULESLIST) { - g_pConfigManager->addExecRule({r, (unsigned long)PROC}); + g_pConfigManager->addExecRule({r, sc(PROC)}); } Debug::log(LOG, "Applied {} rule arguments for exec.", RULESLIST.size()); @@ -1374,8 +1374,8 @@ SDispatchResult CKeybindManager::fullscreenStateActive(std::string args) { clientMode = std::stoi(ARGS[1]); } catch (std::exception& e) { clientMode = -1; } - const SFullscreenState STATE = SFullscreenState{.internal = (internalMode != -1 ? (eFullscreenMode)internalMode : PWINDOW->m_fullscreenState.internal), - .client = (clientMode != -1 ? (eFullscreenMode)clientMode : PWINDOW->m_fullscreenState.client)}; + const SFullscreenState STATE = SFullscreenState{.internal = (internalMode != -1 ? sc(internalMode) : PWINDOW->m_fullscreenState.internal), + .client = (clientMode != -1 ? sc(clientMode) : PWINDOW->m_fullscreenState.client)}; if (internalMode != -1 && clientMode != -1 && PWINDOW->m_fullscreenState.internal == STATE.internal && PWINDOW->m_fullscreenState.client == STATE.client) g_pCompositor->setWindowFullscreenState(PWINDOW, SFullscreenState{.internal = FSMODE_NONE, .client = FSMODE_NONE}); @@ -1685,9 +1685,9 @@ SDispatchResult CKeybindManager::moveActiveTo(std::string args) { const auto BORDERSIZE = PLASTWINDOW->getRealBorderSize(); static auto PGAPSCUSTOMDATA = CConfigValue("general:float_gaps"); static auto PGAPSOUTDATA = CConfigValue("general:gaps_out"); - auto* PGAPSOUT = (CCssGapData*)PGAPSCUSTOMDATA.ptr()->getData(); + auto* PGAPSOUT = sc(PGAPSCUSTOMDATA.ptr()->getData()); if (PGAPSOUT->m_left < 0 || PGAPSOUT->m_right < 0 || PGAPSOUT->m_top < 0 || PGAPSOUT->m_bottom < 0) - PGAPSOUT = (CCssGapData*)PGAPSOUTDATA.ptr()->getData(); + PGAPSOUT = sc(PGAPSOUTDATA.ptr()->getData()); switch (arg) { case 'l': vPosx = PMONITOR->m_reservedTopLeft.x + BORDERSIZE + PMONITOR->m_position.x + PGAPSOUT->m_left; break; @@ -2545,7 +2545,7 @@ SDispatchResult CKeybindManager::sendshortcut(std::string args) { return {.success = false, .error = "sendshortcut: no kb"}; } - const auto KEYPAIRSTRING = std::format("{}{}", (uintptr_t)KB.get(), KEY); + const auto KEYPAIRSTRING = std::format("{}{}", rc(KB.get()), KEY); if (!g_pKeybindManager->m_keyToCodeCache.contains(KEYPAIRSTRING)) { xkb_keymap* km = KB->m_xkbKeymap; @@ -2790,7 +2790,7 @@ SDispatchResult CKeybindManager::pinActive(std::string args) { PWORKSPACE->m_lastFocusedWindow = g_pCompositor->vectorToWindowUnified(g_pInputManager->getMouseCoordsInternal(), RESERVED_EXTENTS | INPUT_EXTENTS); - g_pEventManager->postEvent(SHyprIPCEvent{"pin", std::format("{:x},{}", (uintptr_t)PWINDOW.get(), (int)PWINDOW->m_pinned)}); + g_pEventManager->postEvent(SHyprIPCEvent{"pin", std::format("{:x},{}", rc(PWINDOW.get()), sc(PWINDOW->m_pinned))}); EMIT_HOOK_EVENT("pin", PWINDOW); return {}; @@ -2941,7 +2941,7 @@ void CKeybindManager::moveWindowIntoGroup(PHLWINDOW pWindow, PHLWINDOW pWindowIn g_pCompositor->focusWindow(pWindow); pWindow->warpCursor(); - g_pEventManager->postEvent(SHyprIPCEvent{"moveintogroup", std::format("{:x}", (uintptr_t)pWindow.get())}); + g_pEventManager->postEvent(SHyprIPCEvent{"moveintogroup", std::format("{:x}", rc(pWindow.get()))}); } void CKeybindManager::moveWindowOutOfGroup(PHLWINDOW pWindow, const std::string& dir) { @@ -2982,7 +2982,7 @@ void CKeybindManager::moveWindowOutOfGroup(PHLWINDOW pWindow, const std::string& PWINDOWPREV->warpCursor(); } - g_pEventManager->postEvent(SHyprIPCEvent{"moveoutofgroup", std::format("{:x}", (uintptr_t)pWindow.get())}); + g_pEventManager->postEvent(SHyprIPCEvent{"moveoutofgroup", std::format("{:x}", rc(pWindow.get()))}); } SDispatchResult CKeybindManager::moveIntoGroup(std::string args) { @@ -3097,7 +3097,7 @@ SDispatchResult CKeybindManager::moveWindowOrGroup(std::string args) { } SDispatchResult CKeybindManager::setIgnoreGroupLock(std::string args) { - static auto PIGNOREGROUPLOCK = (Hyprlang::INT* const*)g_pConfigManager->getConfigValuePtr("binds:ignore_group_lock"); + static auto PIGNOREGROUPLOCK = rc(g_pConfigManager->getConfigValuePtr("binds:ignore_group_lock")); if (args == "toggle") **PIGNOREGROUPLOCK = !**PIGNOREGROUPLOCK; @@ -3207,17 +3207,17 @@ SDispatchResult CKeybindManager::setProp(std::string args) { CWindowOverridableVar(SAlphaValue{std::stof(VAL), PWINDOW->m_windowData.alphaFullscreen.valueOrDefault().overridden}, PRIORITY_SET_PROP); } else if (PROP == "alphaoverride") { PWINDOW->m_windowData.alpha = - CWindowOverridableVar(SAlphaValue{PWINDOW->m_windowData.alpha.valueOrDefault().alpha, (bool)configStringToInt(VAL).value_or(0)}, PRIORITY_SET_PROP); + CWindowOverridableVar(SAlphaValue{PWINDOW->m_windowData.alpha.valueOrDefault().alpha, sc(configStringToInt(VAL).value_or(0))}, PRIORITY_SET_PROP); } else if (PROP == "alphainactiveoverride") { PWINDOW->m_windowData.alphaInactive = - CWindowOverridableVar(SAlphaValue{PWINDOW->m_windowData.alphaInactive.valueOrDefault().alpha, (bool)configStringToInt(VAL).value_or(0)}, PRIORITY_SET_PROP); + CWindowOverridableVar(SAlphaValue{PWINDOW->m_windowData.alphaInactive.valueOrDefault().alpha, sc(configStringToInt(VAL).value_or(0))}, PRIORITY_SET_PROP); } else if (PROP == "alphafullscreenoverride") { PWINDOW->m_windowData.alphaFullscreen = - CWindowOverridableVar(SAlphaValue{PWINDOW->m_windowData.alphaFullscreen.valueOrDefault().alpha, (bool)configStringToInt(VAL).value_or(0)}, PRIORITY_SET_PROP); + CWindowOverridableVar(SAlphaValue{PWINDOW->m_windowData.alphaFullscreen.valueOrDefault().alpha, sc(configStringToInt(VAL).value_or(0))}, PRIORITY_SET_PROP); } else if (PROP == "activebordercolor" || PROP == "inactivebordercolor") { CGradientValueData colorData = {}; if (vars.size() > 4) { - for (int i = 3; i < static_cast(vars.size()); ++i) { + for (int i = 3; i < sc(vars.size()); ++i) { const auto TOKEN = vars[i]; if (TOKEN.ends_with("deg")) colorData.m_angle = std::stoi(TOKEN.substr(0, TOKEN.size() - 3)) * (PI / 180.0); @@ -3246,7 +3246,7 @@ SDispatchResult CKeybindManager::setProp(std::string args) { else if (VAL == "unset") pWindowDataElement->unset(PRIORITY_SET_PROP); else - *pWindowDataElement = CWindowOverridableVar((bool)configStringToInt(VAL).value_or(0), PRIORITY_SET_PROP); + *pWindowDataElement = CWindowOverridableVar(sc(configStringToInt(VAL).value_or(0)), PRIORITY_SET_PROP); } else if (auto search = NWindowProperties::intWindowProperties.find(PROP); search != NWindowProperties::intWindowProperties.end()) { if (VAL == "unset") search->second(PWINDOW)->unset(PRIORITY_SET_PROP); @@ -3254,7 +3254,7 @@ SDispatchResult CKeybindManager::setProp(std::string args) { const Hyprlang::INT V = std::stoi(VAL.substr(VAL.find(' '))); search->second(PWINDOW)->increment(V, PRIORITY_SET_PROP); } else if (const auto V = configStringToInt(VAL); V) - *(search->second(PWINDOW)) = CWindowOverridableVar((Hyprlang::INT)*V, PRIORITY_SET_PROP); + *(search->second(PWINDOW)) = CWindowOverridableVar(*V, PRIORITY_SET_PROP); } else if (auto search = NWindowProperties::floatWindowProperties.find(PROP); search != NWindowProperties::floatWindowProperties.end()) { if (VAL == "unset") search->second(PWINDOW)->unset(PRIORITY_SET_PROP); diff --git a/src/managers/LayoutManager.cpp b/src/managers/LayoutManager.cpp index 08bbcf44b..449d17006 100644 --- a/src/managers/LayoutManager.cpp +++ b/src/managers/LayoutManager.cpp @@ -12,7 +12,7 @@ IHyprLayout* CLayoutManager::getCurrentLayout() { void CLayoutManager::switchToLayout(std::string layout) { for (size_t i = 0; i < m_layouts.size(); ++i) { if (m_layouts[i].first == layout) { - if (i == (size_t)m_currentLayoutID) + if (i == sc(m_currentLayoutID)) return; getCurrentLayout()->onDisable(); @@ -31,7 +31,7 @@ bool CLayoutManager::addLayout(const std::string& name, IHyprLayout* layout) { m_layouts.emplace_back(std::make_pair<>(name, layout)); - Debug::log(LOG, "Added new layout {} at {:x}", name, (uintptr_t)layout); + Debug::log(LOG, "Added new layout {} at {:x}", name, rc(layout)); return true; } @@ -45,7 +45,7 @@ bool CLayoutManager::removeLayout(IHyprLayout* layout) { if (m_currentLayoutID == IT - m_layouts.begin()) switchToLayout("dwindle"); - Debug::log(LOG, "Removed a layout {} at {:x}", IT->first, (uintptr_t)layout); + Debug::log(LOG, "Removed a layout {} at {:x}", IT->first, rc(layout)); std::erase(m_layouts, *IT); diff --git a/src/managers/PointerManager.cpp b/src/managers/PointerManager.cpp index 34bf09764..318ec343b 100644 --- a/src/managers/PointerManager.cpp +++ b/src/managers/PointerManager.cpp @@ -502,9 +502,8 @@ SP CPointerManager::renderHWCursorBuffer(SPdmabuf(); auto [data, fmt, size] = buf->beginDataPtr(0); - auto CAIROSURFACE = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, DMABUF.size.x, DMABUF.size.y); - auto CAIRODATASURFACE = - cairo_image_surface_create_for_data((unsigned char*)texData.data(), CAIRO_FORMAT_ARGB32, texture->m_size.x, texture->m_size.y, texture->m_size.x * 4); + auto CAIROSURFACE = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, DMABUF.size.x, DMABUF.size.y); + auto CAIRODATASURFACE = cairo_image_surface_create_for_data(texData.data(), CAIRO_FORMAT_ARGB32, texture->m_size.x, texture->m_size.y, texture->m_size.x * 4); auto CAIRO = cairo_create(CAIROSURFACE); @@ -525,7 +524,7 @@ SP CPointerManager::renderHWCursorBuffer(SP(TR)); // FIXME: this is wrong, and doesn't work for 5, 6 and 7. (flipped + rot) // cba to do it rn, does anyone fucking use that?? @@ -550,7 +549,7 @@ SP CPointerManager::renderHWCursorBuffer(SP(cairo_image_surface_get_height(CAIROSURFACE)) * cairo_image_surface_get_stride(CAIROSURFACE)); cairo_destroy(CAIRO); cairo_surface_destroy(CAIROSURFACE); @@ -664,7 +663,7 @@ CBox CPointerManager::getCursorBoxGlobal() { Vector2D CPointerManager::closestValid(const Vector2D& pos) { static auto PADDING = CConfigValue("cursor:hotspot_padding"); - auto CURSOR_PADDING = std::clamp((int)*PADDING, 0, 100); + auto CURSOR_PADDING = std::clamp(sc(*PADDING), 0, 100); CBox hotBox = {{pos.x - CURSOR_PADDING, pos.y - CURSOR_PADDING}, {2 * CURSOR_PADDING, 2 * CURSOR_PADDING}}; // @@ -809,7 +808,7 @@ void CPointerManager::warpAbsolute(Vector2D abs, SP dev) { switch (dev->getType()) { case HID_TYPE_TABLET: { - CTablet* TAB = reinterpret_cast(dev.get()); + CTablet* TAB = rc(dev.get()); if (!TAB->m_boundOutput.empty()) { mappedArea = outputMappedArea(TAB->m_boundOutput); mappedArea.translate(TAB->m_boundBox.pos()); @@ -826,13 +825,13 @@ void CPointerManager::warpAbsolute(Vector2D abs, SP dev) { break; } case HID_TYPE_TOUCH: { - ITouch* TOUCH = reinterpret_cast(dev.get()); + ITouch* TOUCH = rc(dev.get()); if (!TOUCH->m_boundOutput.empty()) mappedArea = outputMappedArea(TOUCH->m_boundOutput); break; } case HID_TYPE_POINTER: { - IPointer* POINTER = reinterpret_cast(dev.get()); + IPointer* POINTER = rc(dev.get()); if (!POINTER->m_boundOutput.empty()) mappedArea = outputMappedArea(POINTER->m_boundOutput); break; @@ -1118,7 +1117,7 @@ void CPointerManager::setStoredMovement(uint64_t time, const Vector2D& delta, co } void CPointerManager::sendStoredMovement() { - PROTO::relativePointer->sendRelativeMotion((uint64_t)m_storedTime * 1000, m_storedDelta, m_storedUnaccel); + PROTO::relativePointer->sendRelativeMotion(m_storedTime * 1000, m_storedDelta, m_storedUnaccel); m_storedTime = 0; m_storedDelta = Vector2D{}; m_storedUnaccel = Vector2D{}; diff --git a/src/managers/TokenManager.cpp b/src/managers/TokenManager.cpp index 141ea65e6..694830dbe 100644 --- a/src/managers/TokenManager.cpp +++ b/src/managers/TokenManager.cpp @@ -15,9 +15,10 @@ std::string CTokenManager::getRandomUUID() { do { uuid_t uuid_; uuid_generate_random(uuid_); - uuid = std::format("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", (uint16_t)uuid_[0], (uint16_t)uuid_[1], - (uint16_t)uuid_[2], (uint16_t)uuid_[3], (uint16_t)uuid_[4], (uint16_t)uuid_[5], (uint16_t)uuid_[6], (uint16_t)uuid_[7], (uint16_t)uuid_[8], - (uint16_t)uuid_[9], (uint16_t)uuid_[10], (uint16_t)uuid_[11], (uint16_t)uuid_[12], (uint16_t)uuid_[13], (uint16_t)uuid_[14], (uint16_t)uuid_[15]); + uuid = std::format("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", sc(uuid_[0]), sc(uuid_[1]), + sc(uuid_[2]), sc(uuid_[3]), sc(uuid_[4]), sc(uuid_[5]), sc(uuid_[6]), sc(uuid_[7]), + sc(uuid_[8]), sc(uuid_[9]), sc(uuid_[10]), sc(uuid_[11]), sc(uuid_[12]), sc(uuid_[13]), + sc(uuid_[14]), sc(uuid_[15])); } while (m_tokens.contains(uuid)); return uuid; diff --git a/src/managers/XCursorManager.cpp b/src/managers/XCursorManager.cpp index 626c4250d..307cbc84b 100644 --- a/src/managers/XCursorManager.cpp +++ b/src/managers/XCursorManager.cpp @@ -185,15 +185,15 @@ SP CXCursorManager::getShape(std::string const& shape, int size, floa SP CXCursorManager::createCursor(std::string const& shape, void* ximages) { auto xcursor = makeShared(); - XcursorImages* xImages = (XcursorImages*)ximages; + XcursorImages* xImages = sc(ximages); for (int i = 0; i < xImages->nimage; i++) { auto xImage = xImages->images[i]; SXCursorImage image; - image.size = {(int)xImage->width, (int)xImage->height}; - image.hotspot = {(int)xImage->xhot, (int)xImage->yhot}; - image.pixels.resize((size_t)xImage->width * xImage->height); - std::memcpy(image.pixels.data(), xImage->pixels, (size_t)xImage->width * xImage->height * sizeof(uint32_t)); + image.size = {sc(xImage->width), sc(xImage->height)}; + image.hotspot = {sc(xImage->xhot), sc(xImage->yhot)}; + image.pixels.resize(sc(xImage->width) * xImage->height); + std::memcpy(image.pixels.data(), xImage->pixels, sc(xImage->width) * xImage->height * sizeof(uint32_t)); image.delay = xImage->delay; xcursor->images.emplace_back(image); @@ -530,7 +530,7 @@ std::vector> CXCursorManager::loadAllFromDir(std::string const& pa auto const& full = entry.path().string(); using PcloseType = int (*)(FILE*); - const std::unique_ptr f(fopen(full.c_str(), "r"), static_cast(fclose)); + const std::unique_ptr f(fopen(full.c_str(), "r"), fclose); if (!f) continue; diff --git a/src/managers/eventLoop/EventLoopManager.cpp b/src/managers/eventLoop/EventLoopManager.cpp index b9ac7242e..3297d31e8 100644 --- a/src/managers/eventLoop/EventLoopManager.cpp +++ b/src/managers/eventLoop/EventLoopManager.cpp @@ -45,7 +45,7 @@ static int timerWrite(int fd, uint32_t mask, void* data) { } static int aquamarineFDWrite(int fd, uint32_t mask, void* data) { - auto POLLFD = (Aquamarine::SPollFD*)data; + auto POLLFD = sc(data); POLLFD->onSignal(); return 1; } @@ -62,7 +62,7 @@ static int handleWaiterFD(int fd, uint32_t mask, void* data) { } if (mask & WL_EVENT_READABLE) - g_pEventLoopManager->onFdReadable((CEventLoopManager::SReadableWaiter*)data); + g_pEventLoopManager->onFdReadable(sc(data)); return 0; } @@ -129,7 +129,7 @@ static void timespecAddNs(timespec* pTimespec, int64_t delta) { pTimespec->tv_sec += delta_s_high; - pTimespec->tv_nsec += (long)delta_ns_low; + pTimespec->tv_nsec += delta_ns_low; if (pTimespec->tv_nsec >= TIMESPEC_NSEC_PER_SEC) { pTimespec->tv_nsec -= TIMESPEC_NSEC_PER_SEC; ++pTimespec->tv_sec; @@ -181,7 +181,7 @@ void CEventLoopManager::doLater(const std::function& fn) { m_idle.eventSource = wl_event_loop_add_idle( m_wayland.loop, [](void* data) { - auto IDLE = (CEventLoopManager::SIdleData*)data; + auto IDLE = sc(data); auto cpy = IDLE->fns; IDLE->fns.clear(); IDLE->eventSource = nullptr; diff --git a/src/managers/input/IdleInhibitor.cpp b/src/managers/input/IdleInhibitor.cpp index 8c33956b9..82f43f47c 100644 --- a/src/managers/input/IdleInhibitor.cpp +++ b/src/managers/input/IdleInhibitor.cpp @@ -8,7 +8,7 @@ void CInputManager::newIdleInhibitor(std::any inhibitor) { const auto PINHIBIT = m_idleInhibitors.emplace_back(makeUnique()).get(); PINHIBIT->inhibitor = std::any_cast>(inhibitor); - Debug::log(LOG, "New idle inhibitor registered for surface {:x}", (uintptr_t)PINHIBIT->inhibitor->m_surface.get()); + Debug::log(LOG, "New idle inhibitor registered for surface {:x}", rc(PINHIBIT->inhibitor->m_surface.get())); PINHIBIT->inhibitor->m_listeners.destroy = PINHIBIT->inhibitor->m_resource->m_events.destroy.listen([this, PINHIBIT] { std::erase_if(m_idleInhibitors, [PINHIBIT](const auto& other) { return other.get() == PINHIBIT; }); @@ -89,7 +89,7 @@ bool CInputManager::isWindowInhibiting(const PHLWINDOW& w, bool onlyHl) { return; if (WLSurface->visible()) - *(bool*)data = true; + *sc(data) = true; }, &isInhibiting); diff --git a/src/managers/input/InputManager.cpp b/src/managers/input/InputManager.cpp index cbb4c3cc1..f8d2a1603 100644 --- a/src/managers/input/InputManager.cpp +++ b/src/managers/input/InputManager.cpp @@ -54,7 +54,7 @@ CInputManager::CInputManager() { if (wl_resource_get_client(event.pMgr->resource()) != g_pSeatManager->m_state.pointerFocusResource->client()) return; - Debug::log(LOG, "cursorImage request: shape {} -> {}", (uint32_t)event.shape, event.shapeName); + Debug::log(LOG, "cursorImage request: shape {} -> {}", sc(event.shape), event.shapeName); m_cursorSurfaceInfo.wlSurface->unassign(); m_cursorSurfaceInfo.vHotspot = {}; @@ -113,11 +113,11 @@ void CInputManager::onMouseMoved(IPointer::SMotionEvent e) { const auto DELTA = *PNOACCEL == 1 ? unaccel : delta; if (g_pSeatManager->m_isPointerFrameSkipped) - g_pPointerManager->storeMovement((uint64_t)e.timeMs, DELTA, unaccel); + g_pPointerManager->storeMovement(e.timeMs, DELTA, unaccel); else - g_pPointerManager->setStoredMovement((uint64_t)e.timeMs, DELTA, unaccel); + g_pPointerManager->setStoredMovement(e.timeMs, DELTA, unaccel); - PROTO::relativePointer->sendRelativeMotion((uint64_t)e.timeMs * 1000, DELTA, unaccel); + PROTO::relativePointer->sendRelativeMotion(sc(e.timeMs) * 1000, DELTA, unaccel); if (e.mouse) recheckMouseWarpOnMouseInput(); @@ -236,13 +236,13 @@ void CInputManager::mouseMoveUnified(uint32_t time, bool refocus, bool mouse) { g_pCompositor->warpCursorTo(CLOSEST, true); g_pSeatManager->sendPointerMotion(time, CLOSESTLOCAL); - PROTO::relativePointer->sendRelativeMotion((uint64_t)time * 1000, {}, {}); + PROTO::relativePointer->sendRelativeMotion(sc(time) * 1000, {}, {}); } return; } else - Debug::log(ERR, "BUG THIS: Null SURF/CONSTRAINT in mouse refocus. Ignoring constraints. {:x} {:x}", (uintptr_t)SURF.get(), (uintptr_t)CONSTRAINT.get()); + Debug::log(ERR, "BUG THIS: Null SURF/CONSTRAINT in mouse refocus. Ignoring constraints. {:x} {:x}", rc(SURF.get()), rc(CONSTRAINT.get())); } if (PMONITOR != g_pCompositor->m_lastMonitor && (*PMOUSEFOCUSMON || refocus) && m_forcedFocus.expired()) @@ -644,7 +644,7 @@ void CInputManager::processMouseRequest(const CSeatManager::SSetCursorEvent& eve if (!cursorImageUnlocked()) return; - Debug::log(LOG, "cursorImage request: surface {:x}", (uintptr_t)event.surf.get()); + Debug::log(LOG, "cursorImage request: surface {:x}", rc(event.surf.get())); if (event.surf != m_cursorSurfaceInfo.wlSurface->resource()) { m_cursorSurfaceInfo.wlSurface->unassign(); @@ -937,7 +937,7 @@ void CInputManager::newKeyboard(SP keeb) { setupKeyboard(PNEWKEYBOARD); - Debug::log(LOG, "New keyboard created, pointers Hypr: {:x}", (uintptr_t)PNEWKEYBOARD.get()); + Debug::log(LOG, "New keyboard created, pointers Hypr: {:x}", rc(PNEWKEYBOARD.get())); } void CInputManager::newKeyboard(SP keyboard) { @@ -945,7 +945,7 @@ void CInputManager::newKeyboard(SP keyboard) { setupKeyboard(PNEWKEYBOARD); - Debug::log(LOG, "New keyboard created, pointers Hypr: {:x} and AQ: {:x}", (uintptr_t)PNEWKEYBOARD.get(), (uintptr_t)keyboard.get()); + Debug::log(LOG, "New keyboard created, pointers Hypr: {:x} and AQ: {:x}", rc(PNEWKEYBOARD.get()), rc(keyboard.get())); } void CInputManager::newVirtualKeyboard(SP keyboard) { @@ -953,7 +953,7 @@ void CInputManager::newVirtualKeyboard(SP keyboard) setupKeyboard(PNEWKEYBOARD); - Debug::log(LOG, "New virtual keyboard created at {:x}", (uintptr_t)PNEWKEYBOARD.get()); + Debug::log(LOG, "New virtual keyboard created at {:x}", rc(PNEWKEYBOARD.get())); } void CInputManager::setupKeyboard(SP keeb) { @@ -974,7 +974,7 @@ void CInputManager::setupKeyboard(SP keeb) { return; destroyKeyboard(PKEEB); - Debug::log(LOG, "Destroyed keyboard {:x}", (uintptr_t)keeb); + Debug::log(LOG, "Destroyed keyboard {:x}", rc(keeb)); }); keeb->m_keyboardEvents.key.listenStatic([this, keeb = keeb.get()](const IKeyboard::SKeyEvent& event) { @@ -1035,7 +1035,7 @@ void CInputManager::applyConfigToKeyboard(SP pKeyboard) { const auto HASCONFIG = g_pConfigManager->deviceConfigExists(devname); - Debug::log(LOG, "ApplyConfigToKeyboard for \"{}\", hasconfig: {}", devname, (int)HASCONFIG); + Debug::log(LOG, "ApplyConfigToKeyboard for \"{}\", hasconfig: {}", devname, sc(HASCONFIG)); const auto REPEATRATE = g_pConfigManager->getDeviceInt(devname, "repeat_rate", "input:repeat_rate"); const auto REPEATDELAY = g_pConfigManager->getDeviceInt(devname, "repeat_delay", "input:repeat_delay"); @@ -1119,7 +1119,7 @@ void CInputManager::newMouse(SP mouse) { setupMouse(PMOUSE); - Debug::log(LOG, "New mouse created, pointer AQ: {:x}", (uintptr_t)mouse.get()); + Debug::log(LOG, "New mouse created, pointer AQ: {:x}", rc(mouse.get())); } void CInputManager::setupMouse(SP mauz) { @@ -1135,8 +1135,8 @@ void CInputManager::setupMouse(SP mauz) { const auto LIBINPUTDEV = mauz->aq()->getLibinputHandle(); Debug::log(LOG, "New mouse has libinput sens {:.2f} ({:.2f}) with accel profile {} ({})", libinput_device_config_accel_get_speed(LIBINPUTDEV), - libinput_device_config_accel_get_default_speed(LIBINPUTDEV), (int)libinput_device_config_accel_get_profile(LIBINPUTDEV), - (int)libinput_device_config_accel_get_default_profile(LIBINPUTDEV)); + libinput_device_config_accel_get_default_speed(LIBINPUTDEV), sc(libinput_device_config_accel_get_profile(LIBINPUTDEV)), + sc(libinput_device_config_accel_get_default_profile(LIBINPUTDEV))); } g_pPointerManager->attachPointer(mauz); @@ -1223,7 +1223,7 @@ void CInputManager::setPointerConfigs() { const auto TAP_DRAG_LOCK = g_pConfigManager->getDeviceInt(devname, "drag_lock", "input:touchpad:drag_lock"); if (TAP_DRAG_LOCK >= 0 && TAP_DRAG_LOCK <= 2) { - libinput_device_config_tap_set_drag_lock_enabled(LIBINPUTDEV, static_cast(TAP_DRAG_LOCK)); + libinput_device_config_tap_set_drag_lock_enabled(LIBINPUTDEV, sc(TAP_DRAG_LOCK)); } if (libinput_device_config_tap_get_finger_count(LIBINPUTDEV)) // this is for tapping (like on a laptop) @@ -1241,13 +1241,12 @@ void CInputManager::setPointerConfigs() { } if (libinput_device_config_3fg_drag_get_finger_count(LIBINPUTDEV) >= 3) { - const auto DRAG_3FG_STATE = static_cast(g_pConfigManager->getDeviceInt(devname, "drag_3fg", "input:touchpad:drag_3fg")); + const auto DRAG_3FG_STATE = sc(g_pConfigManager->getDeviceInt(devname, "drag_3fg", "input:touchpad:drag_3fg")); libinput_device_config_3fg_drag_set_enabled(LIBINPUTDEV, DRAG_3FG_STATE); } if (libinput_device_config_dwt_is_available(LIBINPUTDEV)) { - const auto DWT = - static_cast(g_pConfigManager->getDeviceInt(devname, "disable_while_typing", "input:touchpad:disable_while_typing") != 0); + const auto DWT = sc(g_pConfigManager->getDeviceInt(devname, "disable_while_typing", "input:touchpad:disable_while_typing") != 0); libinput_device_config_dwt_set_enabled(LIBINPUTDEV, DWT); } @@ -1319,7 +1318,7 @@ static void removeFromHIDs(WP hid) { } void CInputManager::destroyKeyboard(SP pKeyboard) { - Debug::log(LOG, "Keyboard at {:x} removed", (uintptr_t)pKeyboard.get()); + Debug::log(LOG, "Keyboard at {:x} removed", rc(pKeyboard.get())); std::erase_if(m_keyboards, [pKeyboard](const auto& other) { return other == pKeyboard; }); @@ -1343,7 +1342,7 @@ void CInputManager::destroyKeyboard(SP pKeyboard) { } void CInputManager::destroyPointer(SP mouse) { - Debug::log(LOG, "Pointer at {:x} removed", (uintptr_t)mouse.get()); + Debug::log(LOG, "Pointer at {:x} removed", rc(mouse.get())); std::erase_if(m_pointers, [mouse](const auto& other) { return other == mouse; }); @@ -1356,7 +1355,7 @@ void CInputManager::destroyPointer(SP mouse) { } void CInputManager::destroyTouchDevice(SP touch) { - Debug::log(LOG, "Touch device at {:x} removed", (uintptr_t)touch.get()); + Debug::log(LOG, "Touch device at {:x} removed", rc(touch.get())); std::erase_if(m_touches, [touch](const auto& other) { return other == touch; }); @@ -1364,7 +1363,7 @@ void CInputManager::destroyTouchDevice(SP touch) { } void CInputManager::destroyTablet(SP tablet) { - Debug::log(LOG, "Tablet device at {:x} removed", (uintptr_t)tablet.get()); + Debug::log(LOG, "Tablet device at {:x} removed", rc(tablet.get())); std::erase_if(m_tablets, [tablet](const auto& other) { return other == tablet; }); @@ -1372,7 +1371,7 @@ void CInputManager::destroyTablet(SP tablet) { } void CInputManager::destroyTabletTool(SP tool) { - Debug::log(LOG, "Tablet tool at {:x} removed", (uintptr_t)tool.get()); + Debug::log(LOG, "Tablet tool at {:x} removed", rc(tool.get())); std::erase_if(m_tabletTools, [tool](const auto& other) { return other == tool; }); @@ -1380,7 +1379,7 @@ void CInputManager::destroyTabletTool(SP tool) { } void CInputManager::destroyTabletPad(SP pad) { - Debug::log(LOG, "Tablet pad at {:x} removed", (uintptr_t)pad.get()); + Debug::log(LOG, "Tablet pad at {:x} removed", rc(pad.get())); std::erase_if(m_tabletPads, [pad](const auto& other) { return other == pad; }); @@ -1674,7 +1673,7 @@ void CInputManager::newTouchDevice(SP pDevice) { destroyTouchDevice(PDEV); }); - Debug::log(LOG, "New touch device added at {:x}", (uintptr_t)PNEWDEV.get()); + Debug::log(LOG, "New touch device added at {:x}", rc(PNEWDEV.get())); } void CInputManager::setTouchDeviceConfigs(SP dev) { diff --git a/src/managers/input/InputMethodPopup.cpp b/src/managers/input/InputMethodPopup.cpp index 71fdd5a48..27acd08c5 100644 --- a/src/managers/input/InputMethodPopup.cpp +++ b/src/managers/input/InputMethodPopup.cpp @@ -99,7 +99,7 @@ void CInputPopup::updateBox() { if (!cursorRect) { Vector2D coords = OWNER ? OWNER->getSurfaceBoxGlobal().value_or(CBox{0, 0, 500, 500}).pos() : Vector2D{0, 0}; parentBox = {coords, {500, 500}}; - cursorBoxParent = {0, 0, (int)parentBox.w, (int)parentBox.h}; + cursorBoxParent = {0, 0, sc(parentBox.w), sc(parentBox.h)}; } Vector2D currentPopupSize = m_surface->getViewporterCorrectedSize() / m_surface->resource()->m_current.scale; diff --git a/src/managers/input/Swipe.cpp b/src/managers/input/Swipe.cpp index 355ffee3a..1d9b80e20 100644 --- a/src/managers/input/Swipe.cpp +++ b/src/managers/input/Swipe.cpp @@ -67,7 +67,7 @@ void CInputManager::endWorkspaceSwipe() { // commit auto workspaceIDLeft = getWorkspaceIDNameFromString((*PSWIPEUSER ? "r-1" : "m-1")).id; auto workspaceIDRight = getWorkspaceIDNameFromString((*PSWIPEUSER ? "r+1" : "m+1")).id; - const auto SWIPEDISTANCE = std::clamp(*PSWIPEDIST, (int64_t)1LL, (int64_t)UINT32_MAX); + const auto SWIPEDISTANCE = std::clamp(*PSWIPEDIST, sc(1LL), sc(UINT32_MAX)); // If we've been swiping off the right end with PSWIPENEW enabled, there is // no workspace there yet, and we need to choose an ID for a new one now. @@ -213,7 +213,7 @@ void CInputManager::updateWorkspaceSwipe(double delta) { static auto PSWIPEUSER = CConfigValue("gestures:workspace_swipe_use_r"); static auto PWORKSPACEGAP = CConfigValue("general:gaps_workspaces"); - const auto SWIPEDISTANCE = std::clamp(*PSWIPEDIST, (int64_t)1LL, (int64_t)UINT32_MAX); + const auto SWIPEDISTANCE = std::clamp(*PSWIPEDIST, sc(1LL), sc(UINT32_MAX)); const auto XDISTANCE = m_activeSwipe.pMonitor->m_size.x + *PWORKSPACEGAP; const auto YDISTANCE = m_activeSwipe.pMonitor->m_size.y + *PWORKSPACEGAP; const auto ANIMSTYLE = m_activeSwipe.pWorkspaceBegin->m_renderOffset->getStyle(); @@ -234,7 +234,7 @@ void CInputManager::updateWorkspaceSwipe(double delta) { m_activeSwipe.pWorkspaceBegin->m_forceRendering = true; - m_activeSwipe.delta = std::clamp(m_activeSwipe.delta, (double)-SWIPEDISTANCE, (double)SWIPEDISTANCE); + m_activeSwipe.delta = std::clamp(m_activeSwipe.delta, sc(-SWIPEDISTANCE), sc(SWIPEDISTANCE)); if ((m_activeSwipe.pWorkspaceBegin->m_id == workspaceIDLeft && *PSWIPENEW && (m_activeSwipe.delta < 0)) || (m_activeSwipe.delta > 0 && m_activeSwipe.pWorkspaceBegin->getWindows() == 0 && workspaceIDRight <= m_activeSwipe.pWorkspaceBegin->m_id) || diff --git a/src/managers/input/TextInput.cpp b/src/managers/input/TextInput.cpp index c1ce2062a..5da5e47af 100644 --- a/src/managers/input/TextInput.cpp +++ b/src/managers/input/TextInput.cpp @@ -251,7 +251,7 @@ void CTextInput::commitStateToIME(SP ime) { ime->textChangeCause(ZWP_TEXT_INPUT_V3_CHANGE_CAUSE_INPUT_METHOD); if (m_v1Input->m_pendingContentType.isPending) - ime->textContentType((zwpTextInputV3ContentHint)INPUT->m_pendingContentType.hint, (zwpTextInputV3ContentPurpose)INPUT->m_pendingContentType.purpose); + ime->textContentType(sc(INPUT->m_pendingContentType.hint), sc(INPUT->m_pendingContentType.purpose)); } g_pInputManager->m_relay.updateAllPopups(); diff --git a/src/managers/input/Touch.cpp b/src/managers/input/Touch.cpp index 4a67d2f29..9e19c4e80 100644 --- a/src/managers/input/Touch.cpp +++ b/src/managers/input/Touch.cpp @@ -16,7 +16,7 @@ void CInputManager::onTouchDown(ITouch::SDownEvent e) { static auto PSWIPETOUCH = CConfigValue("gestures:workspace_swipe_touch"); static auto PGAPSOUTDATA = CConfigValue("general:gaps_out"); - auto* const PGAPSOUT = (CCssGapData*)(PGAPSOUTDATA.ptr())->getData(); + auto* const PGAPSOUT = sc((PGAPSOUTDATA.ptr())->getData()); // TODO: WORKSPACERULE.gapsOut.value_or() auto gapsOut = *PGAPSOUT; static auto PBORDERSIZE = CConfigValue("general:border_size"); @@ -126,7 +126,7 @@ void CInputManager::onTouchMove(ITouch::SMotionEvent e) { const bool VERTANIMS = ANIMSTYLE == "slidevert" || ANIMSTYLE.starts_with("slidefadevert"); static auto PSWIPEINVR = CConfigValue("gestures:workspace_swipe_touch_invert"); static auto PSWIPEDIST = CConfigValue("gestures:workspace_swipe_distance"); - const auto SWIPEDISTANCE = std::clamp(*PSWIPEDIST, (int64_t)1LL, (int64_t)UINT32_MAX); + const auto SWIPEDISTANCE = std::clamp(*PSWIPEDIST, sc(1LL), sc(UINT32_MAX)); // Handle the workspace swipe if there is one if (m_activeSwipe.initialDirection == -1) { if (*PSWIPEINVR) diff --git a/src/managers/permissions/DynamicPermissionManager.cpp b/src/managers/permissions/DynamicPermissionManager.cpp index 2f4690fc5..3f9d58dd1 100644 --- a/src/managers/permissions/DynamicPermissionManager.cpp +++ b/src/managers/permissions/DynamicPermissionManager.cpp @@ -92,7 +92,7 @@ eDynamicPermissionAllowMode CDynamicPermissionManager::clientPermissionMode(wl_c const auto LOOKUP = binaryNameForWlClient(client); - Debug::log(TRACE, "CDynamicPermissionManager::clientHasPermission: checking permission {} for client {:x} (binary {})", permissionToString(permission), (uintptr_t)client, + Debug::log(TRACE, "CDynamicPermissionManager::clientHasPermission: checking permission {} for client {:x} (binary {})", permissionToString(permission), rc(client), LOOKUP.has_value() ? LOOKUP.value() : "lookup failed: " + LOOKUP.error()); // first, check if we have the client + perm combo in our cache. @@ -174,7 +174,7 @@ eDynamicPermissionAllowMode CDynamicPermissionManager::clientPermissionModeWithS if (lookup.has_value()) binaryName = *lookup; } else - binaryName = specialPidToString((eSpecialPidTypes)pid); + binaryName = specialPidToString(sc(pid)); // first, check if we have the client + perm combo in our cache. auto it = std::ranges::find_if(m_rules, [str, permission, pid](const auto& e) { return e->m_keyString == str && pid && pid == e->m_pid && e->m_type == permission; }); @@ -246,14 +246,14 @@ void CDynamicPermissionManager::askForPermission(wl_client* client, const std::s std::string description = ""; if (binaryPath.empty()) - description = std::format(std::runtime_format(permissionToHumanString(type)), std::format("unknown application (wayland client ID 0x{:x})", (uintptr_t)client)); + description = std::format(std::runtime_format(permissionToHumanString(type)), std::format("unknown application (wayland client ID 0x{:x})", rc(client))); else if (client) { std::string binaryName = binaryPath.contains("/") ? binaryPath.substr(binaryPath.find_last_of('/') + 1) : binaryPath; description = std::format(std::runtime_format(permissionToHumanString(type)), std::format("{} ({})", binaryName, binaryPath)); } else { std::string lookup = ""; if (pid < 0) - lookup = specialPidToString((eSpecialPidTypes)pid); + lookup = specialPidToString(sc(pid)); else { const auto LOOKUP = binaryNameForPid(pid); lookup = LOOKUP.value_or("Unknown"); diff --git a/src/plugins/HookSystem.cpp b/src/plugins/HookSystem.cpp index 906c19859..dccb4cd0b 100644 --- a/src/plugins/HookSystem.cpp +++ b/src/plugins/HookSystem.cpp @@ -33,7 +33,7 @@ CFunctionHook::SInstructionProbe CFunctionHook::getInstructionLenAt(void* start) size_t curOffset = 1; size_t insSize = 0; while (true) { - ud_set_input_buffer(&udis, (uint8_t*)start, curOffset); + ud_set_input_buffer(&udis, sc(start), curOffset); insSize = ud_disassemble(&udis); if (insSize != curOffset) break; @@ -57,7 +57,7 @@ CFunctionHook::SInstructionProbe CFunctionHook::probeMinimumJumpSize(void* start while (size <= min) { // find info about this instruction - auto probe = getInstructionLenAt((uint8_t*)start + size); + auto probe = getInstructionLenAt(sc(start) + size); sizes.push_back(probe.len); size += probe.len; instrs += probe.assembly + "\n"; @@ -70,7 +70,7 @@ CFunctionHook::SAssembly CFunctionHook::fixInstructionProbeRIPCalls(const SInstr SAssembly returns; // analyze the code and fix what we know how to. - uint64_t currentAddress = (uint64_t)m_source; + uint64_t currentAddress = rc(m_source); // actually newline + 1 size_t lastAsmNewline = 0; // needle for destination binary @@ -83,7 +83,7 @@ CFunctionHook::SAssembly CFunctionHook::fixInstructionProbeRIPCalls(const SInstr // copy original bytes to our finalBytes for (size_t i = 0; i < len; ++i) { - finalBytes[currentDestinationOffset + i] = *(char*)(currentAddress + i); + finalBytes[currentDestinationOffset + i] = *rc(currentAddress + i); } std::string code = probe.assembly.substr(lastAsmNewline, probe.assembly.find('\n', lastAsmNewline) - lastAsmNewline); @@ -106,14 +106,14 @@ CFunctionHook::SAssembly CFunctionHook::fixInstructionProbeRIPCalls(const SInstr if (ADDREND == std::string::npos || ADDRSTART == std::string::npos) return {}; - const uint64_t PREDICTEDRIP = (uint64_t)m_trampolineAddr + currentDestinationOffset + len; + const uint64_t PREDICTEDRIP = rc(m_trampolineAddr) + currentDestinationOffset + len; const int32_t NEWRIPOFFSET = DESTINATION - PREDICTEDRIP; size_t ripOffset = 0; // find %rip usage offset from beginning for (int i = len - 4 /* 32-bit */; i > 0; --i) { - if (*(int32_t*)(currentAddress + i) == OFFSET) { + if (*rc(currentAddress + i) == OFFSET) { ripOffset = i; break; } @@ -123,7 +123,7 @@ CFunctionHook::SAssembly CFunctionHook::fixInstructionProbeRIPCalls(const SInstr return {}; // fix offset in the final bytes. This doesn't care about endianness - *(int32_t*)&finalBytes[currentDestinationOffset + ripOffset] = NEWRIPOFFSET; + *rc(&finalBytes[currentDestinationOffset + ripOffset]) = NEWRIPOFFSET; currentDestinationOffset += len; } else { @@ -157,7 +157,7 @@ bool CFunctionHook::hook() { // alloc trampoline const auto MAX_TRAMPOLINE_SIZE = HOOK_TRAMPOLINE_MAX_SIZE; // we will never need more. - m_trampolineAddr = (void*)g_pFunctionHookSystem->getAddressForTrampo(); + m_trampolineAddr = rc(g_pFunctionHookSystem->getAddressForTrampo()); // probe instructions to be trampolin'd SInstructionProbe probe; @@ -186,31 +186,31 @@ bool CFunctionHook::hook() { memcpy(m_originalBytes.data(), m_source, ORIGSIZE); // populate trampoline - memcpy(m_trampolineAddr, PROBEFIXEDASM.bytes.data(), HOOKSIZE); // first, original but fixed func bytes - memcpy((uint8_t*)m_trampolineAddr + HOOKSIZE, PUSH_RAX, sizeof(PUSH_RAX)); // then, pushq %rax - memcpy((uint8_t*)m_trampolineAddr + HOOKSIZE + sizeof(PUSH_RAX), ABSOLUTE_JMP_ADDRESS, sizeof(ABSOLUTE_JMP_ADDRESS)); // then, jump to source + memcpy(m_trampolineAddr, PROBEFIXEDASM.bytes.data(), HOOKSIZE); // first, original but fixed func bytes + memcpy(sc(m_trampolineAddr) + HOOKSIZE, PUSH_RAX, sizeof(PUSH_RAX)); // then, pushq %rax + memcpy(sc(m_trampolineAddr) + HOOKSIZE + sizeof(PUSH_RAX), ABSOLUTE_JMP_ADDRESS, sizeof(ABSOLUTE_JMP_ADDRESS)); // then, jump to source // fixup trampoline addr - *(uint64_t*)((uint8_t*)m_trampolineAddr + TRAMPOLINE_SIZE - sizeof(ABSOLUTE_JMP_ADDRESS) + ABSOLUTE_JMP_ADDRESS_OFFSET) = - (uint64_t)((uint8_t*)m_source + sizeof(ABSOLUTE_JMP_ADDRESS)); + *rc(sc(m_trampolineAddr) + TRAMPOLINE_SIZE - sizeof(ABSOLUTE_JMP_ADDRESS) + ABSOLUTE_JMP_ADDRESS_OFFSET) = + rc(sc(m_source) + sizeof(ABSOLUTE_JMP_ADDRESS)); // make jump to hk const auto PAGESIZE_VAR = sysconf(_SC_PAGE_SIZE); - const uint8_t* PROTSTART = (uint8_t*)m_source - ((uint64_t)m_source % PAGESIZE_VAR); - const size_t PROTLEN = std::ceil((float)(ORIGSIZE + ((uint64_t)m_source - (uint64_t)PROTSTART)) / (float)PAGESIZE_VAR) * PAGESIZE_VAR; - mprotect((uint8_t*)PROTSTART, PROTLEN, PROT_READ | PROT_WRITE | PROT_EXEC); - memcpy((uint8_t*)m_source, ABSOLUTE_JMP_ADDRESS, sizeof(ABSOLUTE_JMP_ADDRESS)); + const uint8_t* PROTSTART = sc(m_source) - (rc(m_source) % PAGESIZE_VAR); + const size_t PROTLEN = std::ceil(sc(ORIGSIZE + (rc(m_source) - rc(PROTSTART))) / sc(PAGESIZE_VAR)) * PAGESIZE_VAR; + mprotect(const_cast(PROTSTART), PROTLEN, PROT_READ | PROT_WRITE | PROT_EXEC); + memcpy(m_source, ABSOLUTE_JMP_ADDRESS, sizeof(ABSOLUTE_JMP_ADDRESS)); // make popq %rax and NOP all remaining - memcpy((uint8_t*)m_source + sizeof(ABSOLUTE_JMP_ADDRESS), POP_RAX, sizeof(POP_RAX)); + memcpy(sc(m_source) + sizeof(ABSOLUTE_JMP_ADDRESS), POP_RAX, sizeof(POP_RAX)); size_t currentOp = sizeof(ABSOLUTE_JMP_ADDRESS) + sizeof(POP_RAX); - memset((uint8_t*)m_source + currentOp, NOP, ORIGSIZE - currentOp); + memset(sc(m_source) + currentOp, NOP, ORIGSIZE - currentOp); // fixup jump addr - *(uint64_t*)((uint8_t*)m_source + ABSOLUTE_JMP_ADDRESS_OFFSET) = (uint64_t)(m_destination); + *rc(sc(m_source) + ABSOLUTE_JMP_ADDRESS_OFFSET) = rc(m_destination); // revert mprot - mprotect((uint8_t*)PROTSTART, PROTLEN, PROT_READ | PROT_EXEC); + mprotect(const_cast(PROTSTART), PROTLEN, PROT_READ | PROT_EXEC); // set original addr to trampo addr m_original = m_trampolineAddr; @@ -232,13 +232,13 @@ bool CFunctionHook::unhook() { return false; // allow write to src - mprotect((uint8_t*)m_source - ((uint64_t)m_source) % sysconf(_SC_PAGE_SIZE), sysconf(_SC_PAGE_SIZE), PROT_READ | PROT_WRITE | PROT_EXEC); + mprotect(sc(m_source) - rc(m_source) % sysconf(_SC_PAGE_SIZE), sysconf(_SC_PAGE_SIZE), PROT_READ | PROT_WRITE | PROT_EXEC); // write back original bytes memcpy(m_source, m_originalBytes.data(), m_hookLen); // revert mprot - mprotect((uint8_t*)m_source - ((uint64_t)m_source) % sysconf(_SC_PAGE_SIZE), sysconf(_SC_PAGE_SIZE), PROT_READ | PROT_EXEC); + mprotect(sc(m_source) - rc(m_source) % sysconf(_SC_PAGE_SIZE), sysconf(_SC_PAGE_SIZE), PROT_READ | PROT_EXEC); // reset vars m_active = false; @@ -352,16 +352,16 @@ uint64_t CHookSystem::getAddressForTrampo() { for (int i = 0; i <= 2; ++i) { const auto PAGEADDR = BASEPAGEADDR + i * PAGESIZE_VAR; - page->addr = (uint64_t)mmap((void*)PAGEADDR, PAGESIZE_VAR, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + page->addr = rc(mmap(rc(PAGEADDR), PAGESIZE_VAR, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); page->len = PAGESIZE_VAR; page->used = 0; Debug::log(LOG, "Attempted to allocate 0x{:x}, got 0x{:x}", PAGEADDR, page->addr); - if (page->addr == (uint64_t)MAP_FAILED) + if (page->addr == rc(MAP_FAILED)) continue; if (page->addr != PAGEADDR && attempt == 0) { - munmap((void*)page->addr, PAGESIZE_VAR); + munmap(rc(page->addr), PAGESIZE_VAR); page->addr = 0; page->len = 0; continue; diff --git a/src/plugins/PluginAPI.cpp b/src/plugins/PluginAPI.cpp index f0d01ea8f..004788b92 100644 --- a/src/plugins/PluginAPI.cpp +++ b/src/plugins/PluginAPI.cpp @@ -94,7 +94,7 @@ APICALL CFunctionHook* HyprlandAPI::createFunctionHook(HANDLE handle, const void if (!PLUGIN) return nullptr; - return g_pFunctionHookSystem->initHook(handle, (void*)source, (void*)destination); + return g_pFunctionHookSystem->initHook(handle, const_cast(source), const_cast(destination)); } APICALL bool HyprlandAPI::removeFunctionHook(HANDLE handle, CFunctionHook* hook) { diff --git a/src/plugins/PluginSystem.cpp b/src/plugins/PluginSystem.cpp index cd36702ec..740b2cce8 100644 --- a/src/plugins/PluginSystem.cpp +++ b/src/plugins/PluginSystem.cpp @@ -89,8 +89,8 @@ std::expected CPluginSystem::loadPluginInternal(const std PLUGIN->m_handle = MODULE; - PPLUGIN_API_VERSION_FUNC apiVerFunc = (PPLUGIN_API_VERSION_FUNC)dlsym(MODULE, PLUGIN_API_VERSION_FUNC_STR); - PPLUGIN_INIT_FUNC initFunc = (PPLUGIN_INIT_FUNC)dlsym(MODULE, PLUGIN_INIT_FUNC_STR); + PPLUGIN_API_VERSION_FUNC apiVerFunc = rc(dlsym(MODULE, PLUGIN_API_VERSION_FUNC_STR)); + PPLUGIN_INIT_FUNC initFunc = rc(dlsym(MODULE, PLUGIN_INIT_FUNC_STR)); if (!apiVerFunc || !initFunc) { Debug::log(ERR, " [PluginSystem] Plugin {} could not be loaded. (No apiver/init func)", path); @@ -120,7 +120,7 @@ std::expected CPluginSystem::loadPluginInternal(const std } } catch (std::exception& e) { m_allowConfigVars = false; - Debug::log(ERR, " [PluginSystem] Plugin {} (Handle {:x}) crashed in init. Unloading.", path, (uintptr_t)MODULE); + Debug::log(ERR, " [PluginSystem] Plugin {} (Handle {:x}) crashed in init. Unloading.", path, rc(MODULE)); unloadPlugin(PLUGIN, true); // Plugin could've already hooked/done something return std::unexpected(std::format("Plugin {} could not be loaded: plugin crashed/threw in main: {}", path, e.what())); } @@ -134,7 +134,7 @@ std::expected CPluginSystem::loadPluginInternal(const std g_pEventLoopManager->doLater([] { g_pConfigManager->reload(); }); - Debug::log(LOG, R"( [PluginSystem] Plugin {} loaded. Handle: {:x}, path: "{}", author: "{}", description: "{}", version: "{}")", PLUGINDATA.name, (uintptr_t)MODULE, path, + Debug::log(LOG, R"( [PluginSystem] Plugin {} loaded. Handle: {:x}, path: "{}", author: "{}", description: "{}", version: "{}")", PLUGINDATA.name, rc(MODULE), path, PLUGINDATA.author, PLUGINDATA.description, PLUGINDATA.version); return PLUGIN; @@ -145,7 +145,7 @@ void CPluginSystem::unloadPlugin(const CPlugin* plugin, bool eject) { return; if (!eject) { - PPLUGIN_EXIT_FUNC exitFunc = (PPLUGIN_EXIT_FUNC)dlsym(plugin->m_handle, PLUGIN_EXIT_FUNC_STR); + PPLUGIN_EXIT_FUNC exitFunc = rc(dlsym(plugin->m_handle, PLUGIN_EXIT_FUNC_STR)); if (exitFunc) exitFunc(); } diff --git a/src/protocols/AlphaModifier.cpp b/src/protocols/AlphaModifier.cpp index 24088190b..a9c09d979 100644 --- a/src/protocols/AlphaModifier.cpp +++ b/src/protocols/AlphaModifier.cpp @@ -27,7 +27,7 @@ void CAlphaModifier::setResource(UP&& resource) { return; } - m_alpha = alpha / (float)UINT32_MAX; + m_alpha = alpha / sc(UINT32_MAX); }); m_listeners.surfaceCommitted = m_surface->m_events.commit.listen([this] { diff --git a/src/protocols/ColorManagement.cpp b/src/protocols/ColorManagement.cpp index ce00a96b8..349a0b075 100644 --- a/src/protocols/ColorManagement.cpp +++ b/src/protocols/ColorManagement.cpp @@ -272,7 +272,7 @@ CColorManagementSurface::CColorManagementSurface(SP m_resource->setSetImageDescription([this](CWpColorManagementSurfaceV1* r, wl_resource* image_description, uint32_t render_intent) { LOGM(TRACE, "Set image description for surface={}, desc={}, intent={}", (uintptr_t)r, (uintptr_t)image_description, render_intent); - const auto PO = (CWpImageDescriptionV1*)wl_resource_get_user_data(image_description); + const auto PO = sc(wl_resource_get_user_data(image_description)); if (!PO) { // FIXME check validity r->error(WP_COLOR_MANAGEMENT_SURFACE_V1_ERROR_IMAGE_DESCRIPTION, "Image description creation failed"); return; @@ -560,7 +560,7 @@ CColorManagementParametricCreator::CColorManagementParametricCreator(SPerror(WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_TF, "Unsupported transfer function"); return; } - m_settings.transferFunction = convertTransferFunction((wpColorManagerV1TransferFunction)tf); + m_settings.transferFunction = convertTransferFunction(sc(tf)); m_valuesSet |= PC_TF; }); m_resource->setSetTfPower([this](CWpImageDescriptionCreatorParamsV1* r, uint32_t eexp) { @@ -605,7 +605,7 @@ CColorManagementParametricCreator::CColorManagementParametricCreator(SP(primaries)); m_settings.primaries = getPrimaries(m_settings.primariesNamed); m_valuesSet |= PC_PRIMARIES; }); @@ -755,7 +755,7 @@ CColorManagementImageDescriptionInfo::CColorManagementImageDescriptionInfo(SPclient(); - const auto toProto = [](float value) { return int32_t(std::round(value * 10000)); }; + const auto toProto = [](float value) { return sc(std::round(value * 10000)); }; if (m_settings.icc.fd >= 0) m_resource->sendIccFile(m_settings.icc.fd, m_settings.icc.length); diff --git a/src/protocols/CursorShape.cpp b/src/protocols/CursorShape.cpp index 89ab71424..0583da1ac 100644 --- a/src/protocols/CursorShape.cpp +++ b/src/protocols/CursorShape.cpp @@ -41,7 +41,7 @@ void CCursorShapeProtocol::createCursorShapeDevice(CWpCursorShapeManagerV1* pMgr } void CCursorShapeProtocol::onSetShape(CWpCursorShapeDeviceV1* pMgr, uint32_t serial, wpCursorShapeDeviceV1Shape shape) { - if UNLIKELY ((uint32_t)shape == 0 || (uint32_t)shape >= CURSOR_SHAPE_NAMES.size()) { + if UNLIKELY (sc(shape) == 0 || sc(shape) >= CURSOR_SHAPE_NAMES.size()) { pMgr->error(WP_CURSOR_SHAPE_DEVICE_V1_ERROR_INVALID_SHAPE, "The shape is invalid"); return; } diff --git a/src/protocols/DRMLease.cpp b/src/protocols/DRMLease.cpp index 3d9580158..260497d3c 100644 --- a/src/protocols/DRMLease.cpp +++ b/src/protocols/DRMLease.cpp @@ -147,7 +147,7 @@ bool CDRMLeaseRequestResource::good() { } SP CDRMLeaseConnectorResource::fromResource(wl_resource* res) { - auto data = (CDRMLeaseConnectorResource*)(((CWpDrmLeaseConnectorV1*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } @@ -181,7 +181,7 @@ void CDRMLeaseConnectorResource::sendData() { m_resource->sendName(m_monitor->m_name.c_str()); m_resource->sendDescription(m_monitor->m_description.c_str()); - auto AQDRMOutput = (Aquamarine::CDRMOutput*)m_monitor->m_output.get(); + auto AQDRMOutput = sc(m_monitor->m_output.get()); m_resource->sendConnectorId(AQDRMOutput->getConnectorID()); m_resource->sendDone(); @@ -265,7 +265,7 @@ CDRMLeaseProtocol::CDRMLeaseProtocol(const wl_interface* iface, const int& ver, if (backend_->type() != Aquamarine::AQ_BACKEND_DRM) return; - m_backend = ((Aquamarine::CDRMBackend*)backend_.get())->self.lock(); + m_backend = sc(backend_.get())->self.lock(); m_deviceName = m_backend->gpuName; CFileDescriptor fd{m_backend->getNonMasterFD()}; diff --git a/src/protocols/DRMSyncobj.cpp b/src/protocols/DRMSyncobj.cpp index 762708e56..2d232e285 100644 --- a/src/protocols/DRMSyncobj.cpp +++ b/src/protocols/DRMSyncobj.cpp @@ -61,7 +61,7 @@ CDRMSyncobjSurfaceResource::CDRMSyncobjSurfaceResource(UPm_timeline, ((uint64_t)hi << 32) | (uint64_t)lo}; + m_pendingAcquire = {timeline->m_timeline, (sc(hi) << 32) | sc(lo)}; }); m_resource->setSetReleasePoint([this](CWpLinuxDrmSyncobjSurfaceV1* r, wl_resource* timeline_, uint32_t hi, uint32_t lo) { @@ -71,7 +71,7 @@ CDRMSyncobjSurfaceResource::CDRMSyncobjSurfaceResource(UPm_timeline, ((uint64_t)hi << 32) | (uint64_t)lo}; + m_pendingRelease = {timeline->m_timeline, (sc(hi) << 32) | sc(lo)}; }); m_listeners.surfacePrecommit = m_surface->m_events.precommit.listen([this] { diff --git a/src/protocols/DataDeviceWlr.cpp b/src/protocols/DataDeviceWlr.cpp index e169f6663..835fbc012 100644 --- a/src/protocols/DataDeviceWlr.cpp +++ b/src/protocols/DataDeviceWlr.cpp @@ -65,7 +65,7 @@ CWLRDataSource::~CWLRDataSource() { } SP CWLRDataSource::fromResource(wl_resource* res) { - auto data = (CWLRDataSource*)(((CZwlrDataControlSourceV1*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } diff --git a/src/protocols/ExtWorkspace.cpp b/src/protocols/ExtWorkspace.cpp index 9c40d773b..8b6c010db 100644 --- a/src/protocols/ExtWorkspace.cpp +++ b/src/protocols/ExtWorkspace.cpp @@ -20,7 +20,7 @@ CExtWorkspaceGroupResource::CExtWorkspaceGroupResource(WPsetOnDestroy([this](auto) { PROTO::extWorkspace->destroyGroup(m_self); }); m_resource->setDestroy([this](auto) { PROTO::extWorkspace->destroyGroup(m_self); }); - m_resource->sendCapabilities(static_cast(0)); + m_resource->sendCapabilities(sc(0)); const auto& output = PROTO::outputs.at(m_monitor->m_name); @@ -41,8 +41,8 @@ bool CExtWorkspaceGroupResource::good() const { } WP CExtWorkspaceGroupResource::fromResource(wl_resource* resource) { - auto handle = static_cast(wl_resource_get_user_data(resource))->data(); - auto data = static_cast(handle); + auto handle = sc(wl_resource_get_user_data(resource))->data(); + auto data = sc(handle); return data ? data->m_self : WP(); } @@ -105,7 +105,7 @@ CExtWorkspaceResource::CExtWorkspaceResource(WP ma id += UINT32_MAX - 1337; if (id > 0) - *static_cast(wl_array_add(&coordinates, sizeof(uint32_t))) = id; + *sc(wl_array_add(&coordinates, sizeof(uint32_t))) = id; m_resource->sendCoordinates(&coordinates); wl_array_release(&coordinates); @@ -142,7 +142,7 @@ void CExtWorkspaceResource::sendState() { if (m_workspace->m_isSpecialWorkspace) state |= EXT_WORKSPACE_HANDLE_V1_STATE_HIDDEN; - m_resource->sendState(static_cast(state)); + m_resource->sendState(sc(state)); if (m_manager) m_manager->scheduleDone(); @@ -158,7 +158,7 @@ void CExtWorkspaceResource::sendCapabilities() { if (active && m_workspace->m_isSpecialWorkspace) capabilities |= EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_DEACTIVATE; - m_resource->sendCapabilities(static_cast(capabilities)); + m_resource->sendCapabilities(sc(capabilities)); if (m_manager) m_manager->scheduleDone(); diff --git a/src/protocols/ForeignToplevel.cpp b/src/protocols/ForeignToplevel.cpp index ec5943afa..c652058f9 100644 --- a/src/protocols/ForeignToplevel.cpp +++ b/src/protocols/ForeignToplevel.cpp @@ -55,7 +55,7 @@ void CForeignToplevelList::onMap(PHLWINDOW pWindow) { return; } - const auto IDENTIFIER = std::format("{:08x}->{:016x}", static_cast((uintptr_t)this & 0xFFFFFFFF), (uintptr_t)pWindow.get()); + const auto IDENTIFIER = std::format("{:08x}->{:016x}", sc(rc(this) & 0xFFFFFFFF), rc(pWindow.get())); LOGM(LOG, "Newly mapped window gets an identifier of {}", IDENTIFIER); m_resource->sendToplevel(NEWHANDLE->m_resource.get()); @@ -172,6 +172,6 @@ bool CForeignToplevelProtocol::windowValidForForeign(PHLWINDOW pWindow) { } PHLWINDOW CForeignToplevelProtocol::windowFromHandleResource(wl_resource* res) { - auto data = (CForeignToplevelHandle*)(((CExtForeignToplevelHandleV1*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->window() : nullptr; } diff --git a/src/protocols/ForeignToplevelWlr.cpp b/src/protocols/ForeignToplevelWlr.cpp index 8eb1a6530..86b68584e 100644 --- a/src/protocols/ForeignToplevelWlr.cpp +++ b/src/protocols/ForeignToplevelWlr.cpp @@ -109,7 +109,7 @@ CForeignToplevelHandleWlr::CForeignToplevelHandleWlr(SPm_isMapped) return; - g_pEventManager->postEvent(SHyprIPCEvent{.event = "minimized", .data = std::format("{:x},1", (uintptr_t)PWINDOW.get())}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "minimized", .data = std::format("{:x},1", rc(PWINDOW.get()))}); }); m_resource->setUnsetMinimized([this](CZwlrForeignToplevelHandleV1* p) { @@ -121,7 +121,7 @@ CForeignToplevelHandleWlr::CForeignToplevelHandleWlr(SPm_isMapped) return; - g_pEventManager->postEvent(SHyprIPCEvent{.event = "minimized", .data = std::format("{:x},0", (uintptr_t)PWINDOW.get())}); + g_pEventManager->postEvent(SHyprIPCEvent{.event = "minimized", .data = std::format("{:x},0", rc(PWINDOW.get()))}); }); m_resource->setClose([this](CZwlrForeignToplevelHandleV1* p) { @@ -179,12 +179,12 @@ void CForeignToplevelHandleWlr::sendState() { wl_array_init(&state); if (PWINDOW == g_pCompositor->m_lastWindow) { - auto p = (uint32_t*)wl_array_add(&state, sizeof(uint32_t)); + auto p = sc(wl_array_add(&state, sizeof(uint32_t))); *p = ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED; } if (PWINDOW->isFullscreen()) { - auto p = (uint32_t*)wl_array_add(&state, sizeof(uint32_t)); + auto p = sc(wl_array_add(&state, sizeof(uint32_t))); if (PWINDOW->isEffectiveInternalFSMode(FSMODE_FULLSCREEN)) *p = ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN; else @@ -424,7 +424,7 @@ void CForeignToplevelWlrProtocol::destroyHandle(CForeignToplevelHandleWlr* handl } PHLWINDOW CForeignToplevelWlrProtocol::windowFromHandleResource(wl_resource* res) { - auto data = (CForeignToplevelHandleWlr*)(((CZwlrForeignToplevelHandleV1*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->window() : nullptr; } diff --git a/src/protocols/FrogColorManagement.cpp b/src/protocols/FrogColorManagement.cpp index 42d3c496e..730a15b04 100644 --- a/src/protocols/FrogColorManagement.cpp +++ b/src/protocols/FrogColorManagement.cpp @@ -19,7 +19,7 @@ static wpColorManagerV1TransferFunction getWPTransferFunction(frogColorManagedSu } static wpColorManagerV1Primaries getWPPrimaries(frogColorManagedSurfacePrimaries primaries) { - return (wpColorManagerV1Primaries)(primaries + 1); + return sc(primaries + 1); } CFrogColorManager::CFrogColorManager(SP resource_) : m_resource(resource_) { diff --git a/src/protocols/GammaControl.cpp b/src/protocols/GammaControl.cpp index e371496de..58382de98 100644 --- a/src/protocols/GammaControl.cpp +++ b/src/protocols/GammaControl.cpp @@ -80,10 +80,10 @@ CGammaControl::CGammaControl(SP resource_, wl_resource* out moreBytes = read(gammaFd.get(), buf, BUF_SIZE); } - if (readBytes < 0 || (size_t)readBytes != m_gammaTable.size() * sizeof(uint16_t) || moreBytes != 0) { + if (readBytes < 0 || sc(readBytes) != m_gammaTable.size() * sizeof(uint16_t) || moreBytes != 0) { LOGM(ERR, "Failed to read bytes"); - if ((size_t)readBytes != m_gammaTable.size() * sizeof(uint16_t) || moreBytes > 0) { + if (sc(readBytes) != m_gammaTable.size() * sizeof(uint16_t) || moreBytes > 0) { gamma->error(ZWLR_GAMMA_CONTROL_V1_ERROR_INVALID_GAMMA, "Gamma ramps size mismatch"); return; } diff --git a/src/protocols/IdleNotify.cpp b/src/protocols/IdleNotify.cpp index 82bd59b1f..0ebe24e30 100644 --- a/src/protocols/IdleNotify.cpp +++ b/src/protocols/IdleNotify.cpp @@ -3,7 +3,7 @@ static int onTimer(SP self, void* data) { - const auto NOTIF = (CExtIdleNotification*)data; + const auto NOTIF = sc(data); NOTIF->onTimerFired(); diff --git a/src/protocols/InputMethodV2.cpp b/src/protocols/InputMethodV2.cpp index 7826a9620..6eb419dc0 100644 --- a/src/protocols/InputMethodV2.cpp +++ b/src/protocols/InputMethodV2.cpp @@ -58,7 +58,7 @@ void CInputMethodKeyboardGrabV2::sendKeyboardData(SP keyboard) { void CInputMethodKeyboardGrabV2::sendKey(uint32_t time, uint32_t key, wl_keyboard_key_state state) { const auto SERIAL = g_pSeatManager->nextSerial(g_pSeatManager->seatResourceForClient(m_resource->client())); - m_resource->sendKey(SERIAL, time, key, (uint32_t)state); + m_resource->sendKey(SERIAL, time, key, sc(state)); } void CInputMethodKeyboardGrabV2::sendMods(uint32_t depressed, uint32_t latched, uint32_t locked, uint32_t group) { @@ -243,11 +243,11 @@ void CInputMethodV2::surroundingText(const std::string& text, uint32_t cursor, u } void CInputMethodV2::textChangeCause(zwpTextInputV3ChangeCause changeCause) { - m_resource->sendTextChangeCause((uint32_t)changeCause); + m_resource->sendTextChangeCause(changeCause); } void CInputMethodV2::textContentType(zwpTextInputV3ContentHint hint, zwpTextInputV3ContentPurpose purpose) { - m_resource->sendContentType((uint32_t)hint, (uint32_t)purpose); + m_resource->sendContentType(hint, purpose); } void CInputMethodV2::done() { diff --git a/src/protocols/LayerShell.cpp b/src/protocols/LayerShell.cpp index be9e33708..2ed4bfb1c 100644 --- a/src/protocols/LayerShell.cpp +++ b/src/protocols/LayerShell.cpp @@ -11,7 +11,7 @@ void CLayerShellResource::SState::reset() { exclusive = 0; interactivity = ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_NONE; layer = ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM; - exclusiveEdge = (zwlrLayerSurfaceV1Anchor)0; + exclusiveEdge = sc(0); desiredSize = {}; margin = {0, 0, 0, 0}; } @@ -84,7 +84,7 @@ CLayerShellResource::CLayerShellResource(SP resource_, SPsetSetSize([this](CZwlrLayerSurfaceV1* r, uint32_t x, uint32_t y) { m_pending.committed |= STATE_SIZE; - m_pending.desiredSize = {(int)x, (int)y}; + m_pending.desiredSize = {sc(x), sc(y)}; }); m_resource->setSetAnchor([this](CZwlrLayerSurfaceV1* r, zwlrLayerSurfaceV1Anchor anchor) { @@ -150,7 +150,7 @@ CLayerShellResource::CLayerShellResource(SP resource_, SP(layer); }); m_resource->setSetExclusiveEdge([this](CZwlrLayerSurfaceV1* r, zwlrLayerSurfaceV1Anchor anchor) { diff --git a/src/protocols/LayerShell.hpp b/src/protocols/LayerShell.hpp index ce8de05a4..08edc700d 100644 --- a/src/protocols/LayerShell.hpp +++ b/src/protocols/LayerShell.hpp @@ -58,7 +58,7 @@ class CLayerShellResource { Vector2D desiredSize; zwlrLayerSurfaceV1KeyboardInteractivity interactivity = ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_NONE; zwlrLayerShellV1Layer layer = ZWLR_LAYER_SHELL_V1_LAYER_BOTTOM; - zwlrLayerSurfaceV1Anchor exclusiveEdge = (zwlrLayerSurfaceV1Anchor)0; + zwlrLayerSurfaceV1Anchor exclusiveEdge = sc(0); uint32_t committed = 0; struct { diff --git a/src/protocols/LinuxDMABUF.cpp b/src/protocols/LinuxDMABUF.cpp index c45da4e0d..24cf29517 100644 --- a/src/protocols/LinuxDMABUF.cpp +++ b/src/protocols/LinuxDMABUF.cpp @@ -80,7 +80,7 @@ CDMABUFFormatTable::CDMABUFFormatTable(SDMABUFTranche _rendererTranche, std::vec CFileDescriptor fds[2]; allocateSHMFilePair(m_tableSize, fds[0], fds[1]); - auto arr = (SDMABUFFormatTableEntry*)mmap(nullptr, m_tableSize, PROT_READ | PROT_WRITE, MAP_SHARED, fds[0].get(), 0); + auto arr = sc(mmap(nullptr, m_tableSize, PROT_READ | PROT_WRITE, MAP_SHARED, fds[0].get(), 0)); if (arr == MAP_FAILED) { LOGM(ERR, "mmap failed"); @@ -150,7 +150,7 @@ CLinuxDMABUFParamsResource::CLinuxDMABUFParamsResource(UPfds[plane] = fd; m_attrs->strides[plane] = stride; m_attrs->offsets[plane] = offset; - m_attrs->modifier = ((uint64_t)modHi << 32) | modLo; + m_attrs->modifier = (sc(modHi) << 32) | modLo; }); m_resource->setCreate([this](CZwpLinuxBufferParamsV1* r, int32_t w, int32_t h, uint32_t fmt, zwpLinuxBufferParamsV1Flags flags) { @@ -279,11 +279,11 @@ bool CLinuxDMABUFParamsResource::verify() { return false; } - for (size_t i = 0; i < (size_t)m_attrs->planes; ++i) { - if ((uint64_t)m_attrs->offsets.at(i) + (uint64_t)m_attrs->strides.at(i) * m_attrs->size.y > UINT32_MAX) { + for (size_t i = 0; i < sc(m_attrs->planes); ++i) { + if (sc(m_attrs->offsets.at(i)) + sc(m_attrs->strides.at(i)) * m_attrs->size.y > UINT32_MAX) { m_resource->error(ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_OUT_OF_BOUNDS, - std::format("size overflow on plane {}: offset {} + stride {} * height {} = {}, overflows UINT32_MAX", i, (uint64_t)m_attrs->offsets.at(i), - (uint64_t)m_attrs->strides.at(i), m_attrs->size.y, (uint64_t)m_attrs->offsets.at(i) + (uint64_t)m_attrs->strides.at(i))); + std::format("size overflow on plane {}: offset {} + stride {} * height {} = {}, overflows UINT32_MAX", i, sc(m_attrs->offsets.at(i)), + sc(m_attrs->strides.at(i)), m_attrs->size.y, sc(m_attrs->offsets.at(i)) + sc(m_attrs->strides.at(i)))); return false; } } @@ -311,11 +311,11 @@ bool CLinuxDMABUFFeedbackResource::good() { void CLinuxDMABUFFeedbackResource::sendTranche(SDMABUFTranche& tranche) { struct wl_array deviceArr = { .size = sizeof(tranche.device), - .data = (void*)&tranche.device, + .data = sc(&tranche.device), }; m_resource->sendTrancheTargetDevice(&deviceArr); - m_resource->sendTrancheFlags((zwpLinuxDmabufFeedbackV1TrancheFlags)tranche.flags); + m_resource->sendTrancheFlags(sc(tranche.flags)); wl_array indices = { .size = tranche.indices.size() * sizeof(tranche.indices.at(0)), @@ -332,7 +332,7 @@ void CLinuxDMABUFFeedbackResource::sendDefaultFeedback() { struct wl_array deviceArr = { .size = sizeof(mainDevice), - .data = (void*)&mainDevice, + .data = sc(&mainDevice), }; m_resource->sendMainDevice(&deviceArr); @@ -577,7 +577,7 @@ void CLinuxDMABufV1Protocol::updateScanoutTranche(SP surface struct wl_array deviceArr = { .size = sizeof(m_mainDevice), - .data = (void*)&m_mainDevice, + .data = sc(&m_mainDevice), }; feedbackResource->m_resource->sendMainDevice(&deviceArr); diff --git a/src/protocols/OutputManagement.cpp b/src/protocols/OutputManagement.cpp index ab2ec88a7..6cb2f4740 100644 --- a/src/protocols/OutputManagement.cpp +++ b/src/protocols/OutputManagement.cpp @@ -480,7 +480,7 @@ COutputConfigurationHead::COutputConfigurationHead(SP(refresh)}; LOGM(LOG, " | configHead for {}: set custom mode to {}x{}@{}", m_monitor->m_name, w, h, refresh); }); @@ -519,7 +519,7 @@ COutputConfigurationHead::COutputConfigurationHead(SP(transform); LOGM(LOG, " | configHead for {}: set transform to {}", m_monitor->m_name, transform); }); diff --git a/src/protocols/PresentationTime.cpp b/src/protocols/PresentationTime.cpp index 4295e19b1..f5a44893f 100644 --- a/src/protocols/PresentationTime.cpp +++ b/src/protocols/PresentationTime.cpp @@ -65,8 +65,8 @@ void CPresentationFeedback::sendQueued(WP data, const T tv_sec = TIMESPEC.tv_sec >> 32; if (data->m_wasPresented) - m_resource->sendPresented((uint32_t)tv_sec, (uint32_t)(TIMESPEC.tv_sec & 0xFFFFFFFF), (uint32_t)(TIMESPEC.tv_nsec), untilRefreshNs, (uint32_t)(seq >> 32), - (uint32_t)(seq & 0xFFFFFFFF), (wpPresentationFeedbackKind)flags); + m_resource->sendPresented(sc(tv_sec), sc(TIMESPEC.tv_sec & 0xFFFFFFFF), sc(TIMESPEC.tv_nsec), untilRefreshNs, sc(seq >> 32), + sc(seq & 0xFFFFFFFF), sc(flags)); else m_resource->sendDiscarded(); diff --git a/src/protocols/PrimarySelection.cpp b/src/protocols/PrimarySelection.cpp index 9a61f25a6..dd0eefad3 100644 --- a/src/protocols/PrimarySelection.cpp +++ b/src/protocols/PrimarySelection.cpp @@ -66,7 +66,7 @@ CPrimarySelectionSource::~CPrimarySelectionSource() { } SP CPrimarySelectionSource::fromResource(wl_resource* res) { - auto data = (CPrimarySelectionSource*)(((CZwpPrimarySelectionSourceV1*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } diff --git a/src/protocols/Screencopy.cpp b/src/protocols/Screencopy.cpp index ef878ebba..cd825b1b1 100644 --- a/src/protocols/Screencopy.cpp +++ b/src/protocols/Screencopy.cpp @@ -63,7 +63,7 @@ CScreencopyFrame::CScreencopyFrame(SP resource_, int32_t m_dmabufFormat = m_monitor->m_output->state->state().drmFormat; if (box_.width == 0 && box_.height == 0) - m_box = {0, 0, (int)(m_monitor->m_size.x), (int)(m_monitor->m_size.y)}; + m_box = {0, 0, sc(m_monitor->m_size.x), sc(m_monitor->m_size.y)}; else m_box = box_; @@ -133,7 +133,7 @@ void CScreencopyFrame::copy(CZwlrScreencopyFrameV1* pFrame, wl_resource* buffer_ m_resource->error(ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer format"); PROTO::screencopy->destroyResource(this); return; - } else if ((int)attrs.stride != m_shmStride) { + } else if (attrs.stride != m_shmStride) { LOGM(ERR, "Invalid buffer shm stride in {:x}", (uintptr_t)pFrame); m_resource->error(ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer stride"); PROTO::screencopy->destroyResource(this); @@ -172,7 +172,7 @@ void CScreencopyFrame::share() { return; } - m_resource->sendFlags((zwlrScreencopyFrameV1Flags)0); + m_resource->sendFlags(sc(0)); if (m_withDamage) { // TODO: add a damage ring for this. m_resource->sendDamage(0, 0, m_buffer->size.x, m_buffer->size.y); @@ -377,12 +377,12 @@ bool CScreencopyFrame::copyShm() { // This could be optimized by using a pixel buffer object to make this async, // but really clients should just use a dma buffer anyways. - if (packStride == (uint32_t)shm.stride) { + if (packStride == sc(shm.stride)) { glReadPixels(0, 0, m_box.w, m_box.h, glFormat, PFORMAT->glType, pixelData); } else { for (size_t i = 0; i < m_box.h; ++i) { uint32_t y = i; - glReadPixels(0, y, m_box.w, 1, glFormat, PFORMAT->glType, ((unsigned char*)pixelData) + i * shm.stride); + glReadPixels(0, y, m_box.w, 1, glFormat, PFORMAT->glType, pixelData + i * shm.stride); } } @@ -446,11 +446,11 @@ void CScreencopyClient::onTick() { const bool FRAMEAWAITING = std::ranges::any_of(PROTO::screencopy->m_frames, [&](const auto& frame) { return frame->m_client.get() == this; }); if (m_framesInLastHalfSecond > 3 && !m_sentScreencast) { - EMIT_HOOK_EVENT("screencast", (std::vector{1, (uint64_t)m_framesInLastHalfSecond, (uint64_t)m_clientOwner})); + EMIT_HOOK_EVENT("screencast", (std::vector{1, sc(m_framesInLastHalfSecond), sc(m_clientOwner)})); g_pEventManager->postEvent(SHyprIPCEvent{"screencast", "1," + std::to_string(m_clientOwner)}); m_sentScreencast = true; } else if (m_framesInLastHalfSecond < 4 && m_sentScreencast && LASTFRAMEDELTA > 1.0 && !FRAMEAWAITING) { - EMIT_HOOK_EVENT("screencast", (std::vector{0, (uint64_t)m_framesInLastHalfSecond, (uint64_t)m_clientOwner})); + EMIT_HOOK_EVENT("screencast", (std::vector{0, sc(m_framesInLastHalfSecond), sc(m_clientOwner)})); g_pEventManager->postEvent(SHyprIPCEvent{"screencast", "0," + std::to_string(m_clientOwner)}); m_sentScreencast = false; } diff --git a/src/protocols/SecurityContext.cpp b/src/protocols/SecurityContext.cpp index acabe0a19..00f7b4d86 100644 --- a/src/protocols/SecurityContext.cpp +++ b/src/protocols/SecurityContext.cpp @@ -4,14 +4,14 @@ using namespace Hyprutils::OS; static int onListenFdEvent(int fd, uint32_t mask, void* data) { - auto sc = (CSecurityContext*)data; - sc->onListen(mask); + auto secCtx = sc(data); + secCtx->onListen(mask); return 0; } static int onCloseFdEvent(int fd, uint32_t mask, void* data) { - auto sc = (CSecurityContext*)data; - sc->onClose(mask); + auto secCtx = sc(data); + secCtx->onClose(mask); return 0; } diff --git a/src/protocols/SinglePixel.cpp b/src/protocols/SinglePixel.cpp index a04cb481c..6ca48a356 100644 --- a/src/protocols/SinglePixel.cpp +++ b/src/protocols/SinglePixel.cpp @@ -12,7 +12,7 @@ CSinglePixelBuffer::CSinglePixelBuffer(uint32_t id, wl_client* client, CHyprColo m_opaque = col_.a >= 1.F; - m_texture = makeShared(DRM_FORMAT_ARGB8888, (uint8_t*)&m_color, 4, Vector2D{1, 1}); + m_texture = makeShared(DRM_FORMAT_ARGB8888, rc(&m_color), 4, Vector2D{1, 1}); m_resource = CWLBufferResource::create(makeShared(client, 1, id)); @@ -50,7 +50,7 @@ Aquamarine::SDMABUFAttrs CSinglePixelBuffer::dmabuf() { } std::tuple CSinglePixelBuffer::beginDataPtr(uint32_t flags) { - return {(uint8_t*)&m_color, DRM_FORMAT_ARGB8888, 4}; + return {rc(&m_color), DRM_FORMAT_ARGB8888, 4}; } void CSinglePixelBuffer::endDataPtr() { @@ -87,8 +87,8 @@ CSinglePixelBufferManagerResource::CSinglePixelBufferManagerResource(UPsetOnDestroy([this](CWpSinglePixelBufferManagerV1* r) { PROTO::singlePixel->destroyResource(this); }); m_resource->setCreateU32RgbaBuffer([this](CWpSinglePixelBufferManagerV1* res, uint32_t id, uint32_t r, uint32_t g, uint32_t b, uint32_t a) { - CHyprColor color{r / (float)std::numeric_limits::max(), g / (float)std::numeric_limits::max(), b / (float)std::numeric_limits::max(), - a / (float)std::numeric_limits::max()}; + CHyprColor color{r / sc(std::numeric_limits::max()), g / sc(std::numeric_limits::max()), + b / sc(std::numeric_limits::max()), a / sc(std::numeric_limits::max())}; const auto& RESOURCE = PROTO::singlePixel->m_buffers.emplace_back(makeUnique(id, m_resource->client(), color)); if UNLIKELY (!RESOURCE->good()) { diff --git a/src/protocols/Tablet.cpp b/src/protocols/Tablet.cpp index 4c47665f5..d3a94242d 100644 --- a/src/protocols/Tablet.cpp +++ b/src/protocols/Tablet.cpp @@ -210,7 +210,7 @@ void CTabletToolV2Resource::queueFrame() { if (m_frameSource) return; - m_frameSource = wl_event_loop_add_idle(g_pCompositor->m_wlEventLoop, [](void* data) { ((CTabletToolV2Resource*)data)->sendFrame(false); }, this); + m_frameSource = wl_event_loop_add_idle(g_pCompositor->m_wlEventLoop, [](void* data) { sc(data)->sendFrame(false); }, this); } void CTabletToolV2Resource::sendFrame(bool removeSource) { @@ -604,7 +604,7 @@ void CTabletV2Protocol::buttonTool(SP tool, uint32_t button, uint32 continue; auto serial = g_pSeatManager->nextSerial(g_pSeatManager->seatResourceForClient(t->m_resource->client())); - t->m_resource->sendButton(serial, button, (zwpTabletToolV2ButtonState)state); + t->m_resource->sendButton(serial, button, sc(state)); t->queueFrame(); } } diff --git a/src/protocols/TextInputV1.cpp b/src/protocols/TextInputV1.cpp index d7a0eb499..7143b0816 100644 --- a/src/protocols/TextInputV1.cpp +++ b/src/protocols/TextInputV1.cpp @@ -37,8 +37,8 @@ CTextInputV1::CTextInputV1(SP resource_) : m_resource(resource_ [this](CZwpTextInputV1* pMgr, const char* text, uint32_t cursor, uint32_t anchor) { m_pendingSurrounding = {true, std::string(text), cursor, anchor}; }); m_resource->setSetContentType([this](CZwpTextInputV1* pMgr, uint32_t hint, uint32_t purpose) { - m_pendingContentType = {true, hint == (uint32_t)ZWP_TEXT_INPUT_V1_CONTENT_HINT_DEFAULT ? (uint32_t)ZWP_TEXT_INPUT_V1_CONTENT_HINT_NONE : hint, - purpose > (uint32_t)ZWP_TEXT_INPUT_V1_CONTENT_PURPOSE_PASSWORD ? hint + 1 : hint}; + m_pendingContentType = {true, hint == sc(ZWP_TEXT_INPUT_V1_CONTENT_HINT_DEFAULT) ? sc(ZWP_TEXT_INPUT_V1_CONTENT_HINT_NONE) : hint, + purpose > sc(ZWP_TEXT_INPUT_V1_CONTENT_PURPOSE_PASSWORD) ? hint + 1 : hint}; }); m_resource->setSetCursorRectangle([this](CZwpTextInputV1* pMgr, int32_t x, int32_t y, int32_t width, int32_t height) { m_cursorRectangle = CBox{x, y, width, height}; }); diff --git a/src/protocols/ToplevelExport.cpp b/src/protocols/ToplevelExport.cpp index fc46dc142..37e90b6fe 100644 --- a/src/protocols/ToplevelExport.cpp +++ b/src/protocols/ToplevelExport.cpp @@ -60,11 +60,11 @@ void CToplevelExportClient::onTick() { const bool FRAMEAWAITING = std::ranges::any_of(PROTO::toplevelExport->m_frames, [&](const auto& frame) { return frame->m_client.get() == this; }); if (m_framesInLastHalfSecond > 3 && !m_sentScreencast) { - EMIT_HOOK_EVENT("screencast", (std::vector{1, (uint64_t)m_framesInLastHalfSecond, (uint64_t)m_clientOwner})); + EMIT_HOOK_EVENT("screencast", (std::vector{1, sc(m_framesInLastHalfSecond), sc(m_clientOwner)})); g_pEventManager->postEvent(SHyprIPCEvent{"screencast", "1," + std::to_string(m_clientOwner)}); m_sentScreencast = true; } else if (m_framesInLastHalfSecond < 4 && m_sentScreencast && LASTFRAMEDELTA > 1.0 && !FRAMEAWAITING) { - EMIT_HOOK_EVENT("screencast", (std::vector{0, (uint64_t)m_framesInLastHalfSecond, (uint64_t)m_clientOwner})); + EMIT_HOOK_EVENT("screencast", (std::vector{0, sc(m_framesInLastHalfSecond), sc(m_clientOwner)})); g_pEventManager->postEvent(SHyprIPCEvent{"screencast", "0," + std::to_string(m_clientOwner)}); m_sentScreencast = false; } @@ -116,7 +116,7 @@ CToplevelExportFrame::CToplevelExportFrame(SP re m_dmabufFormat = PMONITOR->m_output->state->state().drmFormat; - m_box = {0, 0, (int)(m_window->m_realSize->value().x * PMONITOR->m_scale), (int)(m_window->m_realSize->value().y * PMONITOR->m_scale)}; + m_box = {0, 0, sc(m_window->m_realSize->value().x * PMONITOR->m_scale), sc(m_window->m_realSize->value().y * PMONITOR->m_scale)}; m_box.transform(wlTransformToHyprutils(PMONITOR->m_transform), PMONITOR->m_transformedSize.x, PMONITOR->m_transformedSize.y).round(); @@ -180,7 +180,7 @@ void CToplevelExportFrame::copy(CHyprlandToplevelExportFrameV1* pFrame, wl_resou m_resource->error(HYPRLAND_TOPLEVEL_EXPORT_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer format"); PROTO::toplevelExport->destroyResource(this); return; - } else if ((int)attrs.stride != m_shmStride) { + } else if (attrs.stride != m_shmStride) { m_resource->error(HYPRLAND_TOPLEVEL_EXPORT_FRAME_V1_ERROR_INVALID_BUFFER, "invalid buffer stride"); PROTO::toplevelExport->destroyResource(this); return; @@ -217,7 +217,7 @@ void CToplevelExportFrame::share() { } } - m_resource->sendFlags((hyprlandToplevelExportFrameV1Flags)0); + m_resource->sendFlags(sc(0)); if (!m_ignoreDamage) m_resource->sendDamage(0, 0, m_box.width, m_box.height); diff --git a/src/protocols/ToplevelMapping.cpp b/src/protocols/ToplevelMapping.cpp index 5552fdf2b..4cc822f0b 100644 --- a/src/protocols/ToplevelMapping.cpp +++ b/src/protocols/ToplevelMapping.cpp @@ -29,7 +29,7 @@ CToplevelMappingManager::CToplevelMappingManager(SPm_resource->sendFailed(); else - NEWHANDLE->m_resource->sendWindowAddress((uint64_t)WINDOW.get() >> 32 & 0xFFFFFFFF, (uint64_t)WINDOW.get() & 0xFFFFFFFF); + NEWHANDLE->m_resource->sendWindowAddress(rc(WINDOW.get()) >> 32 & 0xFFFFFFFF, rc(WINDOW.get()) & 0xFFFFFFFF); }); m_resource->setGetWindowForToplevelWlr([this](CHyprlandToplevelMappingManagerV1* mgr, uint32_t handle, wl_resource* toplevel) { const auto NEWHANDLE = PROTO::toplevelMapping->m_handles.emplace_back( @@ -48,7 +48,7 @@ CToplevelMappingManager::CToplevelMappingManager(SPm_resource->sendFailed(); else - NEWHANDLE->m_resource->sendWindowAddress((uint64_t)WINDOW.get() >> 32 & 0xFFFFFFFF, (uint64_t)WINDOW.get() & 0xFFFFFFFF); + NEWHANDLE->m_resource->sendWindowAddress(rc(WINDOW.get()) >> 32 & 0xFFFFFFFF, rc(WINDOW.get()) & 0xFFFFFFFF); }); } diff --git a/src/protocols/VirtualKeyboard.cpp b/src/protocols/VirtualKeyboard.cpp index 3dc15d83c..6fe3eed5e 100644 --- a/src/protocols/VirtualKeyboard.cpp +++ b/src/protocols/VirtualKeyboard.cpp @@ -47,7 +47,7 @@ CVirtualKeyboardV1Resource::CVirtualKeyboardV1Resource(SP m_events.key.emit(IKeyboard::SKeyEvent{ .timeMs = timeMs, .keycode = key, - .state = (wl_keyboard_key_state)state, + .state = sc(state), }); const bool CONTAINS = std::ranges::contains(m_pressed, key); @@ -88,7 +88,7 @@ CVirtualKeyboardV1Resource::CVirtualKeyboardV1Resource(SP return; } - auto xkbKeymap = xkb_keymap_new_from_string(xkbContext, (const char*)keymapData, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); + auto xkbKeymap = xkb_keymap_new_from_string(xkbContext, sc(keymapData), XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); munmap(keymapData, len); if UNLIKELY (!xkbKeymap) { diff --git a/src/protocols/VirtualPointer.cpp b/src/protocols/VirtualPointer.cpp index c083fc3f0..9e258b7a2 100644 --- a/src/protocols/VirtualPointer.cpp +++ b/src/protocols/VirtualPointer.cpp @@ -29,7 +29,7 @@ CVirtualPointerV1Resource::CVirtualPointerV1Resource(SP r m_events.warp.emit(IPointer::SMotionAbsoluteEvent{ .timeMs = timeMs, - .absolute = {(double)x / xExtent, (double)y / yExtent}, + .absolute = {sc(x) / xExtent, sc(y) / yExtent}, }); }); @@ -37,7 +37,7 @@ CVirtualPointerV1Resource::CVirtualPointerV1Resource(SP r m_events.button.emit(IPointer::SButtonEvent{ .timeMs = timeMs, .button = button, - .state = (wl_pointer_button_state)state, + .state = sc(state), }); }); @@ -48,7 +48,7 @@ CVirtualPointerV1Resource::CVirtualPointerV1Resource(SP r } m_axis = axis_; - m_axisEvents[m_axis] = IPointer::SAxisEvent{.timeMs = timeMs, .axis = (wl_pointer_axis)m_axis, .delta = wl_fixed_to_double(value)}; + m_axisEvents[m_axis] = IPointer::SAxisEvent{.timeMs = timeMs, .axis = sc(m_axis), .delta = wl_fixed_to_double(value)}; }); m_resource->setFrame([this](CZwlrVirtualPointerV1* r) { @@ -62,7 +62,7 @@ CVirtualPointerV1Resource::CVirtualPointerV1Resource(SP r m_events.frame.emit(); }); - m_resource->setAxisSource([this](CZwlrVirtualPointerV1* r, uint32_t source) { m_axisEvents[m_axis].source = (wl_pointer_axis_source)source; }); + m_resource->setAxisSource([this](CZwlrVirtualPointerV1* r, uint32_t source) { m_axisEvents[m_axis].source = sc(source); }); m_resource->setAxisStop([this](CZwlrVirtualPointerV1* r, uint32_t timeMs, uint32_t axis_) { if UNLIKELY (m_axis > WL_POINTER_AXIS_HORIZONTAL_SCROLL) { @@ -72,7 +72,7 @@ CVirtualPointerV1Resource::CVirtualPointerV1Resource(SP r m_axis = axis_; m_axisEvents[m_axis].timeMs = timeMs; - m_axisEvents[m_axis].axis = (wl_pointer_axis)m_axis; + m_axisEvents[m_axis].axis = sc(m_axis); m_axisEvents[m_axis].delta = 0; m_axisEvents[m_axis].deltaDiscrete = 0; }); @@ -85,7 +85,7 @@ CVirtualPointerV1Resource::CVirtualPointerV1Resource(SP r m_axis = axis_; m_axisEvents[m_axis].timeMs = timeMs; - m_axisEvents[m_axis].axis = (wl_pointer_axis)m_axis; + m_axisEvents[m_axis].axis = sc(m_axis); m_axisEvents[m_axis].delta = wl_fixed_to_double(value); m_axisEvents[m_axis].deltaDiscrete = discrete * 120; }); diff --git a/src/protocols/WaylandProtocol.cpp b/src/protocols/WaylandProtocol.cpp index 8aa2c8968..650992485 100644 --- a/src/protocols/WaylandProtocol.cpp +++ b/src/protocols/WaylandProtocol.cpp @@ -2,7 +2,7 @@ #include "../Compositor.hpp" static void bindManagerInternal(wl_client* client, void* data, uint32_t ver, uint32_t id) { - ((IWaylandProtocol*)data)->bindManager(client, data, ver, id); + sc(data)->bindManager(client, data, ver, id); } static void displayDestroyInternal(struct wl_listener* listener, void* data) { diff --git a/src/protocols/XDGBell.cpp b/src/protocols/XDGBell.cpp index bf46d3eb9..884564735 100644 --- a/src/protocols/XDGBell.cpp +++ b/src/protocols/XDGBell.cpp @@ -37,7 +37,7 @@ CXDGSystemBellManagerResource::CXDGSystemBellManagerResource(UPm_wlSurface->resource() == SURFACE) { g_pEventManager->postEvent(SHyprIPCEvent{ .event = "bell", - .data = std::format("{:x}", (uintptr_t)w.get()), + .data = std::format("{:x}", rc(w.get())), }); return; } diff --git a/src/protocols/XDGShell.cpp b/src/protocols/XDGShell.cpp index 488ff6f16..55945cb93 100644 --- a/src/protocols/XDGShell.cpp +++ b/src/protocols/XDGShell.cpp @@ -99,7 +99,7 @@ Vector2D CXDGPopupResource::accumulateParentOffset() { } SP CXDGPopupResource::fromResource(wl_resource* res) { - auto data = (CXDGPopupResource*)(((CXdgPopup*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } @@ -146,9 +146,9 @@ CXDGToplevelResource::CXDGToplevelResource(SP resource_, SPversion() >= 5) { wl_array arr; wl_array_init(&arr); - auto p = (uint32_t*)wl_array_add(&arr, sizeof(uint32_t)); + auto p = sc(wl_array_add(&arr, sizeof(uint32_t))); *p = XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN; - p = (uint32_t*)wl_array_add(&arr, sizeof(uint32_t)); + p = sc(wl_array_add(&arr, sizeof(uint32_t))); *p = XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE; m_resource->sendWmCapabilities(&arr); wl_array_release(&arr); @@ -239,7 +239,7 @@ CXDGToplevelResource::~CXDGToplevelResource() { } SP CXDGToplevelResource::fromResource(wl_resource* res) { - auto data = (CXDGToplevelResource*)(((CXdgToplevel*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } @@ -491,12 +491,12 @@ bool CXDGSurfaceResource::good() { } SP CXDGSurfaceResource::fromResource(wl_resource* res) { - auto data = (CXDGSurfaceResource*)(((CXdgSurface*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } static void onConfigure(void* data) { - ((CXDGSurfaceResource*)data)->configure(); + sc(data)->configure(); } uint32_t CXDGSurfaceResource::scheduleConfigure() { @@ -547,14 +547,14 @@ CXDGPositionerResource::CXDGPositionerResource(SP resource_, SP< m_resource->setSetGravity([this](CXdgPositioner* r, xdgPositionerGravity g) { m_state.setGravity(g); }); - m_resource->setSetConstraintAdjustment([this](CXdgPositioner* r, xdgPositionerConstraintAdjustment a) { m_state.constraintAdjustment = (uint32_t)a; }); + m_resource->setSetConstraintAdjustment([this](CXdgPositioner* r, xdgPositionerConstraintAdjustment a) { m_state.constraintAdjustment = sc(a); }); // TODO: support this shit better. The current impl _works_, but is lacking and could be wrong in a few cases. // doesn't matter _that_ much for now, though. } SP CXDGPositionerResource::fromResource(wl_resource* res) { - auto data = (CXDGPositionerResource*)(((CXdgPositioner*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } diff --git a/src/protocols/XWaylandShell.cpp b/src/protocols/XWaylandShell.cpp index 9bb75a3ea..62c1e208d 100644 --- a/src/protocols/XWaylandShell.cpp +++ b/src/protocols/XWaylandShell.cpp @@ -18,7 +18,7 @@ CXWaylandSurfaceResource::CXWaylandSurfaceResource(SP resour m_client = m_resource->client(); m_resource->setSetSerial([this](CXwaylandSurfaceV1* r, uint32_t lo, uint32_t hi) { - m_serial = (((uint64_t)hi) << 32) + lo; + m_serial = (sc(hi) << 32) + lo; PROTO::xwaylandShell->m_events.newSurface.emit(m_self.lock()); }); } diff --git a/src/protocols/XXColorManagement.cpp b/src/protocols/XXColorManagement.cpp index 08f2fe70a..8ec780b40 100644 --- a/src/protocols/XXColorManagement.cpp +++ b/src/protocols/XXColorManagement.cpp @@ -28,7 +28,7 @@ static wpColorManagerV1TransferFunction getWPTransferFunction(xxColorManagerV4Tr } static wpColorManagerV1Primaries getWPPrimaries(xxColorManagerV4Primaries primaries) { - return (wpColorManagerV1Primaries)(primaries + 1); + return sc(primaries + 1); } CXXColorManager::CXXColorManager(SP resource_) : m_resource(resource_) { @@ -235,7 +235,7 @@ CXXColorManagementSurface::CXXColorManagementSurface(SPsetSetImageDescription([this](CXxColorManagementSurfaceV4* r, wl_resource* image_description, uint32_t render_intent) { LOGM(TRACE, "Set image description for surface={}, desc={}, intent={}", (uintptr_t)r, (uintptr_t)image_description, render_intent); - const auto PO = (CXxImageDescriptionV4*)wl_resource_get_user_data(image_description); + const auto PO = sc(wl_resource_get_user_data(image_description)); if (!PO) { // FIXME check validity r->error(XX_COLOR_MANAGEMENT_SURFACE_V4_ERROR_IMAGE_DESCRIPTION, "Image description creation failed"); return; @@ -425,7 +425,7 @@ CXXColorManagementParametricCreator::CXXColorManagementParametricCreator(SPerror(XX_IMAGE_DESCRIPTION_CREATOR_PARAMS_V4_ERROR_INVALID_TF, "Unsupported transfer function"); return; } - m_settings.transferFunction = convertTransferFunction(getWPTransferFunction((xxColorManagerV4TransferFunction)tf)); + m_settings.transferFunction = convertTransferFunction(getWPTransferFunction(sc(tf))); m_valuesSet |= PC_TF; }); m_resource->setSetTfPower([this](CXxImageDescriptionCreatorParamsV4* r, uint32_t eexp) { @@ -455,7 +455,7 @@ CXXColorManagementParametricCreator::CXXColorManagementParametricCreator(SP(primaries))); m_settings.primaries = getPrimaries(m_settings.primariesNamed); m_valuesSet |= PC_PRIMARIES; break; @@ -585,7 +585,7 @@ CXXColorManagementImageDescriptionInfo::CXXColorManagementImageDescriptionInfo(S m_client = m_resource->client(); - const auto toProto = [](float value) { return int32_t(std::round(value * 10000)); }; + const auto toProto = [](float value) { return sc(std::round(value * 10000)); }; if (m_settings.icc.fd >= 0) m_resource->sendIccFile(m_settings.icc.fd, m_settings.icc.length); diff --git a/src/protocols/core/Compositor.cpp b/src/protocols/core/Compositor.cpp index bbb76cb2d..37e2df9a5 100644 --- a/src/protocols/core/Compositor.cpp +++ b/src/protocols/core/Compositor.cpp @@ -57,7 +57,7 @@ bool CWLRegionResource::good() { } SP CWLRegionResource::fromResource(wl_resource* res) { - auto data = (CWLRegionResource*)(((CWlRegion*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } @@ -167,7 +167,7 @@ CWLSurfaceResource::CWLSurfaceResource(SP resource_) : m_resource(re whenReadable(); } else if (state->buffer->type() == Aquamarine::BUFFER_TYPE_DMABUF && state->buffer->dmabuf().success) { // async buffer and is dmabuf, then we can wait on implicit fences - auto syncFd = dynamic_cast(state->buffer.m_buffer.get())->exportSyncFile(); + auto syncFd = dc(state->buffer.m_buffer.get())->exportSyncFile(); if (syncFd.isValid()) g_pEventLoopManager->doOnReadable(std::move(syncFd), whenReadable); @@ -211,7 +211,7 @@ CWLSurfaceResource::CWLSurfaceResource(SP resource_) : m_resource(re m_pending.updated.bits.transform = true; m_pending.updated.bits.damage = true; - m_pending.transform = (wl_output_transform)tr; + m_pending.transform = sc(tr); m_pending.bufferDamage = CBox{{}, m_pending.bufferSize}; }); @@ -270,7 +270,7 @@ void CWLSurfaceResource::dropCurrentBuffer() { } SP CWLSurfaceResource::fromResource(wl_resource* res) { - auto data = (CWLSurfaceResource*)(((CWlSurface*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } @@ -379,7 +379,7 @@ void CWLSurfaceResource::bfHelper(std::vector> const& nod for (auto const& n : nodes) { Vector2D offset = {}; if (n->m_role->role() == SURFACE_ROLE_SUBSURFACE) { - auto subsurface = ((CSubsurfaceRole*)n->m_role.get())->m_subsurface.lock(); + auto subsurface = sc(n->m_role.get())->m_subsurface.lock(); offset = subsurface->posRelativeToParent(); } @@ -491,7 +491,7 @@ CBox CWLSurfaceResource::extends() { if (surf->m_role->role() != SURFACE_ROLE_SUBSURFACE) return; - ((CRegion*)d)->add(CBox{offset, surf->m_current.size}); + sc(d)->add(CBox{offset, surf->m_current.size}); }, &full); return full.getExtents(); @@ -515,7 +515,7 @@ void CWLSurfaceResource::commitState(SSurfaceState& state) { m_current.texture->m_transform = wlTransformToHyprutils(m_current.transform); if (m_role->role() == SURFACE_ROLE_SUBSURFACE) { - auto subsurface = ((CSubsurfaceRole*)m_role.get())->m_subsurface.lock(); + auto subsurface = sc(m_role.get())->m_subsurface.lock(); if (subsurface->m_sync) return; @@ -525,7 +525,7 @@ void CWLSurfaceResource::commitState(SSurfaceState& state) { breadthfirst( [](SP surf, const Vector2D& offset, void* data) { if (surf->m_role->role() == SURFACE_ROLE_SUBSURFACE) { - auto subsurface = ((CSubsurfaceRole*)surf->m_role.get())->m_subsurface.lock(); + auto subsurface = sc(surf->m_role.get())->m_subsurface.lock(); if (!subsurface->m_sync) return; } @@ -543,7 +543,7 @@ void CWLSurfaceResource::commitState(SSurfaceState& state) { SImageDescription CWLSurfaceResource::getPreferredImageDescription() { auto parent = m_self; if (parent->m_role->role() == SURFACE_ROLE_SUBSURFACE) { - auto subsurface = ((CSubsurfaceRole*)parent->m_role.get())->m_subsurface.lock(); + auto subsurface = sc(parent->m_role.get())->m_subsurface.lock(); parent = subsurface->t1Parent(); } WP monitor; @@ -611,7 +611,7 @@ void CWLSurfaceResource::updateCursorShm(CRegion damage) { // bpp is 32 INSALLAH auto begin = 4 * box.y1 * (box.x2 - box.x1) + box.x1; auto len = 4 * (box.x2 - box.x1); - memcpy((uint8_t*)shmData.data() + begin, (uint8_t*)pixelData + begin, len); + memcpy(shmData.data() + begin, pixelData + begin, len); } }); } diff --git a/src/protocols/core/DataDevice.cpp b/src/protocols/core/DataDevice.cpp index 254a55a3c..98dd29456 100644 --- a/src/protocols/core/DataDevice.cpp +++ b/src/protocols/core/DataDevice.cpp @@ -157,7 +157,7 @@ CWLDataSourceResource::~CWLDataSourceResource() { } SP CWLDataSourceResource::fromResource(wl_resource* res) { - auto data = (CWLDataSourceResource*)(((CWlDataSource*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } diff --git a/src/protocols/core/Output.cpp b/src/protocols/core/Output.cpp index 8ebf87eb8..d0f057e3d 100644 --- a/src/protocols/core/Output.cpp +++ b/src/protocols/core/Output.cpp @@ -51,7 +51,7 @@ CWLOutputResource::CWLOutputResource(SP resource_, PHLMONITOR pMonito } SP CWLOutputResource::fromResource(wl_resource* res) { - auto data = (CWLOutputResource*)(((CWlOutput*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } @@ -74,10 +74,10 @@ void CWLOutputResource::updateState() { if (m_resource->version() >= 2) m_resource->sendScale(std::ceil(m_monitor->m_scale)); - m_resource->sendMode((wl_output_mode)(WL_OUTPUT_MODE_CURRENT), m_monitor->m_pixelSize.x, m_monitor->m_pixelSize.y, m_monitor->m_refreshRate * 1000.0); + m_resource->sendMode(WL_OUTPUT_MODE_CURRENT, m_monitor->m_pixelSize.x, m_monitor->m_pixelSize.y, m_monitor->m_refreshRate * 1000.0); - m_resource->sendGeometry(0, 0, m_monitor->m_output->physicalSize.x, m_monitor->m_output->physicalSize.y, (wl_output_subpixel)m_monitor->m_output->subpixel, - m_monitor->m_output->make.c_str(), m_monitor->m_output->model.c_str(), m_monitor->m_transform); + m_resource->sendGeometry(0, 0, m_monitor->m_output->physicalSize.x, m_monitor->m_output->physicalSize.y, m_monitor->m_output->subpixel, m_monitor->m_output->make.c_str(), + m_monitor->m_output->model.c_str(), m_monitor->m_transform); if (m_resource->version() >= 2) m_resource->sendDone(); diff --git a/src/protocols/core/Seat.cpp b/src/protocols/core/Seat.cpp index 8aa2f36a0..e89c49aec 100644 --- a/src/protocols/core/Seat.cpp +++ b/src/protocols/core/Seat.cpp @@ -473,7 +473,7 @@ void CWLSeatResource::sendCapabilities(uint32_t caps) { if (caps & eHIDCapabilityType::HID_INPUT_CAPABILITY_TOUCH) wlCaps |= WL_SEAT_CAPABILITY_TOUCH; - m_resource->sendCapabilities((wl_seat_capability)wlCaps); + m_resource->sendCapabilities(sc(wlCaps)); } bool CWLSeatResource::good() { @@ -561,6 +561,6 @@ SP CWLSeatProtocol::seatResourceForClient(wl_client* client) { std::vector& CCursorSurfaceRole::cursorPixelData(SP surface) { RASSERT(surface->m_role->role() == SURFACE_ROLE_CURSOR, "cursorPixelData called on a non-cursor surface"); - auto role = (CCursorSurfaceRole*)surface->m_role.get(); + auto role = sc(surface->m_role.get()); return role->m_cursorShmPixelData; } diff --git a/src/protocols/core/Shm.cpp b/src/protocols/core/Shm.cpp index d73525a60..673bc03bc 100644 --- a/src/protocols/core/Shm.cpp +++ b/src/protocols/core/Shm.cpp @@ -59,7 +59,7 @@ Aquamarine::SSHMAttrs CWLSHMBuffer::shm() { } std::tuple CWLSHMBuffer::beginDataPtr(uint32_t flags) { - return {(uint8_t*)m_pool->m_data + m_offset, m_fmt, m_stride * size.y}; + return {sc(m_pool->m_data) + m_offset, m_fmt, m_stride * size.y}; } void CWLSHMBuffer::endDataPtr() { @@ -101,7 +101,7 @@ static int shmIsSizeValid(CFileDescriptor& fd, size_t size) { return 0; } - return (size_t)st.st_size >= size; + return sc(st.st_size) >= size; } CWLSHMPoolResource::CWLSHMPoolResource(SP resource_, CFileDescriptor fd_, size_t size_) : m_resource(resource_) { @@ -119,7 +119,7 @@ CWLSHMPoolResource::CWLSHMPoolResource(SP resource_, CFileDescriptor m_resource->setOnDestroy([this](CWlShmPool* r) { PROTO::shm->destroyResource(this); }); m_resource->setResize([this](CWlShmPool* r, int32_t size_) { - if UNLIKELY (size_ < (int32_t)m_pool->m_size) { + if UNLIKELY (size_ < sc(m_pool->m_size)) { r->error(-1, "Shrinking a shm pool is illegal"); return; } @@ -188,7 +188,7 @@ CWLSHMResource::CWLSHMResource(SP resource_) : m_resource(resource_) { // send a few supported formats. No need for any other I think? for (auto const& s : PROTO::shm->m_shmFormats) { - m_resource->sendFormat((wl_shm_format)s); + m_resource->sendFormat(sc(s)); } } diff --git a/src/protocols/core/Subcompositor.cpp b/src/protocols/core/Subcompositor.cpp index a88733901..c198052c4 100644 --- a/src/protocols/core/Subcompositor.cpp +++ b/src/protocols/core/Subcompositor.cpp @@ -116,7 +116,7 @@ Vector2D CWLSubsurfaceResource::posRelativeToParent() { while (surf->m_role->role() == SURFACE_ROLE_SUBSURFACE && std::ranges::find_if(surfacesVisited, [surf](const auto& other) { return surf == other; }) == surfacesVisited.end()) { surfacesVisited.emplace_back(surf); - auto subsurface = ((CSubsurfaceRole*)m_parent->m_role.get())->m_subsurface.lock(); + auto subsurface = sc(m_parent->m_role.get())->m_subsurface.lock(); pos += subsurface->m_position; surf = subsurface->m_parent.lock(); } @@ -133,7 +133,7 @@ SP CWLSubsurfaceResource::t1Parent() { while (surf->m_role->role() == SURFACE_ROLE_SUBSURFACE && std::ranges::find_if(surfacesVisited, [surf](const auto& other) { return surf == other; }) == surfacesVisited.end()) { surfacesVisited.emplace_back(surf); - auto subsurface = ((CSubsurfaceRole*)m_parent->m_role.get())->m_subsurface.lock(); + auto subsurface = sc(m_parent->m_role.get())->m_subsurface.lock(); surf = subsurface->m_parent.lock(); } return surf; @@ -163,7 +163,7 @@ CWLSubcompositorResource::CWLSubcompositorResource(SP resource SP t1Parent = nullptr; if (PARENT->m_role->role() == SURFACE_ROLE_SUBSURFACE) { - auto subsurface = ((CSubsurfaceRole*)PARENT->m_role.get())->m_subsurface.lock(); + auto subsurface = sc(PARENT->m_role.get())->m_subsurface.lock(); t1Parent = subsurface->t1Parent(); } else t1Parent = PARENT; diff --git a/src/protocols/types/ColorManagement.hpp b/src/protocols/types/ColorManagement.hpp index 52f3f1b7b..68726a56d 100644 --- a/src/protocols/types/ColorManagement.hpp +++ b/src/protocols/types/ColorManagement.hpp @@ -2,6 +2,7 @@ #include "color-management-v1.hpp" #include +#include "../../helpers/memory/Memory.hpp" #define SDR_MIN_LUMINANCE 0.2 #define SDR_MAX_LUMINANCE 80.0 @@ -42,16 +43,16 @@ namespace NColorManagement { // NOTE should be ok this way. unsupported primaries/tfs must be rejected earlier. supported enum values should be in sync with proto. // might need a proper switch-case and additional INVALID enum value. inline wpColorManagerV1Primaries convertPrimaries(ePrimaries primaries) { - return (wpColorManagerV1Primaries)primaries; + return sc(primaries); } inline ePrimaries convertPrimaries(wpColorManagerV1Primaries primaries) { - return (ePrimaries)primaries; + return sc(primaries); } inline wpColorManagerV1TransferFunction convertTransferFunction(eTransferFunction tf) { - return (wpColorManagerV1TransferFunction)tf; + return sc(tf); } inline eTransferFunction convertTransferFunction(wpColorManagerV1TransferFunction tf) { - return (eTransferFunction)tf; + return sc(tf); } using SPCPRimaries = Hyprgraphics::SPCPRimaries; diff --git a/src/protocols/types/WLBuffer.cpp b/src/protocols/types/WLBuffer.cpp index 8e2f2b5f6..8b8e730ea 100644 --- a/src/protocols/types/WLBuffer.cpp +++ b/src/protocols/types/WLBuffer.cpp @@ -36,7 +36,7 @@ wl_resource* CWLBufferResource::getResource() { } SP CWLBufferResource::fromResource(wl_resource* res) { - auto data = (CWLBufferResource*)(((CWlBuffer*)wl_resource_get_user_data(res))->data()); + auto data = sc(sc(wl_resource_get_user_data(res))->data()); return data ? data->m_self.lock() : nullptr; } diff --git a/src/render/Framebuffer.cpp b/src/render/Framebuffer.cpp index 9e590de5f..070bcc1b2 100644 --- a/src/render/Framebuffer.cpp +++ b/src/render/Framebuffer.cpp @@ -47,7 +47,7 @@ bool CFramebuffer::alloc(int w, int h, uint32_t drmFormat) { } auto status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - RASSERT((status == GL_FRAMEBUFFER_COMPLETE), "Framebuffer incomplete, couldn't create! (FB status: {}, GL Error: 0x{:x})", status, (int)glGetError()); + RASSERT((status == GL_FRAMEBUFFER_COMPLETE), "Framebuffer incomplete, couldn't create! (FB status: {}, GL Error: 0x{:x})", status, sc(glGetError())); Debug::log(LOG, "Framebuffer created, status {}", status); } diff --git a/src/render/OpenGL.cpp b/src/render/OpenGL.cpp index 65cd4c65f..bff6d9c41 100644 --- a/src/render/OpenGL.cpp +++ b/src/render/OpenGL.cpp @@ -46,12 +46,12 @@ const std::vector ASSET_PATHS = { }; static inline void loadGLProc(void* pProc, const char* name) { - void* proc = (void*)eglGetProcAddress(name); + void* proc = rc(eglGetProcAddress(name)); if (proc == nullptr) { Debug::log(CRIT, "[Tracy GPU Profiling] eglGetProcAddress({}) failed", name); abort(); } - *(void**)pProc = proc; + *sc(pProc) = proc; } static enum eLogLevel eglLogToLevel(EGLint type) { @@ -142,7 +142,7 @@ void CHyprOpenGLImpl::initEGL(bool gbm) { if (eglInitialize(m_eglDisplay, &major, &minor) == EGL_FALSE) RASSERT(false, "EGL: failed to initialize a platform display"); - const std::string EGLEXTENSIONS = (const char*)eglQueryString(m_eglDisplay, EGL_EXTENSIONS); + const std::string EGLEXTENSIONS = eglQueryString(m_eglDisplay, EGL_EXTENSIONS); m_exts.IMG_context_priority = EGLEXTENSIONS.contains("IMG_context_priority"); m_exts.EXT_create_context_robustness = EGLEXTENSIONS.contains("EXT_create_context_robustness"); @@ -254,7 +254,7 @@ EGLDeviceEXT CHyprOpenGLImpl::eglDeviceFromDRMFD(int drmFD) { } CHyprOpenGLImpl::CHyprOpenGLImpl() : m_drmFD(g_pCompositor->m_drmFD) { - const std::string EGLEXTENSIONS = (const char*)eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); + const std::string EGLEXTENSIONS = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); Debug::log(LOG, "Supported EGL global extensions: ({}) {}", std::ranges::count(EGLEXTENSIONS, ' '), EGLEXTENSIONS); @@ -323,15 +323,15 @@ CHyprOpenGLImpl::CHyprOpenGLImpl() : m_drmFD(g_pCompositor->m_drmFD) { RASSERT(success, "EGL does not support KHR_platform_gbm or EXT_platform_device, this is an issue with your gpu driver."); - auto* const EXTENSIONS = (const char*)glGetString(GL_EXTENSIONS); + auto* const EXTENSIONS = rc(glGetString(GL_EXTENSIONS)); RASSERT(EXTENSIONS, "Couldn't retrieve openGL extensions!"); m_extensions = EXTENSIONS; Debug::log(LOG, "Creating the Hypr OpenGL Renderer!"); - Debug::log(LOG, "Using: {}", (char*)glGetString(GL_VERSION)); - Debug::log(LOG, "Vendor: {}", (char*)glGetString(GL_VENDOR)); - Debug::log(LOG, "Renderer: {}", (char*)glGetString(GL_RENDERER)); + Debug::log(LOG, "Using: {}", rc(glGetString(GL_VERSION))); + Debug::log(LOG, "Vendor: {}", rc(glGetString(GL_VENDOR))); + Debug::log(LOG, "Renderer: {}", rc(glGetString(GL_RENDERER))); Debug::log(LOG, "Supported extensions: ({}) {}", std::ranges::count(m_extensions, ' '), m_extensions); m_exts.EXT_read_format_bgra = m_extensions.contains("GL_EXT_read_format_bgra"); @@ -343,7 +343,7 @@ CHyprOpenGLImpl::CHyprOpenGLImpl() : m_drmFD(g_pCompositor->m_drmFD) { if (!m_exts.EXT_image_dma_buf_import || !m_exts.EXT_image_dma_buf_import_modifiers) Debug::log(WARN, "Your GPU does not support DMABUFs, this will possibly cause issues and will take a hit on the performance."); - const std::string EGLEXTENSIONS_DISPLAY = (const char*)eglQueryString(m_eglDisplay, EGL_EXTENSIONS); + const std::string EGLEXTENSIONS_DISPLAY = eglQueryString(m_eglDisplay, EGL_EXTENSIONS); Debug::log(LOG, "Supported EGL display extensions: ({}) {}", std::ranges::count(EGLEXTENSIONS_DISPLAY, ' '), EGLEXTENSIONS_DISPLAY); @@ -563,9 +563,9 @@ EGLImageKHR CHyprOpenGLImpl::createEGLImage(const Aquamarine::SDMABUFAttrs& attr if (m_hasModifiers && attrs.modifier != DRM_FORMAT_MOD_INVALID) { attribs[idx++] = attrNames[i].modlo; - attribs[idx++] = static_cast(attrs.modifier & 0xFFFFFFFF); + attribs[idx++] = sc(attrs.modifier & 0xFFFFFFFF); attribs[idx++] = attrNames[i].modhi; - attribs[idx++] = static_cast(attrs.modifier >> 32); + attribs[idx++] = sc(attrs.modifier >> 32); } } @@ -575,7 +575,7 @@ EGLImageKHR CHyprOpenGLImpl::createEGLImage(const Aquamarine::SDMABUFAttrs& attr RASSERT(idx <= attribs.size(), "createEglImage: attribs array out of bounds."); - EGLImageKHR image = m_proc.eglCreateImageKHR(m_eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, (int*)attribs.data()); + EGLImageKHR image = m_proc.eglCreateImageKHR(m_eglDisplay, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, rc(attribs.data())); if (image == EGL_NO_IMAGE_KHR) { Debug::log(ERR, "EGL: EGLCreateImageKHR failed: {}", eglGetError()); return EGL_NO_IMAGE_KHR; @@ -652,7 +652,7 @@ GLuint CHyprOpenGLImpl::compileShader(const GLuint& type, std::string src, bool auto shaderSource = src.c_str(); - glShaderSource(shader, 1, (const GLchar**)&shaderSource, nullptr); + glShaderSource(shader, 1, &shaderSource, nullptr); glCompileShader(shader); GLint ok; @@ -1421,8 +1421,8 @@ void CHyprOpenGLImpl::renderRectWithDamageInternal(const CBox& box, const CHyprC const auto FULLSIZE = Vector2D(transformedBox.width, transformedBox.height); // Rounded corners - m_shaders->m_shQUAD.setUniformFloat2(SHADER_TOP_LEFT, (float)TOPLEFT.x, (float)TOPLEFT.y); - m_shaders->m_shQUAD.setUniformFloat2(SHADER_FULL_SIZE, (float)FULLSIZE.x, (float)FULLSIZE.y); + m_shaders->m_shQUAD.setUniformFloat2(SHADER_TOP_LEFT, sc(TOPLEFT.x), sc(TOPLEFT.y)); + m_shaders->m_shQUAD.setUniformFloat2(SHADER_FULL_SIZE, sc(FULLSIZE.x), sc(FULLSIZE.y)); m_shaders->m_shQUAD.setUniformFloat(SHADER_RADIUS, data.round); m_shaders->m_shQUAD.setUniformFloat(SHADER_ROUNDING_POWER, data.roundingPower); @@ -1846,7 +1846,7 @@ CFramebuffer* CHyprOpenGLImpl::blurFramebufferWithDamage(float a, CRegion* origi CRegion damage{*originalDamage}; damage.transform(wlTransformToHyprutils(invertTransform(m_renderData.pMonitor->m_transform)), m_renderData.pMonitor->m_transformedSize.x, m_renderData.pMonitor->m_transformedSize.y); - damage.expand(*PBLURPASSES > 10 ? pow(2, 15) : std::clamp(*PBLURSIZE, (int64_t)1, (int64_t)40) * pow(2, *PBLURPASSES)); + damage.expand(*PBLURPASSES > 10 ? pow(2, 15) : std::clamp(*PBLURSIZE, sc(1), sc(40)) * pow(2, *PBLURPASSES)); // helper const auto PMIRRORFB = &m_renderData.pCurrentMonData->mirrorFB; @@ -2361,7 +2361,7 @@ void CHyprOpenGLImpl::renderBorder(const CBox& box, const CGradientValueData& gr m_shaders->m_shBORDER1.setUniformMatrix3fv(SHADER_PROJ, 1, GL_TRUE, glMatrix.getMatrix()); m_shaders->m_shBORDER1.setUniform4fv(SHADER_GRADIENT, grad.m_colorsOkLabA.size() / 4, grad.m_colorsOkLabA); m_shaders->m_shBORDER1.setUniformInt(SHADER_GRADIENT_LENGTH, grad.m_colorsOkLabA.size() / 4); - m_shaders->m_shBORDER1.setUniformFloat(SHADER_ANGLE, (int)(grad.m_angle / (std::numbers::pi / 180.0)) % 360 * (std::numbers::pi / 180.0)); + m_shaders->m_shBORDER1.setUniformFloat(SHADER_ANGLE, sc(grad.m_angle / (std::numbers::pi / 180.0)) % 360 * (std::numbers::pi / 180.0)); m_shaders->m_shBORDER1.setUniformFloat(SHADER_ALPHA, data.a); m_shaders->m_shBORDER1.setUniformInt(SHADER_GRADIENT2_LENGTH, 0); @@ -2372,9 +2372,9 @@ void CHyprOpenGLImpl::renderBorder(const CBox& box, const CGradientValueData& gr const auto TOPLEFT = Vector2D(transformedBox.x, transformedBox.y); const auto FULLSIZE = Vector2D(transformedBox.width, transformedBox.height); - m_shaders->m_shBORDER1.setUniformFloat2(SHADER_TOP_LEFT, (float)TOPLEFT.x, (float)TOPLEFT.y); - m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE, (float)FULLSIZE.x, (float)FULLSIZE.y); - m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE_UNTRANSFORMED, (float)newBox.width, (float)newBox.height); + m_shaders->m_shBORDER1.setUniformFloat2(SHADER_TOP_LEFT, sc(TOPLEFT.x), sc(TOPLEFT.y)); + m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE, sc(FULLSIZE.x), sc(FULLSIZE.y)); + m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE_UNTRANSFORMED, sc(newBox.width), sc(newBox.height)); m_shaders->m_shBORDER1.setUniformFloat(SHADER_RADIUS, round); m_shaders->m_shBORDER1.setUniformFloat(SHADER_RADIUS_OUTER, data.outerRound == -1 ? round : data.outerRound); m_shaders->m_shBORDER1.setUniformFloat(SHADER_ROUNDING_POWER, data.roundingPower); @@ -2447,11 +2447,11 @@ void CHyprOpenGLImpl::renderBorder(const CBox& box, const CGradientValueData& gr m_shaders->m_shBORDER1.setUniformMatrix3fv(SHADER_PROJ, 1, GL_TRUE, glMatrix.getMatrix()); m_shaders->m_shBORDER1.setUniform4fv(SHADER_GRADIENT, grad1.m_colorsOkLabA.size() / 4, grad1.m_colorsOkLabA); m_shaders->m_shBORDER1.setUniformInt(SHADER_GRADIENT_LENGTH, grad1.m_colorsOkLabA.size() / 4); - m_shaders->m_shBORDER1.setUniformFloat(SHADER_ANGLE, (int)(grad1.m_angle / (std::numbers::pi / 180.0)) % 360 * (std::numbers::pi / 180.0)); + m_shaders->m_shBORDER1.setUniformFloat(SHADER_ANGLE, sc(grad1.m_angle / (std::numbers::pi / 180.0)) % 360 * (std::numbers::pi / 180.0)); if (!grad2.m_colorsOkLabA.empty()) m_shaders->m_shBORDER1.setUniform4fv(SHADER_GRADIENT2, grad2.m_colorsOkLabA.size() / 4, grad2.m_colorsOkLabA); m_shaders->m_shBORDER1.setUniformInt(SHADER_GRADIENT2_LENGTH, grad2.m_colorsOkLabA.size() / 4); - m_shaders->m_shBORDER1.setUniformFloat(SHADER_ANGLE2, (int)(grad2.m_angle / (std::numbers::pi / 180.0)) % 360 * (std::numbers::pi / 180.0)); + m_shaders->m_shBORDER1.setUniformFloat(SHADER_ANGLE2, sc(grad2.m_angle / (std::numbers::pi / 180.0)) % 360 * (std::numbers::pi / 180.0)); m_shaders->m_shBORDER1.setUniformFloat(SHADER_ALPHA, data.a); m_shaders->m_shBORDER1.setUniformFloat(SHADER_GRADIENT_LERP, lerp); @@ -2462,9 +2462,9 @@ void CHyprOpenGLImpl::renderBorder(const CBox& box, const CGradientValueData& gr const auto TOPLEFT = Vector2D(transformedBox.x, transformedBox.y); const auto FULLSIZE = Vector2D(transformedBox.width, transformedBox.height); - m_shaders->m_shBORDER1.setUniformFloat2(SHADER_TOP_LEFT, (float)TOPLEFT.x, (float)TOPLEFT.y); - m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE, (float)FULLSIZE.x, (float)FULLSIZE.y); - m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE_UNTRANSFORMED, (float)newBox.width, (float)newBox.height); + m_shaders->m_shBORDER1.setUniformFloat2(SHADER_TOP_LEFT, sc(TOPLEFT.x), sc(TOPLEFT.y)); + m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE, sc(FULLSIZE.x), sc(FULLSIZE.y)); + m_shaders->m_shBORDER1.setUniformFloat2(SHADER_FULL_SIZE_UNTRANSFORMED, sc(newBox.width), sc(newBox.height)); m_shaders->m_shBORDER1.setUniformFloat(SHADER_RADIUS, round); m_shaders->m_shBORDER1.setUniformFloat(SHADER_RADIUS_OUTER, data.outerRound == -1 ? round : data.outerRound); m_shaders->m_shBORDER1.setUniformFloat(SHADER_ROUNDING_POWER, data.roundingPower); @@ -2508,7 +2508,7 @@ void CHyprOpenGLImpl::renderRoundedShadow(const CBox& box, int round, float roun static auto PSHADOWPOWER = CConfigValue("decoration:shadow:render_power"); - const auto SHADOWPOWER = std::clamp((int)*PSHADOWPOWER, 1, 4); + const auto SHADOWPOWER = std::clamp(sc(*PSHADOWPOWER), 1, 4); const auto col = color; @@ -2532,9 +2532,9 @@ void CHyprOpenGLImpl::renderRoundedShadow(const CBox& box, int round, float roun const auto FULLSIZE = Vector2D(newBox.width, newBox.height); // Rounded corners - m_shaders->m_shSHADOW.setUniformFloat2(SHADER_TOP_LEFT, (float)TOPLEFT.x, (float)TOPLEFT.y); - m_shaders->m_shSHADOW.setUniformFloat2(SHADER_BOTTOM_RIGHT, (float)BOTTOMRIGHT.x, (float)BOTTOMRIGHT.y); - m_shaders->m_shSHADOW.setUniformFloat2(SHADER_FULL_SIZE, (float)FULLSIZE.x, (float)FULLSIZE.y); + m_shaders->m_shSHADOW.setUniformFloat2(SHADER_TOP_LEFT, sc(TOPLEFT.x), sc(TOPLEFT.y)); + m_shaders->m_shSHADOW.setUniformFloat2(SHADER_BOTTOM_RIGHT, sc(BOTTOMRIGHT.x), sc(BOTTOMRIGHT.y)); + m_shaders->m_shSHADOW.setUniformFloat2(SHADER_FULL_SIZE, sc(FULLSIZE.x), sc(FULLSIZE.y)); m_shaders->m_shSHADOW.setUniformFloat(SHADER_RADIUS, range + round); m_shaders->m_shSHADOW.setUniformFloat(SHADER_ROUNDING_POWER, roundingPower); m_shaders->m_shSHADOW.setUniformFloat(SHADER_RANGE, range); @@ -2623,7 +2623,7 @@ void CHyprOpenGLImpl::renderSplash(cairo_t* const CAIRO, cairo_surface_t* const static auto FALLBACKFONT = CConfigValue("misc:font_family"); const auto FONTFAMILY = *PSPLASHFONT != STRVAL_EMPTY ? *PSPLASHFONT : *FALLBACKFONT; - const auto FONTSIZE = (int)(size.y / 76); + const auto FONTSIZE = sc(size.y / 76); const auto COLOR = CHyprColor(*PSPLASHCOLOR); PangoLayout* layoutText = pango_cairo_create_layout(CAIRO); @@ -2724,7 +2724,7 @@ SP CHyprOpenGLImpl::renderText(const std::string& text, CHyprColor col pango_font_description_set_family_static(pangoFD, FONTFAMILY.c_str()); pango_font_description_set_absolute_size(pangoFD, FONTSIZE * PANGO_SCALE); pango_font_description_set_style(pangoFD, italic ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL); - pango_font_description_set_weight(pangoFD, static_cast(weight)); + pango_font_description_set_weight(pangoFD, sc(weight)); pango_layout_set_font_description(layoutText, pangoFD); cairo_set_source_rgba(CAIRO, COLOR.r, COLOR.g, COLOR.b, COLOR.a); @@ -2755,7 +2755,7 @@ SP CHyprOpenGLImpl::renderText(const std::string& text, CHyprColor col pango_font_description_set_family_static(pangoFD, FONTFAMILY.c_str()); pango_font_description_set_absolute_size(pangoFD, FONTSIZE * PANGO_SCALE); pango_font_description_set_style(pangoFD, italic ? PANGO_STYLE_ITALIC : PANGO_STYLE_NORMAL); - pango_font_description_set_weight(pangoFD, static_cast(weight)); + pango_font_description_set_weight(pangoFD, sc(weight)); pango_layout_set_font_description(layoutText, pangoFD); pango_layout_set_text(layoutText, text.c_str(), -1); @@ -2872,7 +2872,7 @@ void CHyprOpenGLImpl::ensureBackgroundTexturePresence() { static auto PNOWALLPAPER = CConfigValue("misc:disable_hyprland_logo"); static auto PFORCEWALLPAPER = CConfigValue("misc:force_default_wallpaper"); - const auto FORCEWALLPAPER = std::clamp(*PFORCEWALLPAPER, static_cast(-1L), static_cast(2L)); + const auto FORCEWALLPAPER = std::clamp(*PFORCEWALLPAPER, -1L, 2L); if (*PNOWALLPAPER) m_backgroundTexture.reset(); @@ -2887,7 +2887,7 @@ void CHyprOpenGLImpl::ensureBackgroundTexturePresence() { texPath += std::to_string(distribution(engine)); } else - texPath += std::to_string(std::clamp(*PFORCEWALLPAPER, (int64_t)0, (int64_t)2)); + texPath += std::to_string(std::clamp(*PFORCEWALLPAPER, sc(0), sc(2))); texPath += ".png"; diff --git a/src/render/Renderbuffer.cpp b/src/render/Renderbuffer.cpp index da148b9cb..d47a5195c 100644 --- a/src/render/Renderbuffer.cpp +++ b/src/render/Renderbuffer.cpp @@ -32,7 +32,7 @@ CRenderbuffer::CRenderbuffer(SP buffer, uint32_t format) : glGenRenderbuffers(1, &m_rbo); glBindRenderbuffer(GL_RENDERBUFFER, m_rbo); - g_pHyprOpenGL->m_proc.glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER, (GLeglImageOES)m_image); + g_pHyprOpenGL->m_proc.glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER, m_image); glBindRenderbuffer(GL_RENDERBUFFER, 0); glGenFramebuffers(1, &m_framebuffer.m_fb); diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp index 94a362de9..dfafbeade 100644 --- a/src/render/Renderer.cpp +++ b/src/render/Renderer.cpp @@ -1139,10 +1139,10 @@ void CHyprRenderer::calculateUVForSurface(PHLWINDOW pWindow, SPm_current.size.x; - const auto YPERC = (double)geom.y / (double)pSurface->m_current.size.y; - const auto WPERC = (double)(geom.x + geom.w ? geom.w : pSurface->m_current.size.x) / (double)pSurface->m_current.size.x; - const auto HPERC = (double)(geom.y + geom.h ? geom.h : pSurface->m_current.size.y) / (double)pSurface->m_current.size.y; + const auto XPERC = geom.x / pSurface->m_current.size.x; + const auto YPERC = geom.y / pSurface->m_current.size.y; + const auto WPERC = (geom.x + geom.w ? geom.w : pSurface->m_current.size.x) / pSurface->m_current.size.x; + const auto HPERC = (geom.y + geom.h ? geom.h : pSurface->m_current.size.y) / pSurface->m_current.size.y; const auto TOADDTL = Vector2D(XPERC * (uvBR.x - uvTL.x), YPERC * (uvBR.y - uvTL.y)); uvBR = uvBR - Vector2D((1.0 - WPERC) * (uvBR.x - uvTL.x), (1.0 - HPERC) * (uvBR.y - uvTL.y)); @@ -1349,7 +1349,7 @@ void CHyprRenderer::renderMonitor(PHLMONITOR pMonitor, bool commit) { // if we have no tracking or full tracking, invalidate the entire monitor if (*PDAMAGETRACKINGMODE == DAMAGE_TRACKING_NONE || *PDAMAGETRACKINGMODE == DAMAGE_TRACKING_MONITOR || pMonitor->m_forceFullFrames > 0 || damageBlinkCleanup > 0) - damage = {0, 0, (int)pMonitor->m_transformedSize.x * 10, (int)pMonitor->m_transformedSize.y * 10}; + damage = {0, 0, sc(pMonitor->m_transformedSize.x) * 10, sc(pMonitor->m_transformedSize.y) * 10}; finalDamage = damage; @@ -1375,7 +1375,7 @@ void CHyprRenderer::renderMonitor(PHLMONITOR pMonitor, bool commit) { EMIT_HOOK_EVENT("render", RENDER_POST_MIRROR); renderCursor = false; } else { - CBox renderBox = {0, 0, (int)pMonitor->m_pixelSize.x, (int)pMonitor->m_pixelSize.y}; + CBox renderBox = {0, 0, sc(pMonitor->m_pixelSize.x), sc(pMonitor->m_pixelSize.y)}; renderWorkspace(pMonitor, pMonitor->m_activeWorkspace, NOW, renderBox); renderLockscreen(pMonitor, NOW, renderBox); @@ -1431,7 +1431,7 @@ void CHyprRenderer::renderMonitor(PHLMONITOR pMonitor, bool commit) { frameDamage.transform(wlTransformToHyprutils(TRANSFORM), pMonitor->m_transformedSize.x, pMonitor->m_transformedSize.y); if (*PDAMAGETRACKINGMODE == DAMAGE_TRACKING_NONE || *PDAMAGETRACKINGMODE == DAMAGE_TRACKING_MONITOR) - frameDamage.add(0, 0, (int)pMonitor->m_transformedSize.x, (int)pMonitor->m_transformedSize.y); + frameDamage.add(0, 0, sc(pMonitor->m_transformedSize.x), sc(pMonitor->m_transformedSize.y)); if (*PDAMAGEBLINK) frameDamage.add(damage); @@ -1481,8 +1481,8 @@ static hdr_output_metadata createHDRMetadata(SImageDescription settings, A default: return NO_HDR_METADATA; // empty metadata for SDR } - const auto toNits = [](uint32_t value) { return uint16_t(std::round(value)); }; - const auto to16Bit = [](float value) { return uint16_t(std::round(value * 50000)); }; + const auto toNits = [](uint32_t value) { return sc(std::round(value)); }; + const auto to16Bit = [](float value) { return sc(std::round(value * 50000)); }; auto colorimetry = settings.primariesNameSet || settings.primaries == SPCPRimaries{} ? getPrimaries(settings.primariesNamed) : settings.primaries; auto luminances = settings.masteringLuminances.max > 0 ? @@ -1622,11 +1622,11 @@ bool CHyprRenderer::commitPendingAndDoExplicitSync(PHLMONITOR pMonitor) { void CHyprRenderer::renderWorkspace(PHLMONITOR pMonitor, PHLWORKSPACE pWorkspace, const Time::steady_tp& now, const CBox& geometry) { Vector2D translate = {geometry.x, geometry.y}; - float scale = (float)geometry.width / pMonitor->m_pixelSize.x; + float scale = sc(geometry.width) / pMonitor->m_pixelSize.x; TRACY_GPU_ZONE("RenderWorkspace"); - if (!DELTALESSTHAN((double)geometry.width / (double)geometry.height, pMonitor->m_pixelSize.x / pMonitor->m_pixelSize.y, 0.01)) { + if (!DELTALESSTHAN(sc(geometry.width) / sc(geometry.height), pMonitor->m_pixelSize.x / pMonitor->m_pixelSize.y, 0.01)) { Debug::log(ERR, "Ignoring geometry in renderWorkspace: aspect ratio mismatch"); scale = 1.f; translate = Vector2D{}; @@ -1792,7 +1792,7 @@ void CHyprRenderer::arrangeLayerArray(PHLMONITOR pMonitor, const std::vectormargin.bottom; if (box.width <= 0 || box.height <= 0) { - Debug::log(ERR, "LayerSurface {:x} has a negative/zero w/h???", (uintptr_t)ls.get()); + Debug::log(ERR, "LayerSurface {:x} has a negative/zero w/h???", rc(ls.get())); continue; } @@ -2126,7 +2126,7 @@ std::tuple CHyprRenderer::getRenderTimes(PHLMONITOR pMonito static int handleCrashLoop(void* data) { - g_pHyprNotificationOverlay->addNotification("Hyprland will crash in " + std::to_string(10 - (int)(g_pHyprRenderer->m_crashingDistort * 2.f)) + "s.", CHyprColor(0), 5000, + g_pHyprNotificationOverlay->addNotification("Hyprland will crash in " + std::to_string(10 - sc(g_pHyprRenderer->m_crashingDistort * 2.f)) + "s.", CHyprColor(0), 5000, ICON_INFO); g_pHyprRenderer->m_crashingDistort += 0.5f; @@ -2150,7 +2150,7 @@ void CHyprRenderer::initiateManualCrash() { g_pHyprOpenGL->m_globalTimer.reset(); - static auto PDT = (Hyprlang::INT* const*)(g_pConfigManager->getConfigValuePtr("debug:damage_tracking")); + static auto PDT = rc(g_pConfigManager->getConfigValuePtr("debug:damage_tracking")); **PDT = 0; } @@ -2419,12 +2419,12 @@ void CHyprRenderer::makeSnapshot(PHLWINDOW pWindow) { if (!shouldRenderWindow(pWindow)) return; // ignore, window is not being rendered - Debug::log(LOG, "renderer: making a snapshot of {:x}", (uintptr_t)pWindow.get()); + Debug::log(LOG, "renderer: making a snapshot of {:x}", rc(pWindow.get())); // we need to "damage" the entire monitor // so that we render the entire window // this is temporary, doesn't mess with the actual damage - CRegion fakeDamage{0, 0, (int)PMONITOR->m_transformedSize.x, (int)PMONITOR->m_transformedSize.y}; + CRegion fakeDamage{0, 0, sc(PMONITOR->m_transformedSize.x), sc(PMONITOR->m_transformedSize.y)}; PHLWINDOWREF ref{pWindow}; @@ -2454,12 +2454,12 @@ void CHyprRenderer::makeSnapshot(PHLLS pLayer) { if (!PMONITOR || !PMONITOR->m_output || PMONITOR->m_pixelSize.x <= 0 || PMONITOR->m_pixelSize.y <= 0) return; - Debug::log(LOG, "renderer: making a snapshot of {:x}", (uintptr_t)pLayer.get()); + Debug::log(LOG, "renderer: making a snapshot of {:x}", rc(pLayer.get())); // we need to "damage" the entire monitor // so that we render the entire window // this is temporary, doesn't mess with the actual damage - CRegion fakeDamage{0, 0, (int)PMONITOR->m_transformedSize.x, (int)PMONITOR->m_transformedSize.y}; + CRegion fakeDamage{0, 0, sc(PMONITOR->m_transformedSize.x), sc(PMONITOR->m_transformedSize.y)}; makeEGLCurrent(); @@ -2491,7 +2491,7 @@ void CHyprRenderer::makeSnapshot(WP popup) { if (!popup->m_wlSurface || !popup->m_wlSurface->resource() || !popup->m_mapped) return; - Debug::log(LOG, "renderer: making a snapshot of {:x}", (uintptr_t)popup.get()); + Debug::log(LOG, "renderer: making a snapshot of {:x}", rc(popup.get())); CRegion fakeDamage{0, 0, PMONITOR->m_transformedSize.x, PMONITOR->m_transformedSize.y}; diff --git a/src/render/decorations/CHyprGroupBarDecoration.cpp b/src/render/decorations/CHyprGroupBarDecoration.cpp index df8731bed..9890ba80c 100644 --- a/src/render/decorations/CHyprGroupBarDecoration.cpp +++ b/src/render/decorations/CHyprGroupBarDecoration.cpp @@ -124,10 +124,10 @@ void CHyprGroupBarDecoration::draw(PHLMONITOR pMonitor, float const& a) { static auto PINNERGAP = CConfigValue("group:groupbar:gaps_in"); static auto PKEEPUPPERGAP = CConfigValue("group:groupbar:keep_upper_gap"); static auto PTEXTOFFSET = CConfigValue("group:groupbar:text_offset"); - auto* const GROUPCOLACTIVE = (CGradientValueData*)(PGROUPCOLACTIVE.ptr())->getData(); - auto* const GROUPCOLINACTIVE = (CGradientValueData*)(PGROUPCOLINACTIVE.ptr())->getData(); - auto* const GROUPCOLACTIVELOCKED = (CGradientValueData*)(PGROUPCOLACTIVELOCKED.ptr())->getData(); - auto* const GROUPCOLINACTIVELOCKED = (CGradientValueData*)(PGROUPCOLINACTIVELOCKED.ptr())->getData(); + auto* const GROUPCOLACTIVE = sc((PGROUPCOLACTIVE.ptr())->getData()); + auto* const GROUPCOLINACTIVE = sc((PGROUPCOLINACTIVE.ptr())->getData()); + auto* const GROUPCOLACTIVELOCKED = sc((PGROUPCOLACTIVELOCKED.ptr())->getData()); + auto* const GROUPCOLINACTIVELOCKED = sc((PGROUPCOLINACTIVELOCKED.ptr())->getData()); const auto ASSIGNEDBOX = assignedBoxGlobal(); @@ -295,8 +295,8 @@ CTitleTex::CTitleTex(PHLWINDOW pWindow, const Vector2D& bufferSize, const float static auto PTITLEFONTWEIGHTACTIVE = CConfigValue("group:groupbar:font_weight_active"); static auto PTITLEFONTWEIGHTINACTIVE = CConfigValue("group:groupbar:font_weight_inactive"); - const auto FONTWEIGHTACTIVE = (CFontWeightConfigValueData*)(PTITLEFONTWEIGHTACTIVE.ptr())->getData(); - const auto FONTWEIGHTINACTIVE = (CFontWeightConfigValueData*)(PTITLEFONTWEIGHTINACTIVE.ptr())->getData(); + const auto FONTWEIGHTACTIVE = sc((PTITLEFONTWEIGHTACTIVE.ptr())->getData()); + const auto FONTWEIGHTINACTIVE = sc((PTITLEFONTWEIGHTINACTIVE.ptr())->getData()); const CHyprColor COLORACTIVE = CHyprColor(*PTEXTCOLORACTIVE); const CHyprColor COLORINACTIVE = *PTEXTCOLORINACTIVE == -1 ? COLORACTIVE : CHyprColor(*PTEXTCOLORINACTIVE); @@ -333,7 +333,7 @@ static void renderGradientTo(SP tex, CGradientValueData* grad) { pattern = cairo_pattern_create_linear(0, 0, 0, bufferSize.y); for (unsigned long i = 0; i < grad->m_colors.size(); i++) { - cairo_pattern_add_color_stop_rgba(pattern, 1 - (double)(i + 1) / (grad->m_colors.size() + 1), grad->m_colors[i].r, grad->m_colors[i].g, grad->m_colors[i].b, + cairo_pattern_add_color_stop_rgba(pattern, 1 - sc(i + 1) / (grad->m_colors.size() + 1), grad->m_colors[i].r, grad->m_colors[i].g, grad->m_colors[i].b, grad->m_colors[i].a); } @@ -368,10 +368,10 @@ void refreshGroupBarGradients() { static auto PGROUPCOLINACTIVE = CConfigValue("group:groupbar:col.inactive"); static auto PGROUPCOLACTIVELOCKED = CConfigValue("group:groupbar:col.locked_active"); static auto PGROUPCOLINACTIVELOCKED = CConfigValue("group:groupbar:col.locked_inactive"); - auto* const GROUPCOLACTIVE = (CGradientValueData*)(PGROUPCOLACTIVE.ptr())->getData(); - auto* const GROUPCOLINACTIVE = (CGradientValueData*)(PGROUPCOLINACTIVE.ptr())->getData(); - auto* const GROUPCOLACTIVELOCKED = (CGradientValueData*)(PGROUPCOLACTIVELOCKED.ptr())->getData(); - auto* const GROUPCOLINACTIVELOCKED = (CGradientValueData*)(PGROUPCOLINACTIVELOCKED.ptr())->getData(); + auto* const GROUPCOLACTIVE = sc((PGROUPCOLACTIVE.ptr())->getData()); + auto* const GROUPCOLINACTIVE = sc((PGROUPCOLINACTIVE.ptr())->getData()); + auto* const GROUPCOLACTIVELOCKED = sc((PGROUPCOLACTIVELOCKED.ptr())->getData()); + auto* const GROUPCOLINACTIVELOCKED = sc((PGROUPCOLINACTIVELOCKED.ptr())->getData()); g_pHyprRenderer->makeEGLCurrent(); diff --git a/src/render/decorations/DecorationPositioner.cpp b/src/render/decorations/DecorationPositioner.cpp index 178f3b9bd..760a9a33d 100644 --- a/src/render/decorations/DecorationPositioner.cpp +++ b/src/render/decorations/DecorationPositioner.cpp @@ -234,26 +234,26 @@ void CDecorationPositioner::onWindowUpdate(PHLWINDOW pWindow) { } else if (LEFT) { pos = wb.pos() - EDGEPOINT - Vector2D{stickyOffsetXL, -stickyOffsetYT}; pos.x -= desiredSize; - size = {(double)desiredSize, wb.size().y + stickyOffsetYB + stickyOffsetYT}; + size = {sc(desiredSize), wb.size().y + stickyOffsetYB + stickyOffsetYT}; if (SOLID) stickyOffsetXL += desiredSize; } else if (RIGHT) { pos = wb.pos() + Vector2D{wb.size().x, 0.0} - EDGEPOINT + Vector2D{stickyOffsetXR, -stickyOffsetYT}; - size = {(double)desiredSize, wb.size().y + stickyOffsetYB + stickyOffsetYT}; + size = {sc(desiredSize), wb.size().y + stickyOffsetYB + stickyOffsetYT}; if (SOLID) stickyOffsetXR += desiredSize; } else if (TOP) { pos = wb.pos() - EDGEPOINT - Vector2D{stickyOffsetXL, stickyOffsetYT}; pos.y -= desiredSize; - size = {wb.size().x + stickyOffsetXL + stickyOffsetXR, (double)desiredSize}; + size = {wb.size().x + stickyOffsetXL + stickyOffsetXR, sc(desiredSize)}; if (SOLID) stickyOffsetYT += desiredSize; } else { pos = wb.pos() + Vector2D{0.0, wb.size().y} - EDGEPOINT - Vector2D{stickyOffsetXL, stickyOffsetYB}; - size = {wb.size().x + stickyOffsetXL + stickyOffsetXR, (double)desiredSize}; + size = {wb.size().x + stickyOffsetXL + stickyOffsetXR, sc(desiredSize)}; if (SOLID) stickyOffsetYB += desiredSize; diff --git a/src/render/pass/Pass.cpp b/src/render/pass/Pass.cpp index 8e075d4c6..f7ee6a718 100644 --- a/src/render/pass/Pass.cpp +++ b/src/render/pass/Pass.cpp @@ -294,7 +294,7 @@ float CRenderPass::oneBlurRadius() { // TODO: is this exact range correct? static auto PBLURSIZE = CConfigValue("decoration:blur:size"); static auto PBLURPASSES = CConfigValue("decoration:blur:passes"); - return *PBLURPASSES > 10 ? pow(2, 15) : std::clamp(*PBLURSIZE, (int64_t)1, (int64_t)40) * pow(2, *PBLURPASSES); // is this 2^pass? I don't know but it works... I think. + return *PBLURPASSES > 10 ? pow(2, 15) : std::clamp(*PBLURSIZE, sc(1), sc(40)) * pow(2, *PBLURPASSES); // is this 2^pass? I don't know but it works... I think. } void CRenderPass::removeAllOfType(const std::string& type) { diff --git a/src/render/pass/SurfacePassElement.cpp b/src/render/pass/SurfacePassElement.cpp index 1d3d5bda8..ea720ab11 100644 --- a/src/render/pass/SurfacePassElement.cpp +++ b/src/render/pass/SurfacePassElement.cpp @@ -169,7 +169,7 @@ CBox CSurfacePassElement::getTexBox() { CBox windowBox; if (m_data.surface && m_data.mainSurface) { - windowBox = {(int)outputX + m_data.pos.x + m_data.localPos.x, (int)outputY + m_data.pos.y + m_data.localPos.y, m_data.w, m_data.h}; + windowBox = {sc(outputX) + m_data.pos.x + m_data.localPos.x, sc(outputY) + m_data.pos.y + m_data.localPos.y, m_data.w, m_data.h}; // however, if surface buffer w / h < box, we need to adjust them const auto PWINDOW = PSURFACE ? PSURFACE->getWindow() : nullptr; @@ -191,8 +191,8 @@ CBox CSurfacePassElement::getTexBox() { } } else { // here we clamp to 2, these might be some tiny specks - windowBox = {(int)outputX + m_data.pos.x + m_data.localPos.x, (int)outputY + m_data.pos.y + m_data.localPos.y, std::max((float)m_data.surface->m_current.size.x, 2.F), - std::max((float)m_data.surface->m_current.size.y, 2.F)}; + windowBox = {sc(outputX) + m_data.pos.x + m_data.localPos.x, sc(outputY) + m_data.pos.y + m_data.localPos.y, + std::max(sc(m_data.surface->m_current.size.x), 2.F), std::max(sc(m_data.surface->m_current.size.y), 2.F)}; if (m_data.pWindow && m_data.pWindow->m_realSize->isBeingAnimated() && m_data.surface && !m_data.mainSurface && m_data.squishOversized /* subsurface */) { // adjust subsurfaces to the window windowBox.width = (windowBox.width / m_data.pWindow->m_reportedSize.x) * m_data.pWindow->m_realSize->value().x; diff --git a/src/signal-safe.hpp b/src/signal-safe.hpp index ac7514fc1..a48b51b0d 100644 --- a/src/signal-safe.hpp +++ b/src/signal-safe.hpp @@ -62,7 +62,7 @@ class CBufFileWriter { } void write(char const* data, size_t len) { while (len > 0) { - size_t to_add = std::min(len, (size_t)BUFSIZE - m_writeBufPos); + size_t to_add = std::min(len, sc(BUFSIZE) - m_writeBufPos); memcpy(m_writeBuf + m_writeBufPos, data, to_add); data += to_add; len -= to_add; @@ -127,7 +127,7 @@ class CBufFileWriter { close(pipefd[0]); dup2(pipefd[1], STDOUT_FILENO); char const* const argv[] = {"/bin/sh", "-c", cmd, nullptr}; - execv("/bin/sh", (char* const*)argv); + execv("/bin/sh", const_cast(argv)); CBufFileWriter<64> failmsg(pipefd[1]); failmsg += "m_wm->getConnection()); - xcb_send_event(conn, 0, targetWindow, XCB_EVENT_MASK_NO_EVENT, (const char*)&event); + xcb_send_event(conn, 0, targetWindow, XCB_EVENT_MASK_NO_EVENT, rc(&event)); xcb_flush(conn); } @@ -51,14 +51,14 @@ xcb_window_t CX11DataDevice::getProxyWindow(xcb_window_t window) { }; if (isValidPropertyReply(proxyReply)) { - xcb_window_t proxyWindow = *(xcb_window_t*)xcb_get_property_value(proxyReply); + xcb_window_t proxyWindow = *sc(xcb_get_property_value(proxyReply)); xcb_get_property_cookie_t proxyVerifyCookie = xcb_get_property(g_pXWayland->m_wm->getConnection(), PROPERTY_OFFSET, proxyWindow, HYPRATOMS["XdndProxy"], XCB_ATOM_WINDOW, PROPERTY_OFFSET, PROPERTY_LENGTH); xcb_get_property_reply_t* proxyVerifyReply = xcb_get_property_reply(g_pXWayland->m_wm->getConnection(), proxyVerifyCookie, nullptr); if (isValidPropertyReply(proxyVerifyReply)) { - xcb_window_t verifyWindow = *(xcb_window_t*)xcb_get_property_value(proxyVerifyReply); + xcb_window_t verifyWindow = *sc(xcb_get_property_value(proxyVerifyReply)); if (verifyWindow == proxyWindow) { targetWindow = proxyWindow; Debug::log(LOG, "Using XdndProxy window {:x} for window {:x}", proxyWindow, window); @@ -181,7 +181,7 @@ void CX11DataDevice::sendMotion(uint32_t timeMs, const Vector2D& local) { xcb_window_t targetWindow = getProxyWindow(m_lastSurface->m_xID); const auto XCOORDS = g_pXWaylandManager->waylandToXWaylandCoords(m_lastSurfaceCoords + local); - const uint32_t coords = ((uint32_t)XCOORDS.x << 16) | (uint32_t)XCOORDS.y; + const uint32_t coords = (sc(XCOORDS.x) << 16) | sc(XCOORDS.y); xcb_client_message_data_t data = {{0}}; data.data32[0] = g_pXWayland->m_wm->m_dndSelection.window; diff --git a/src/xwayland/Server.cpp b/src/xwayland/Server.cpp index 209c2f95e..6750db10f 100644 --- a/src/xwayland/Server.cpp +++ b/src/xwayland/Server.cpp @@ -53,7 +53,7 @@ static CFileDescriptor createSocket(struct sockaddr_un* addr, size_t pathSize) { if (isRegularSocket) unlink(addr->sun_path); - if (bind(fd.get(), (struct sockaddr*)addr, size) < 0) { + if (bind(fd.get(), rc(addr), size) < 0) { Debug::log(ERR, "Failed to bind socket {}{}", dbgSocketPathPrefix, dbgSocketPathRem); if (isRegularSocket) unlink(addr->sun_path); diff --git a/src/xwayland/XDataSource.cpp b/src/xwayland/XDataSource.cpp index 7044d5ff1..c67ca101e 100644 --- a/src/xwayland/XDataSource.cpp +++ b/src/xwayland/XDataSource.cpp @@ -21,7 +21,7 @@ CXDataSource::CXDataSource(SXSelection& sel_) : m_selection(sel_) { return; } - auto value = (xcb_atom_t*)xcb_get_property_value(reply); + auto value = sc(xcb_get_property_value(reply)); for (uint32_t i = 0; i < reply->value_len; i++) { if (value[i] == HYPRATOMS["UTF8_STRING"]) m_mimeTypes.emplace_back("text/plain;charset=utf-8"); diff --git a/src/xwayland/XSurface.cpp b/src/xwayland/XSurface.cpp index 3b0615a04..ac8ac512a 100644 --- a/src/xwayland/XSurface.cpp +++ b/src/xwayland/XSurface.cpp @@ -98,7 +98,7 @@ void CXWaylandSurface::map() { m_mapped = true; m_surface->map(); - Debug::log(LOG, "XWayland surface {:x} mapping", (uintptr_t)this); + Debug::log(LOG, "XWayland surface {:x} mapping", rc(this)); m_events.map.emit(); @@ -118,7 +118,7 @@ void CXWaylandSurface::unmap() { m_events.unmap.emit(); m_surface->unmap(); - Debug::log(LOG, "XWayland surface {:x} unmapping", (uintptr_t)this); + Debug::log(LOG, "XWayland surface {:x} unmapping", rc(this)); g_pXWayland->m_wm->updateClientList(); } @@ -184,7 +184,7 @@ void CXWaylandSurface::configure(const CBox& box) { e.border_width = 0; e.above_sibling = XCB_NONE; e.override_redirect = m_overrideRedirect; - xcb_send_event(g_pXWayland->m_wm->getConnection(), false, m_xID, XCB_EVENT_MASK_STRUCTURE_NOTIFY, (const char*)&e); + xcb_send_event(g_pXWayland->m_wm->getConnection(), false, m_xID, XCB_EVENT_MASK_STRUCTURE_NOTIFY, rc(&e)); } g_pXWayland->m_wm->updateClientList(); diff --git a/src/xwayland/XWM.cpp b/src/xwayland/XWM.cpp index 3b217bc38..f71d369b9 100644 --- a/src/xwayland/XWM.cpp +++ b/src/xwayland/XWM.cpp @@ -55,12 +55,12 @@ void CXWM::handleCreate(xcb_create_notify_event_t* e) { const auto XSURF = m_surfaces.emplace_back(SP(new CXWaylandSurface(e->window, CBox{e->x, e->y, e->width, e->height}, e->override_redirect))); XSURF->m_self = XSURF; - Debug::log(LOG, "[xwm] New XSurface at {:x} with xid of {}", (uintptr_t)XSURF.get(), e->window); + Debug::log(LOG, "[xwm] New XSurface at {:x} with xid of {}", rc(XSURF.get()), e->window); const auto WINDOW = CWindow::create(XSURF); g_pCompositor->m_windows.emplace_back(WINDOW); WINDOW->m_self = WINDOW; - Debug::log(LOG, "[xwm] New XWayland window at {:x} for surf {:x}", (uintptr_t)WINDOW.get(), (uintptr_t)XSURF.get()); + Debug::log(LOG, "[xwm] New XWayland window at {:x} for surf {:x}", rc(WINDOW.get()), rc(XSURF.get())); } void CXWM::handleDestroy(xcb_destroy_notify_event_t* e) { @@ -211,7 +211,7 @@ void CXWM::readProp(SP XSURF, uint32_t atom, xcb_get_property_ propName = getAtomName(atom); const auto valueLen = xcb_get_property_value_length(reply); - const auto* value = (const char*)xcb_get_property_value(reply); + const auto* value = sc(xcb_get_property_value(reply)); auto handleWMClass = [&]() { XSURF->m_state.appid = std::string{value, valueLen}; @@ -231,12 +231,12 @@ void CXWM::readProp(SP XSURF, uint32_t atom, xcb_get_property_ }; auto handleWindowType = [&]() { - auto* atomsArr = (xcb_atom_t*)value; + auto* atomsArr = rc(value); XSURF->m_atoms.assign(atomsArr, atomsArr + reply->value_len); }; auto handleWMState = [&]() { - auto* atoms = (xcb_atom_t*)value; + auto* atoms = rc(value); for (uint32_t i = 0; i < reply->value_len; i++) { if (atoms[i] == HYPRATOMS["_NET_WM_STATE_MODAL"]) XSURF->m_modal = true; @@ -264,7 +264,7 @@ void CXWM::readProp(SP XSURF, uint32_t atom, xcb_get_property_ auto handleTransientFor = [&]() { if (reply->type != XCB_ATOM_WINDOW) return; - const auto XID = (xcb_window_t*)value; + const auto XID = rc(value); XSURF->m_transient = XID; if (!XID) return; @@ -306,7 +306,7 @@ void CXWM::readProp(SP XSURF, uint32_t atom, xcb_get_property_ auto handleWMProtocols = [&]() { if (reply->type != XCB_ATOM_ATOM) return; - auto* atoms = (xcb_atom_t*)value; + auto* atoms = rc(value); XSURF->m_protocols.assign(atoms, atoms + reply->value_len); }; @@ -386,9 +386,9 @@ void CXWM::handleClientMessage(xcb_client_message_event_t* e) { uint32_t serialLow = e->data.data32[0]; uint32_t serialHigh = e->data.data32[1]; - XSURF->m_wlSerial = ((uint64_t)serialHigh << 32) | serialLow; + XSURF->m_wlSerial = (sc(serialHigh) << 32) | serialLow; - Debug::log(LOG, "[xwm] surface {:x} requests serial {:x}", (uintptr_t)XSURF.get(), XSURF->m_wlSerial); + Debug::log(LOG, "[xwm] surface {:x} requests serial {:x}", rc(XSURF.get()), XSURF->m_wlSerial); for (auto const& res : m_shellResources) { if (!res) @@ -500,7 +500,7 @@ void CXWM::sendWMMessage(SP surf, xcb_client_message_data_t* d .data = *data, }; - xcb_send_event(getConnection(), 0, surf->m_xID, mask, (const char*)&event); + xcb_send_event(getConnection(), 0, surf->m_xID, mask, rc(&event)); xcb_flush(getConnection()); } @@ -569,10 +569,10 @@ void CXWM::selectionSendNotify(xcb_selection_request_event_t* e, bool success) { .requestor = e->requestor, .selection = e->selection, .target = e->target, - .property = success ? e->property : (uint32_t)XCB_ATOM_NONE, + .property = success ? e->property : sc(XCB_ATOM_NONE), }; - xcb_send_event(getConnection(), 0, e->requestor, XCB_EVENT_MASK_NO_EVENT, (const char*)&selection_notify); + xcb_send_event(getConnection(), 0, e->requestor, XCB_EVENT_MASK_NO_EVENT, rc(&selection_notify)); xcb_flush(getConnection()); } @@ -773,20 +773,20 @@ bool CXWM::handleSelectionXFixesNotify(xcb_xfixes_selection_notify_event_t* e) { bool CXWM::handleSelectionEvent(xcb_generic_event_t* e) { switch (e->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) { case XCB_SELECTION_NOTIFY: { - handleSelectionNotify((xcb_selection_notify_event_t*)e); + handleSelectionNotify(rc(e)); return true; } case XCB_PROPERTY_NOTIFY: { - return handleSelectionPropertyNotify((xcb_property_notify_event_t*)e); + return handleSelectionPropertyNotify(rc(e)); } case XCB_SELECTION_REQUEST: { - handleSelectionRequest((xcb_selection_request_event_t*)e); + handleSelectionRequest(rc(e)); return true; } } if (e->response_type - m_xfixes->first_event == XCB_XFIXES_SELECTION_NOTIFY) - return handleSelectionXFixesNotify((xcb_xfixes_selection_notify_event_t*)e); + return handleSelectionXFixesNotify(rc(e)); return false; } @@ -818,18 +818,18 @@ int CXWM::onEvent(int fd, uint32_t mask) { continue; switch (event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) { - case XCB_CREATE_NOTIFY: handleCreate((xcb_create_notify_event_t*)event.get()); break; - case XCB_DESTROY_NOTIFY: handleDestroy((xcb_destroy_notify_event_t*)event.get()); break; - case XCB_CONFIGURE_REQUEST: handleConfigureRequest((xcb_configure_request_event_t*)event.get()); break; - case XCB_CONFIGURE_NOTIFY: handleConfigureNotify((xcb_configure_notify_event_t*)event.get()); break; - case XCB_MAP_REQUEST: handleMapRequest((xcb_map_request_event_t*)event.get()); break; - case XCB_MAP_NOTIFY: handleMapNotify((xcb_map_notify_event_t*)event.get()); break; - case XCB_UNMAP_NOTIFY: handleUnmapNotify((xcb_unmap_notify_event_t*)event.get()); break; - case XCB_PROPERTY_NOTIFY: handlePropertyNotify((xcb_property_notify_event_t*)event.get()); break; - case XCB_CLIENT_MESSAGE: handleClientMessage((xcb_client_message_event_t*)event.get()); break; - case XCB_FOCUS_IN: handleFocusIn((xcb_focus_in_event_t*)event.get()); break; - case XCB_FOCUS_OUT: handleFocusOut((xcb_focus_out_event_t*)event.get()); break; - case 0: handleError((xcb_value_error_t*)event.get()); break; + case XCB_CREATE_NOTIFY: handleCreate(rc(event.get())); break; + case XCB_DESTROY_NOTIFY: handleDestroy(rc(event.get())); break; + case XCB_CONFIGURE_REQUEST: handleConfigureRequest(rc(event.get())); break; + case XCB_CONFIGURE_NOTIFY: handleConfigureNotify(rc(event.get())); break; + case XCB_MAP_REQUEST: handleMapRequest(rc(event.get())); break; + case XCB_MAP_NOTIFY: handleMapNotify(rc(event.get())); break; + case XCB_UNMAP_NOTIFY: handleUnmapNotify(rc(event.get())); break; + case XCB_PROPERTY_NOTIFY: handlePropertyNotify(rc(event.get())); break; + case XCB_CLIENT_MESSAGE: handleClientMessage(rc(event.get())); break; + case XCB_FOCUS_IN: handleFocusIn(rc(event.get())); break; + case XCB_FOCUS_OUT: handleFocusOut(rc(event.get())); break; + case 0: handleError(rc(event.get())); break; default: { Debug::log(TRACE, "[xwm] unhandled event {}", event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK); } @@ -1027,10 +1027,10 @@ void CXWM::activateSurface(SP surf, bool activate) { return; if (!surf || (!activate && g_pCompositor->m_lastWindow && !g_pCompositor->m_lastWindow->m_isX11)) { - setActiveWindow((uint32_t)XCB_WINDOW_NONE); + setActiveWindow(XCB_WINDOW_NONE); focusWindow(nullptr); } else { - setActiveWindow(surf ? surf->m_xID : (uint32_t)XCB_WINDOW_NONE); + setActiveWindow(surf ? surf->m_xID : sc(XCB_WINDOW_NONE)); focusWindow(surf); } @@ -1071,7 +1071,7 @@ void CXWM::onNewSurface(SP surf) { if (surf->client() != g_pXWayland->m_server->m_xwaylandClient) return; - Debug::log(LOG, "[xwm] New XWayland surface at {:x}", (uintptr_t)surf.get()); + Debug::log(LOG, "[xwm] New XWayland surface at {:x}", rc(surf.get())); const auto WLID = surf->id(); @@ -1087,7 +1087,7 @@ void CXWM::onNewSurface(SP surf) { } void CXWM::onNewResource(SP resource) { - Debug::log(LOG, "[xwm] New XWayland resource at {:x}", (uintptr_t)resource.get()); + Debug::log(LOG, "[xwm] New XWayland resource at {:x}", rc(resource.get())); std::erase_if(m_shellResources, [](const auto& e) { return e.expired(); }); m_shellResources.emplace_back(resource); @@ -1135,7 +1135,7 @@ void CXWM::associate(SP surf, SP wlSurf) { auto existing = std::ranges::find_if(m_surfaces, [wlSurf](const auto& e) { return e->m_surface == wlSurf; }); if (existing != m_surfaces.end()) { - Debug::log(WARN, "[xwm] associate() called but surface is already associated to {:x}, ignoring...", (uintptr_t)surf.get()); + Debug::log(WARN, "[xwm] associate() called but surface is already associated to {:x}, ignoring...", rc(surf.get())); return; } @@ -1157,7 +1157,7 @@ void CXWM::dissociate(SP surf) { surf->m_surface.reset(); surf->m_events.resourceChange.emit(); - Debug::log(LOG, "Dissociate for {:x}", (uintptr_t)surf.get()); + Debug::log(LOG, "Dissociate for {:x}", rc(surf.get())); } void CXWM::updateClientList() { @@ -1237,7 +1237,7 @@ void CXWM::setClipboardToWayland(SXSelection& sel) { sel.dataSource = source; - Debug::log(LOG, "[xwm] X selection at {:x} takes {}", (uintptr_t)sel.dataSource.get(), (&sel == &m_clipboard) ? "clipboard" : "primary selection"); + Debug::log(LOG, "[xwm] X selection at {:x} takes {}", rc(sel.dataSource.get()), (&sel == &m_clipboard) ? "clipboard" : "primary selection"); if (&sel == &m_clipboard) g_pSeatManager->setCurrentSelection(sel.dataSource); @@ -1246,7 +1246,7 @@ void CXWM::setClipboardToWayland(SXSelection& sel) { } static int writeDataSource(int fd, uint32_t mask, void* data) { - auto selection = (SXSelection*)data; + auto selection = sc(data); return selection->onWrite(); } @@ -1445,7 +1445,7 @@ int SXSelection::onRead(int fd, uint32_t mask) { static int readDataSource(int fd, uint32_t mask, void* data) { Debug::log(LOG, "[xwm] readDataSource on fd {}", fd); - auto selection = (SXSelection*)data; + auto selection = sc(data); return selection->onRead(fd, mask); } @@ -1510,7 +1510,7 @@ int SXSelection::onWrite() { } auto& transfer = *it; - char* property = (char*)xcb_get_property_value(transfer->propertyReply); + char* property = sc(xcb_get_property_value(transfer->propertyReply)); int remainder = xcb_get_property_value_length(transfer->propertyReply) - transfer->propertyStart; ssize_t len = write(transfer->wlFD.get(), property + transfer->propertyStart, remainder); diff --git a/src/xwayland/XWM.hpp b/src/xwayland/XWM.hpp index 6af6c7b0d..b03ab4b2d 100644 --- a/src/xwayland/XWM.hpp +++ b/src/xwayland/XWM.hpp @@ -71,7 +71,7 @@ class CXCBConnection { ~CXCBConnection() { if (m_connection) { - Debug::log(LOG, "Disconnecting XCB connection {:x}", (uintptr_t)m_connection); + Debug::log(LOG, "Disconnecting XCB connection {:x}", rc(m_connection)); xcb_disconnect(m_connection); m_connection = nullptr; } else