From 88c6386994c960006e14c7bfa4ccfee873252882 Mon Sep 17 00:00:00 2001 From: Miko <110693261+mikomikotaishi@users.noreply.github.com> Date: Sat, 1 Aug 2026 12:02:50 -0400 Subject: [PATCH] chore: replace string concatenation with std::format (#15652) * chore: replace string concatenation with std::format * Fix " Preserve the root API prefix when formatting" suggestion * Fix missing slash; add explicit getenv safety check --- hyprctl/src/hyprpaper/Hyprpaper.cpp | 8 +- hyprctl/src/main.cpp | 26 +++-- hyprpm/src/core/DataState.cpp | 8 +- hyprpm/src/core/HyprlandSocket.cpp | 12 +-- hyprpm/src/core/PluginManager.cpp | 101 +++++++++--------- hyprpm/src/helpers/Sys.cpp | 2 +- hyprtester/src/hyprctlCompat.cpp | 13 ++- hyprtester/src/tests/clients/child-window.cpp | 3 +- .../src/tests/clients/keyboard-modifiers.cpp | 3 +- .../src/tests/clients/pointer-scroll.cpp | 3 +- hyprtester/src/tests/clients/pointer-warp.cpp | 3 +- .../src/tests/clients/shortcut-inhibitor.cpp | 7 +- .../tests/clients/surface-scale-transform.cpp | 8 +- .../src/tests/clients/xdg-interactive.cpp | 5 +- hyprtester/src/tests/main/dwindle.cpp | 10 +- hyprtester/src/tests/main/exec.cpp | 2 +- hyprtester/src/tests/main/hyprctl.cpp | 7 +- hyprtester/src/tests/main/keybinds.cpp | 47 ++++---- hyprtester/src/tests/main/layer.cpp | 2 +- hyprtester/src/tests/main/master.cpp | 9 +- hyprtester/src/tests/main/scroll.cpp | 6 +- hyprtester/src/tests/main/window.cpp | 15 +-- hyprtester/src/tests/shared.cpp | 3 +- meta/generateLuaStubs.py | 6 +- src/Compositor.cpp | 11 +- src/config/lua/ConfigManager.cpp | 21 ++-- .../lua/bindings/LuaBindingsConfigRules.cpp | 6 +- .../lua/bindings/LuaBindingsDispatchers.cpp | 4 +- .../lua/bindings/LuaBindingsToplevel.cpp | 2 +- src/config/lua/layout/LuaLayoutProvider.cpp | 2 +- src/config/lua/types/LuaConfigInt.cpp | 2 +- src/config/shared/monitor/Parser.cpp | 4 +- src/desktop/Workspace.cpp | 6 +- src/desktop/state/FocusState.cpp | 6 +- src/desktop/view/Window.cpp | 8 +- src/devices/IKeyboard.cpp | 4 +- src/errorOverlay/Overlay.cpp | 2 +- src/helpers/AsyncDialogBox.cpp | 2 +- src/helpers/MiscFunctions.cpp | 18 ++-- src/helpers/SystemInfo.cpp | 12 +-- src/helpers/TagKeeper.cpp | 6 +- src/ipc/s1/Commands.cpp | 24 ++--- src/ipc/s1/S1.cpp | 2 +- src/ipc/s1/Unix.cpp | 2 +- src/ipc/s2/Unix.cpp | 2 +- src/managers/DonationNagManager.cpp | 4 +- src/managers/KeybindManager.cpp | 14 +-- src/managers/VersionKeeperManager.cpp | 6 +- src/managers/XCursorManager.cpp | 4 +- src/managers/input/Eis.cpp | 2 +- src/managers/input/InputManager.cpp | 10 +- .../gestures/SpecialWorkspaceGesture.cpp | 4 +- .../permissions/DynamicPermissionManager.cpp | 4 +- src/output/Monitor.cpp | 14 +-- src/plugins/HookSystem.cpp | 2 +- src/plugins/PluginAPI.cpp | 16 +-- src/plugins/PluginAPI.hpp | 5 +- src/protocols/Hotkey.cpp | 2 +- src/protocols/InputCapture.cpp | 4 +- src/render/OpenGL.cpp | 2 +- src/render/Renderer.cpp | 5 +- src/render/ShaderLoader.cpp | 6 +- src/state/WorkspacePlacementController.cpp | 6 +- src/xwayland/XWM.cpp | 2 +- tests/config/lua/LuaBindingsInternal.cpp | 6 +- 65 files changed, 297 insertions(+), 276 deletions(-) diff --git a/hyprctl/src/hyprpaper/Hyprpaper.cpp b/hyprctl/src/hyprpaper/Hyprpaper.cpp index 93f4182a8..1d2589ba4 100644 --- a/hyprctl/src/hyprpaper/Hyprpaper.cpp +++ b/hyprctl/src/hyprpaper/Hyprpaper.cpp @@ -11,8 +11,6 @@ #include using namespace Hyprutils::String; -using namespace std::string_literals; - constexpr const char* SOCKET_NAME = ".hyprpaper.sock"; static SP g_coreImpl; @@ -48,7 +46,7 @@ static std::expected getFullPath(const std::string_vie if (!HOME || HOME[0] == '\0') return std::unexpected("home path but no $HOME"); - return resolvePath(std::string{HOME} + "/"s + std::string{sv.substr(1)}); + return resolvePath(std::format("{}/{}", HOME, sv.substr(1))); } return resolvePath(sv); @@ -79,7 +77,7 @@ static std::expected doWallpaper(const std::string_view& RHS) if (!PATH) return std::unexpected(std::format("bad path: {}", PATH_RAW)); - auto socketPath = RTDIR + "/hypr/"s + HIS + "/"s + SOCKET_NAME; + auto socketPath = std::format("{}/hypr/{}/{}", RTDIR, HIS, SOCKET_NAME); auto socket = Hyprwire::IClientSocket::open(socketPath); @@ -149,7 +147,7 @@ static std::expected doListActive() { if (!HIS || HIS[0] == '\0') return std::unexpected("can't send: no HYPRLAND_INSTANCE_SIGNATURE (not running under hyprland)"); - auto socketPath = RTDIR + "/hypr/"s + HIS + "/"s + SOCKET_NAME; + auto socketPath = std::format("{}/hypr/{}/{}", RTDIR, HIS, SOCKET_NAME); auto socket = Hyprwire::IClientSocket::open(socketPath); diff --git a/hyprctl/src/main.cpp b/hyprctl/src/main.cpp index ae2dfe6c0..80671df04 100644 --- a/hyprctl/src/main.cpp +++ b/hyprctl/src/main.cpp @@ -81,12 +81,10 @@ static int getUID() { std::string getRuntimeDir() { const auto XDG = getenv("XDG_RUNTIME_DIR"); - if (!XDG) { - const std::string USERID = std::to_string(getUID()); - return "/run/user/" + USERID + "/hypr"; - } + if (!XDG) + return std::format("/run/user/{}/hypr", getUID()); - return std::string{XDG} + "/hypr"; + return std::format("{}/hypr", XDG); } static std::optional toUInt64(const std::string_view str) { @@ -227,12 +225,12 @@ int request(std::string_view arg, int minArgs = 0, bool needRoll = false) { sockaddr_un serverAddress = {0}; serverAddress.sun_family = AF_UNIX; - std::string socketPath = getRuntimeDir() + "/" + instanceSignature + "/.socket.sock"; + std::string socketPath = std::format("{}/{}/.socket.sock", getRuntimeDir(), instanceSignature); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); if (connect(SERVERSOCKET, rc(&serverAddress), SUN_LEN(&serverAddress)) < 0) { - log("Couldn't connect to " + socketPath + ". (4)"); + log(std::format("Couldn't connect to {}. (4)", socketPath)); return 4; } @@ -296,12 +294,12 @@ int requestIPC(std::string_view filename, std::string_view arg) { sockaddr_un serverAddress = {0}; serverAddress.sun_family = AF_UNIX; - std::string socketPath = getRuntimeDir() + "/" + instanceSignature + "/" + filename; + std::string socketPath = std::format("{}/{}/{}", getRuntimeDir(), instanceSignature, filename); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); if (connect(SERVERSOCKET, rc(&serverAddress), SUN_LEN(&serverAddress)) < 0) { - log("Couldn't connect to " + socketPath + ". (3)"); + log(std::format("Couldn't connect to {}. (3)", socketPath)); return 3; } @@ -344,7 +342,7 @@ void batchRequest(std::string_view arg, bool json) { commands.insert(0, "j/"); } - std::string rq = "[[BATCH]]" + commands; + std::string rq = std::format("[[BATCH]]{}", commands); request(rq); } @@ -375,7 +373,7 @@ void instancesRequest(bool json) { result += "\n]"; } - log(result + "\n"); + log(std::format("{}\n", result)); } std::vector splitArgs(int argc, char** argv) { @@ -467,7 +465,7 @@ int main(int argc, char** argv) { continue; } - fullRequest += ARGS[i] + " "; + fullRequest += std::format("{} ", ARGS[i]); } if (fullRequest.empty()) { @@ -477,7 +475,7 @@ int main(int argc, char** argv) { fullRequest.pop_back(); // remove trailing space - fullRequest = fullArgs + "/" + fullRequest; + fullRequest = std::format("{}/{}", fullArgs, fullRequest); // instances is HIS-independent if (fullRequest.contains("/instances")) { @@ -568,7 +566,7 @@ int main(int argc, char** argv) { while ((input = readline("> ")) != nullptr) { std::string line(input); if (!line.empty()) { - exitStatus = request("/repl " + line); + exitStatus = request(std::format("/repl {}", line)); add_history(input); } free(input); diff --git a/hyprpm/src/core/DataState.cpp b/hyprpm/src/core/DataState.cpp index f33d84c16..2110b619f 100644 --- a/hyprpm/src/core/DataState.cpp +++ b/hyprpm/src/core/DataState.cpp @@ -27,18 +27,18 @@ static std::string getTempRoot() { // write the state to a file static bool writeState(const std::string& str, const std::string& to) { // create temp file in a safe temp root - std::ofstream of(getTempRoot() + ".temp-state", std::ios::trunc); + std::ofstream of(std::format("{}.temp-state", getTempRoot()), std::ios::trunc); if (!of.good()) return false; of << str; of.close(); - return NSys::root::install(getTempRoot() + ".temp-state", to, "644"); + return NSys::root::install(std::format("{}.temp-state", getTempRoot()), to, "644"); } std::filesystem::path DataState::getDataStatePath() { - return std::filesystem::path("/var/cache/hyprpm/" + g_pPluginManager->m_szUsername); + return std::filesystem::path(std::format("/var/cache/hyprpm/{}", g_pPluginManager->m_szUsername)); } std::string DataState::getHeadersPath() { @@ -100,7 +100,7 @@ void DataState::addNewPluginRepo(const SPluginRepository& repo) { }} }; for (auto const& p : repo.plugins) { - const auto filename = p.name + ".so"; + const auto filename = std::format("{}.so", p.name); // copy .so to the good place and chmod 755 if (std::filesystem::exists(p.filename)) { diff --git a/hyprpm/src/core/HyprlandSocket.cpp b/hyprpm/src/core/HyprlandSocket.cpp index 2609dae29..139bd44b7 100644 --- a/hyprpm/src/core/HyprlandSocket.cpp +++ b/hyprpm/src/core/HyprlandSocket.cpp @@ -38,12 +38,10 @@ static int getUID() { static std::string getRuntimeDir() { const auto XDG = getenv("XDG_RUNTIME_DIR"); - if (!XDG) { - const std::string USERID = std::to_string(getUID()); - return "/run/user/" + USERID + "/hypr"; - } + if (!XDG) + return std::format("/run/user/{}/hypr", getUID()); - return std::string{XDG} + "/hypr"; + return std::format("{}/hypr", XDG); } std::string NHyprlandSocket::send(const std::string& cmd) { @@ -64,12 +62,12 @@ std::string NHyprlandSocket::send(const std::string& cmd) { sockaddr_un serverAddress = {0}; serverAddress.sun_family = AF_UNIX; - std::string socketPath = getRuntimeDir() + "/" + HIS + "/.socket.sock"; + std::string socketPath = std::format("{}/{}/.socket.sock", getRuntimeDir(), HIS); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); if (connect(SERVERSOCKET, rc(&serverAddress), SUN_LEN(&serverAddress)) < 0) { - std::println("{}", failureString("Couldn't connect to " + socketPath + ". (4)")); + std::println("{}", failureString("Couldn't connect to {}. (4)", socketPath)); return ""; } diff --git a/hyprpm/src/core/PluginManager.cpp b/hyprpm/src/core/PluginManager.cpp index e85bdeec3..d9a25d500 100644 --- a/hyprpm/src/core/PluginManager.cpp +++ b/hyprpm/src/core/PluginManager.cpp @@ -51,7 +51,7 @@ static std::string getTempRoot() { exit(1); } - const auto STR = ENV + std::string{"/hyprpm/"}; + const auto STR = std::format("{}/hyprpm/", ENV); return STR; } @@ -203,7 +203,7 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& const std::string USERNAME = getpwuid(getuid())->pw_name; - m_szWorkingPluginDirectory = getTempRoot() + USERNAME; + m_szWorkingPluginDirectory = std::format("{}{}", getTempRoot(), USERNAME); if (!createSafeDirectory(m_szWorkingPluginDirectory)) { std::println(stderr, "\n{}", failureString("Could not prepare working dir for repo")); @@ -214,18 +214,18 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& std::string ret = execAndGet(std::format("cd {} && git clone --recursive '{}' {}", getTempRoot(), url, USERNAME)); - if (!std::filesystem::exists(m_szWorkingPluginDirectory + "/.git")) { + if (!std::filesystem::exists(std::format("{}/.git", m_szWorkingPluginDirectory))) { std::println(stderr, "\n{}", failureString("Could not clone the plugin repository. shell returned:\n{}", ret)); return false; } if (!rev.empty()) { - std::string ret = execAndGet("git -C " + m_szWorkingPluginDirectory + " reset --hard --recurse-submodules " + rev); + std::string ret = execAndGet(std::format("git -C {} reset --hard --recurse-submodules {}", m_szWorkingPluginDirectory, rev)); if (ret.compare(0, 6, "fatal:") == 0) { std::println(stderr, "\n{}", failureString("Could not check out revision {}. shell returned:\n{}", rev, ret)); return false; } - ret = execAndGet("git -C " + m_szWorkingPluginDirectory + " submodule update --init"); + ret = execAndGet(std::format("git -C {} submodule update --init", m_szWorkingPluginDirectory)); if (m_bVerbose) std::println("{}", verboseString("git submodule update --init returned: {}", ret)); } @@ -237,12 +237,12 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& std::unique_ptr pManifest; - if (std::filesystem::exists(m_szWorkingPluginDirectory + "/hyprpm.toml")) { + if (std::filesystem::exists(std::format("{}/hyprpm.toml", m_szWorkingPluginDirectory))) { progress.printMessageAbove(successString("found hyprpm manifest")); - pManifest = std::make_unique(MANIFEST_HYPRPM, m_szWorkingPluginDirectory + "/hyprpm.toml"); - } else if (std::filesystem::exists(m_szWorkingPluginDirectory + "/hyprload.toml")) { + pManifest = std::make_unique(MANIFEST_HYPRPM, std::format("{}/hyprpm.toml", m_szWorkingPluginDirectory)); + } else if (std::filesystem::exists(std::format("{}/hyprload.toml", m_szWorkingPluginDirectory))) { progress.printMessageAbove(successString("found hyprload manifest")); - pManifest = std::make_unique(MANIFEST_HYPRLOAD, m_szWorkingPluginDirectory + "/hyprload.toml"); + pManifest = std::make_unique(MANIFEST_HYPRLOAD, std::format("{}/hyprload.toml", m_szWorkingPluginDirectory)); } if (!pManifest) { @@ -256,17 +256,17 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& } progress.m_iSteps = 2; - progress.printMessageAbove(successString("parsed manifest, found " + std::to_string(pManifest->m_plugins.size()) + " plugins:")); + progress.printMessageAbove(successString("parsed manifest, found {} plugins:", pManifest->m_plugins.size())); for (auto const& pl : pManifest->m_plugins) { - std::string message = "→ " + pl.name + " by "; + std::string message = std::format("→ {} by ", pl.name); for (auto const& a : pl.authors) { - message += a + ", "; + message += std::format("{}, ", a); } if (pl.authors.size() > 0) { message.pop_back(); message.pop_back(); } - message += " version " + pl.version; + message += std::format(" version {}", pl.version); progress.printMessageAbove(message); } @@ -286,9 +286,9 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& progress.printMessageAbove(successString("commit pin {} matched hl, resetting", plugin)); - execAndGet("cd " + m_szWorkingPluginDirectory + " && git reset --hard --recurse-submodules '" + plugin + "'"); + execAndGet(std::format("cd {} && git reset --hard --recurse-submodules '{}'", m_szWorkingPluginDirectory, plugin)); - ret = execAndGet("git -C " + m_szWorkingPluginDirectory + " submodule update --init"); + ret = execAndGet(std::format("git -C {} submodule update --init", m_szWorkingPluginDirectory)); if (m_bVerbose) std::println("{}", verboseString("git submodule update --init returned: {}", ret)); @@ -333,13 +333,13 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& break; } - out += " -> " + *CMD_RAW + "\n" + execAndGet(*CMD_RAW) + "\n"; + out += std::format(" -> {}\n{}\n", *CMD_RAW, execAndGet(*CMD_RAW)); } if (m_bVerbose) std::println("{}", verboseString("shell returned: {}", out)); - if (!std::filesystem::exists(m_szWorkingPluginDirectory + "/" + p.output)) { + if (!std::filesystem::exists(std::format("{}/{}", m_szWorkingPluginDirectory, p.output))) { progress.printMessageAbove(failureString("Plugin {} failed to build.\n" " This likely means that the plugin is either outdated, not yet available for your version, or broken.\n" " If you are on -git, update first\n" @@ -360,7 +360,7 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& // add repo toml to DataState SPluginRepository repo; - std::string repohash = execAndGet("cd " + m_szWorkingPluginDirectory + " && git rev-parse HEAD"); + std::string repohash = execAndGet(std::format("cd {} && git rev-parse HEAD", m_szWorkingPluginDirectory)); if (repohash.length() > 0) repohash.pop_back(); auto lastSlash = url.find_last_of('/'); @@ -371,7 +371,7 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string& repo.rev = rev; repo.hash = repohash; for (auto const& p : pManifest->m_plugins) { - repo.plugins.push_back(SPlugin{p.name, m_szWorkingPluginDirectory + "/" + p.output, false, p.failed}); + repo.plugins.push_back(SPlugin{p.name, std::format("{}/{}", m_szWorkingPluginDirectory, p.output), false, p.failed}); } DataState::addNewPluginRepo(repo); @@ -414,7 +414,7 @@ bool CPluginManager::removePluginRepo(const SPluginRepoIdentifier& identifier) { eHeadersErrors CPluginManager::headersValid() { const auto HLVER = getHyprlandVersion(false); - if (!std::filesystem::exists(DataState::getHeadersPath() + "/share/pkgconfig/hyprland.pc")) + if (!std::filesystem::exists(std::format("{}/share/pkgconfig/hyprland.pc", DataState::getHeadersPath()))) return HEADERS_MISSING; // find headers commit @@ -439,7 +439,7 @@ eHeadersErrors CPluginManager::headersValid() { if (PATH.ends_with("protocols")) continue; - verHeader = trim(PATH.substr(2)) + "/hyprland/src/version.h"; + verHeader = std::format("{}/hyprland/src/version.h", trim(PATH.substr(2))); break; } @@ -516,7 +516,7 @@ bool CPluginManager::updateHeaders(bool force) { progress.print(); const std::string USERNAME = getpwuid(getuid())->pw_name; - const auto WORKINGDIR = getTempRoot() + "hyprland-" + USERNAME; + const auto WORKINGDIR = std::format("{}hyprland-{}", getTempRoot(), USERNAME); if (!createSafeDirectory(WORKINGDIR)) { std::println("\n{}", failureString("Could not prepare working dir for hl")); @@ -531,20 +531,21 @@ bool CPluginManager::updateHeaders(bool force) { // let us give a bit of leg-room for shallowing // due to timezones, etc. - const std::string SHALLOW_DATE = trim(HLVER.date).empty() ? "" : execAndGet("LC_TIME=\"en_US.UTF-8\" date --date='" + HLVER.date + " - 1 weeks' '+%a %b %d %H:%M:%S %Y'"); + const std::string SHALLOW_DATE = + trim(HLVER.date).empty() ? "" : execAndGet(std::format("LC_TIME=\"en_US.UTF-8\" date --date='{} - 1 weeks' '+%a %b %d %H:%M:%S %Y'", HLVER.date)); if (m_bVerbose && bShallow) progress.printMessageAbove(verboseString("will shallow since: {}", SHALLOW_DATE)); - std::string ret = - execAndGet(std::format("cd {} && git clone --recursive '{}' hyprland-{}{}", getTempRoot(), HL_URL, USERNAME, (bShallow ? " --shallow-since='" + SHALLOW_DATE + "'" : ""))); + std::string ret = execAndGet(std::format("cd {} && git clone --recursive '{}' hyprland-{}{}", getTempRoot(), HL_URL, USERNAME, + (bShallow ? std::format(" --shallow-since='{}'", SHALLOW_DATE) : std::string{}))); if (!std::filesystem::exists(WORKINGDIR)) { progress.printMessageAbove(failureString("Clone failed. Retrying without shallow.")); ret = execAndGet(std::format("cd {} && git clone --recursive '{}' hyprland-{}", getTempRoot(), HL_URL, USERNAME)); } - if (!std::filesystem::exists(WORKINGDIR + "/.git")) { + if (!std::filesystem::exists(std::format("{}/.git", WORKINGDIR))) { std::println(stderr, "\n{}", failureString("Could not clone the Hyprland repository. shell returned:\n{}", ret)); return false; } @@ -557,7 +558,7 @@ bool CPluginManager::updateHeaders(bool force) { if (m_bVerbose) progress.printMessageAbove(verboseString("will run: cd {} && git checkout {} 2>&1", WORKINGDIR, HLVER.hash)); - ret = execAndGet("cd " + WORKINGDIR + " && git checkout " + HLVER.hash + " 2>&1"); + ret = execAndGet(std::format("cd {} && git checkout {} 2>&1", WORKINGDIR, HLVER.hash)); if (ret.contains("fatal: unable to read tree")) { std::println(stderr, "\n{}", @@ -569,7 +570,7 @@ bool CPluginManager::updateHeaders(bool force) { if (m_bVerbose) progress.printMessageAbove(verboseString("git returned (co): {}", ret)); - ret = execAndGet("cd " + WORKINGDIR + " ; git rm subprojects/tracy ; git submodule update --init 2>&1 ; git reset --hard --recurse-submodules " + HLVER.hash); + ret = execAndGet(std::format("cd {} ; git rm subprojects/tracy ; git submodule update --init 2>&1 ; git reset --hard --recurse-submodules {}", WORKINGDIR, HLVER.hash)); if (m_bVerbose) progress.printMessageAbove(verboseString("git returned (rs): {}", ret)); @@ -691,7 +692,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { progress.print(); const std::string USERNAME = getpwuid(getuid())->pw_name; - m_szWorkingPluginDirectory = getTempRoot() + USERNAME; + m_szWorkingPluginDirectory = std::format("{}{}", getTempRoot(), USERNAME); std::vector failedRepos; @@ -709,7 +710,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { bool update = forceUpdateAll; progress.m_iSteps++; - progress.m_szCurrentMessage = "Updating " + repo.name; + progress.m_szCurrentMessage = std::format("Updating {}", repo.name); progress.print(); progress.printMessageAbove(infoString("checking for updates for {}", repo.name)); @@ -720,7 +721,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { std::string ret = execAndGet(std::format("cd {} && git clone --recursive '{}' {}", getTempRoot(), repo.url, USERNAME)); - if (!std::filesystem::exists(m_szWorkingPluginDirectory + "/.git")) { + if (!std::filesystem::exists(std::format("{}/.git", m_szWorkingPluginDirectory))) { std::println(stderr, "\n{}", failureString("could not clone repo: shell returned: {}", ret)); markRepoFailed(repo, true); continue; @@ -729,7 +730,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { if (!repo.rev.empty()) { progress.printMessageAbove(infoString("Plugin has revision set, resetting: {}", repo.rev)); - std::string ret = execAndGet("git -C " + m_szWorkingPluginDirectory + " reset --hard --recurse-submodules \'" + repo.rev + "\'"); + std::string ret = execAndGet(std::format("git -C {} reset --hard --recurse-submodules \'{}\'", m_szWorkingPluginDirectory, repo.rev)); if (ret.compare(0, 6, "fatal:") == 0) { std::println(stderr, "\n{}", failureString("could not check out revision {}: shell returned:\n{}", repo.rev, ret)); @@ -740,7 +741,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { if (!update) { // check if git has updates - std::string hash = execAndGet("cd " + m_szWorkingPluginDirectory + " && git rev-parse HEAD"); + std::string hash = execAndGet(std::format("cd {} && git rev-parse HEAD", m_szWorkingPluginDirectory)); if (!hash.empty()) hash.pop_back(); @@ -764,12 +765,12 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { std::unique_ptr pManifest; - if (std::filesystem::exists(m_szWorkingPluginDirectory + "/hyprpm.toml")) { + if (std::filesystem::exists(std::format("{}/hyprpm.toml", m_szWorkingPluginDirectory))) { progress.printMessageAbove(successString("found hyprpm manifest")); - pManifest = std::make_unique(MANIFEST_HYPRPM, m_szWorkingPluginDirectory + "/hyprpm.toml"); - } else if (std::filesystem::exists(m_szWorkingPluginDirectory + "/hyprload.toml")) { + pManifest = std::make_unique(MANIFEST_HYPRPM, std::format("{}/hyprpm.toml", m_szWorkingPluginDirectory)); + } else if (std::filesystem::exists(std::format("{}/hyprload.toml", m_szWorkingPluginDirectory))) { progress.printMessageAbove(successString("found hyprload manifest")); - pManifest = std::make_unique(MANIFEST_HYPRLOAD, m_szWorkingPluginDirectory + "/hyprload.toml"); + pManifest = std::make_unique(MANIFEST_HYPRLOAD, std::format("{}/hyprload.toml", m_szWorkingPluginDirectory)); } if (!pManifest) { @@ -804,7 +805,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { progress.printMessageAbove(successString("commit pin {} matched hl, resetting", plugin)); - execAndGet("cd " + m_szWorkingPluginDirectory + " && git reset --hard --recurse-submodules '" + plugin + "'"); + execAndGet(std::format("cd {} && git reset --hard --recurse-submodules '{}'", m_szWorkingPluginDirectory, plugin)); } if (commitPinFailed) @@ -836,13 +837,13 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { break; } - out += " -> " + *CMD_RAW + "\n" + execAndGet(*CMD_RAW) + "\n"; + out += std::format(" -> {}\n{}\n", *CMD_RAW, execAndGet(*CMD_RAW)); } if (m_bVerbose) std::println("{}", verboseString("shell returned: {}", out)); - if (!std::filesystem::exists(m_szWorkingPluginDirectory + "/" + p.output)) { + if (!std::filesystem::exists(std::format("{}/{}", m_szWorkingPluginDirectory, p.output))) { std::println(stderr, "\n{}\n" " This likely means that the plugin is either outdated, not yet available for your version, or broken.\n" @@ -860,9 +861,9 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { // add repo toml to DataState SPluginRepository newrepo = repo; newrepo.plugins.clear(); - execAndGet("cd " + m_szWorkingPluginDirectory + - " && git pull --recurse-submodules && git reset --hard --recurse-submodules"); // repo hash in the state.toml has to match head and not any pin - std::string repohash = execAndGet("cd " + m_szWorkingPluginDirectory + " && git rev-parse HEAD"); + execAndGet(std::format("cd {} && git pull --recurse-submodules && git reset --hard --recurse-submodules", + m_szWorkingPluginDirectory)); // repo hash in the state.toml has to match head and not any pin + std::string repohash = execAndGet(std::format("cd {} && git rev-parse HEAD", m_szWorkingPluginDirectory)); if (!repohash.empty()) repohash.pop_back(); // a build failure must not record the fetched hash: the next update would consider the @@ -871,7 +872,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) { for (auto const& p : pManifest->m_plugins) { const auto OLDPLUGINIT = std::ranges::find_if(repo.plugins, [&](const auto& other) { return other.name == p.name; }); newrepo.plugins.emplace_back(SPlugin{.name = p.name, - .filename = m_szWorkingPluginDirectory + "/" + p.output, + .filename = std::format("{}/{}", m_szWorkingPluginDirectory, p.output), .enabled = OLDPLUGINIT != repo.plugins.end() ? OLDPLUGINIT->enabled : false, .failed = p.failed}); } @@ -1011,7 +1012,7 @@ ePluginLoadStateReturn CPluginManager::ensurePluginsLoadState(bool forceReload) for (auto const& p : loadedPlugins) { if (forceReload || !enabled(p)) { // unload - if (!loadUnloadPlugin(HYPRPMPATH / repoForName(p) / (p + ".so"), false)) { + if (!loadUnloadPlugin(HYPRPMPATH / repoForName(p) / std::format("{}.so", p), false)) { std::println("{}", infoString("{} will be unloaded after restarting Hyprland", p)); hyprlandVersionMismatch = true; } else @@ -1057,9 +1058,9 @@ bool CPluginManager::loadUnloadPlugin(const std::string& path, bool load) { } if (load) - NHyprlandSocket::send("/plugin load " + path); + NHyprlandSocket::send(std::format("/plugin load {}", path)); else - NHyprlandSocket::send("/plugin unload " + path); + NHyprlandSocket::send(std::format("/plugin unload {}", path)); return true; } @@ -1074,7 +1075,7 @@ void CPluginManager::listAllPlugins() { std::println(" │ Plugin {}", p.name); if (!p.failed) - std::println(" └─ enabled: {}", (p.enabled ? std::string{Colors::GREEN} + "true" : std::string{Colors::RED} + "false")); + std::println(" └─ enabled: {}", (p.enabled ? std::format("{}true", Colors::GREEN) : std::format("{}false", Colors::RED))); else std::println(" └─ enabled: {}Plugin failed to build", Colors::RED); @@ -1084,7 +1085,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(icon) + " " + std::to_string(durationMs) + " " + std::to_string(color) + " " + message); + NHyprlandSocket::send(std::format("/notify {} {} {} {}", sc(icon), durationMs, color, message)); } std::string CPluginManager::headerError(const eHeadersErrors err) { @@ -1125,7 +1126,7 @@ bool CPluginManager::hasDeps() { std::vector deps = {"cpio", "cmake", "pkg-config", "g++", "gcc", "git"}; for (auto const& d : deps) { - if (!execAndGet("command -v " + d).contains("/")) { + if (!execAndGet(std::format("command -v {}", d)).contains("/")) { std::println(stderr, "{}", failureString("Missing dependency: {}", d)); hasAllDeps = false; } diff --git a/hyprpm/src/helpers/Sys.cpp b/hyprpm/src/helpers/Sys.cpp index e9dd4c85f..bfab9fb7a 100644 --- a/hyprpm/src/helpers/Sys.cpp +++ b/hyprpm/src/helpers/Sys.cpp @@ -158,7 +158,7 @@ bool NSys::root::install(const std::string& what, const std::string& where, cons if (!std::ranges::all_of(mode, [](const char& c) { return c >= '0' && c <= '9'; })) return false; - CProcess proc(subin(), {"install", "-m" + mode, "-o", "0", "-g", "0", what, where}); + CProcess proc(subin(), {"install", std::format("-m{}", mode), "-o", "0", "-g", "0", what, where}); return proc.runSync() && proc.exitCode() == 0; } diff --git a/hyprtester/src/hyprctlCompat.cpp b/hyprtester/src/hyprctlCompat.cpp index dbeee93d5..fca822193 100644 --- a/hyprtester/src/hyprctlCompat.cpp +++ b/hyprtester/src/hyprctlCompat.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include using namespace Hyprutils::Memory; @@ -26,12 +27,10 @@ static int getUID() { static std::string getRuntimeDir() { const auto XDG = getenv("XDG_RUNTIME_DIR"); - if (!XDG) { - const std::string USERID = std::to_string(getUID()); - return "/run/user/" + USERID + "/hypr"; - } + if (!XDG) + return std::format("/run/user/{}/hypr", getUID()); - return std::string{XDG} + "/hypr"; + return std::format("{}/hypr", XDG); } std::vector instances() { @@ -55,7 +54,7 @@ std::vector instances() { } catch (std::exception& e) { continue; } // read file - std::ifstream ifs(el.path().string() + "/hyprland.lock"); + std::ifstream ifs(std::format("{}/hyprland.lock", el.path().string())); int i = 0; for (std::string line; std::getline(ifs, line); ++i) { @@ -93,7 +92,7 @@ std::string getFromSocket(const std::string& cmd) { sockaddr_un serverAddress = {0}; serverAddress.sun_family = AF_UNIX; - std::string socketPath = getRuntimeDir() + "/" + HIS + "/.socket.sock"; + std::string socketPath = std::format("{}/{}/.socket.sock", getRuntimeDir(), HIS); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1); diff --git a/hyprtester/src/tests/clients/child-window.cpp b/hyprtester/src/tests/clients/child-window.cpp index 4c3e9d630..9a89608fe 100644 --- a/hyprtester/src/tests/clients/child-window.cpp +++ b/hyprtester/src/tests/clients/child-window.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -49,7 +50,7 @@ namespace { CClient::CClient() { NLog::log("{}Attempting to start child-window client", Colors::YELLOW); - this->proc = makeShared(binaryDir + "/child-window", std::vector{}); + this->proc = makeShared(std::format("{}/child-window", binaryDir), std::vector{}); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); diff --git a/hyprtester/src/tests/clients/keyboard-modifiers.cpp b/hyprtester/src/tests/clients/keyboard-modifiers.cpp index 398d14f76..1409def63 100644 --- a/hyprtester/src/tests/clients/keyboard-modifiers.cpp +++ b/hyprtester/src/tests/clients/keyboard-modifiers.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -34,7 +35,7 @@ namespace { CClient::CClient() { Tests::killAllWindows(); - this->proc = makeShared(binaryDir + "/keyboard-modifiers", std::vector{}); + this->proc = makeShared(std::format("{}/keyboard-modifiers", binaryDir), std::vector{}); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); diff --git a/hyprtester/src/tests/clients/pointer-scroll.cpp b/hyprtester/src/tests/clients/pointer-scroll.cpp index 57b93a758..611e294e8 100644 --- a/hyprtester/src/tests/clients/pointer-scroll.cpp +++ b/hyprtester/src/tests/clients/pointer-scroll.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -33,7 +34,7 @@ namespace { } CClient::CClient() { - this->proc = makeShared(binaryDir + "/pointer-scroll", std::vector{}); + this->proc = makeShared(std::format("{}/pointer-scroll", binaryDir), std::vector{}); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); diff --git a/hyprtester/src/tests/clients/pointer-warp.cpp b/hyprtester/src/tests/clients/pointer-warp.cpp index 08634b23f..7f5868640 100644 --- a/hyprtester/src/tests/clients/pointer-warp.cpp +++ b/hyprtester/src/tests/clients/pointer-warp.cpp @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -34,7 +35,7 @@ namespace { } CClient::CClient() { - this->proc = makeShared(binaryDir + "/pointer-warp", std::vector{}); + this->proc = makeShared(std::format("{}/pointer-warp", binaryDir), std::vector{}); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); diff --git a/hyprtester/src/tests/clients/shortcut-inhibitor.cpp b/hyprtester/src/tests/clients/shortcut-inhibitor.cpp index 49c78f593..1c1480910 100644 --- a/hyprtester/src/tests/clients/shortcut-inhibitor.cpp +++ b/hyprtester/src/tests/clients/shortcut-inhibitor.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -34,7 +35,7 @@ namespace { CClient::CClient() { Tests::killAllWindows(); - this->proc = makeShared(binaryDir + "/shortcut-inhibitor", std::vector{}); + this->proc = makeShared(std::format("{}/shortcut-inhibitor", binaryDir), std::vector{}); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); @@ -163,7 +164,7 @@ TEST_CASE(shortcutInhibitor) { EXPECT(ok, true); //basic keybind test - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'))"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'))", flagFile)), "ok"); OK(getFromSocket("/eval hl.plugin.test.keybind(1, 7, 29)")); EXPECT(attemptCheckFlag(20, 50), false); OK(getFromSocket("/eval hl.plugin.test.keybind(0, 0, 29)")); @@ -171,7 +172,7 @@ TEST_CASE(shortcutInhibitor) { //keybind bypass flag test EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { dont_inhibit = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ dont_inhibit = true }})", flagFile)), "ok"); OK(getFromSocket("/eval hl.plugin.test.keybind(1, 7, 29)")); EXPECT(attemptCheckFlag(20, 50), true); OK(getFromSocket("/eval hl.plugin.test.keybind(0, 0, 29)")); diff --git a/hyprtester/src/tests/clients/surface-scale-transform.cpp b/hyprtester/src/tests/clients/surface-scale-transform.cpp index 83833a7a7..0574a1449 100644 --- a/hyprtester/src/tests/clients/surface-scale-transform.cpp +++ b/hyprtester/src/tests/clients/surface-scale-transform.cpp @@ -58,7 +58,7 @@ static bool waitForClientWindow(pid_t pid, int timeoutMs) { } CClient::CClient() { - m_proc = makeShared(binaryDir + "/surface-scale-transform", std::vector{}); + m_proc = makeShared(std::format("{}/surface-scale-transform", binaryDir), std::vector{}); m_proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); int pipeFds1[2], pipeFds2[2]; @@ -85,8 +85,8 @@ CClient::CClient() { } while (pollRet == -1 && errno == EINTR); if (pollRet != 1 || !(m_fds.revents & POLLIN)) - throw std::runtime_error(std::format("startup stdout poll failed: ret={} revents={} alive={} pid={} binary={}", pollRet, m_fds.revents, Tests::processAlive(m_proc->pid()), - m_proc->pid(), binaryDir + "/surface-scale-transform")); + throw std::runtime_error(std::format("startup stdout poll failed: ret={} revents={} alive={} pid={} binary={}/surface-scale-transform", pollRet, m_fds.revents, + Tests::processAlive(m_proc->pid()), m_proc->pid(), binaryDir)); m_readBuf.fill(0); const ssize_t bytesRead = read(m_readFd.get(), m_readBuf.data(), m_readBuf.size() - 1); @@ -115,7 +115,7 @@ CClient::~CClient() { } std::string CClient::command(const std::string& command) { - const std::string cmd = command + "\n"; + const std::string cmd = std::format("{}\n", command); if ((size_t)write(m_writeFd.get(), cmd.c_str(), cmd.length()) != cmd.length()) return ""; diff --git a/hyprtester/src/tests/clients/xdg-interactive.cpp b/hyprtester/src/tests/clients/xdg-interactive.cpp index 292f1c7b6..89fddce07 100644 --- a/hyprtester/src/tests/clients/xdg-interactive.cpp +++ b/hyprtester/src/tests/clients/xdg-interactive.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -140,7 +141,7 @@ static bool click(uint32_t button, bool pressed) { } static std::optional statusValue(const std::string& line, const std::string& key) { - const auto KEY = key + "="; + const auto KEY = std::format("{}=", key); auto pos = line.find(KEY); if (pos == std::string::npos) return std::nullopt; @@ -209,7 +210,7 @@ std::optional CClient::takeLineContaining(const std::string& marker CClient::CClient() { NLog::log("{}Attempting to start xdg-interactive client", Colors::YELLOW); - proc = makeShared(binaryDir + "/xdg-interactive", std::vector{}); + proc = makeShared(std::format("{}/xdg-interactive", binaryDir), std::vector{}); proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); int procInPipeFd[2], procOutPipeFd[2]; diff --git a/hyprtester/src/tests/main/dwindle.cpp b/hyprtester/src/tests/main/dwindle.cpp index 8aa68777a..683060530 100644 --- a/hyprtester/src/tests/main/dwindle.cpp +++ b/hyprtester/src/tests/main/dwindle.cpp @@ -3,6 +3,8 @@ #include "../../hyprctlCompat.hpp" #include "tests.hpp" +#include + TEST_CASE(dwindleFloatClamp) { for (auto const& win : {"a", "b", "c"}) { if (!Tests::spawnKitty(win)) { @@ -202,7 +204,7 @@ TEST_CASE(dwindleForceSplitOnMoveToWorkspace) { OK(getFromSocket("/dispatch hl.dsp.focus({ workspace = '1' })")); ASSERT(!!Tests::spawnKitty("kitty"), true); - std::string posBefore = "at: " + Tests::getAttribute(getFromSocket("/activewindow"), "at"); + std::string posBefore = std::format("at: {}", Tests::getAttribute(getFromSocket("/activewindow"), "at")); OK(getFromSocket("/eval hl.config({ dwindle = { force_split = 2 } })")); OK(getFromSocket("/dispatch hl.dsp.cursor.move_to_corner({ corner = 3 })")); // top left @@ -228,8 +230,8 @@ TEST_CASE(dwindleMoveAcrossToggledSplit) { // Window A, now on top, is to be moved auto origWinB = getFromSocket("/activewindow"); - auto expectPos = "at: " + Tests::getAttribute(origWinB, "at"); - auto expectSize = "size: " + Tests::getAttribute(origWinB, "size"); + auto expectPos = std::format("at: {}", Tests::getAttribute(origWinB, "at")); + auto expectSize = std::format("size: {}", Tests::getAttribute(origWinB, "size")); OK(getFromSocket("/dispatch hl.dsp.focus({ window = 'class:a' })")); OK(getFromSocket("/dispatch hl.dsp.window.move({ direction = 'down' })")); @@ -252,7 +254,7 @@ TEST_CASE(dwindleMoveSmallWindowAcrossSplit) { } // Window B, on the left, is the smaller one - auto posBefore = "at: " + Tests::getAttribute(getFromSocket("/activewindow"), "at"); + auto posBefore = std::format("at: {}", Tests::getAttribute(getFromSocket("/activewindow"), "at")); OK(getFromSocket("/dispatch hl.dsp.window.move({ direction = 'right' })")); diff --git a/hyprtester/src/tests/main/exec.cpp b/hyprtester/src/tests/main/exec.cpp index ff19edfe6..f225a1743 100644 --- a/hyprtester/src/tests/main/exec.cpp +++ b/hyprtester/src/tests/main/exec.cpp @@ -32,7 +32,7 @@ TEST_CASE(processSpawning) { continue; } - const std::string sleepParentComm = Tests::execAndGet("cat \"/proc/$(ps -o ppid:1= -p " + sleepPidS + ")/comm\""); + const std::string sleepParentComm = Tests::execAndGet(std::format("cat \"/proc/$(ps -o ppid:1= -p {})/comm\"", sleepPidS)); NLog::log("{}Expecting that sleep's parent is Hyprland", Colors::YELLOW); EXPECT_CONTAINS(sleepParentComm, "Hyprland"); diff --git a/hyprtester/src/tests/main/hyprctl.cpp b/hyprtester/src/tests/main/hyprctl.cpp index b89d71541..e844be908 100644 --- a/hyprtester/src/tests/main/hyprctl.cpp +++ b/hyprtester/src/tests/main/hyprctl.cpp @@ -3,6 +3,7 @@ #include "../../hyprctlCompat.hpp" #include #include +#include #include #include #include "../shared.hpp" @@ -25,7 +26,7 @@ static std::string getCommandStdOut(std::string command) { } static void setWindowProp(const std::string& selector, const std::string& prop, const std::string& value) { - getFromSocket("/dispatch hl.dsp.window.set_prop({ window = '" + selector + "', prop = '" + prop + "', value = '" + value + "' })"); + getFromSocket(std::format("/dispatch hl.dsp.window.set_prop({{ window = '{}', prop = '{}', value = '{}' }})", selector, prop, value)); } TEST_CASE(hyprctlDevicesActiveLayoutIndex) { @@ -34,9 +35,9 @@ TEST_CASE(hyprctlDevicesActiveLayoutIndex) { for (uint8_t i = 0; i < 3; i++) { // set layout - getFromSocket("/switchxkblayout all " + std::to_string(i)); + getFromSocket(std::format("/switchxkblayout all {}", i)); std::string devicesJson = getFromSocket("j/devices"); - std::string expected = R"("active_layout_index": )" + std::to_string(i); + std::string expected = std::format(R"("active_layout_index": {})", i); // check layout index EXPECT_CONTAINS(devicesJson, expected); } diff --git a/hyprtester/src/tests/main/keybinds.cpp b/hyprtester/src/tests/main/keybinds.cpp index 75a316f21..c45160f57 100644 --- a/hyprtester/src/tests/main/keybinds.cpp +++ b/hyprtester/src/tests/main/keybinds.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include "../../shared.hpp" #include "../../hyprctlCompat.hpp" @@ -11,7 +12,7 @@ using namespace Hyprutils::Memory; static std::string flagFile = "/tmp/hyprtester-keybinds.txt"; static std::string pluginKeybindCmd(bool pressed, uint32_t modifier, uint32_t key) { - return "/eval hl.plugin.test.keybind(" + std::to_string(pressed ? 1 : 0) + ", " + std::to_string(modifier) + ", " + std::to_string(key) + ")"; + return std::format("/eval hl.plugin.test.keybind({}, {}, {})", pressed ? 1 : 0, modifier, key); } static std::string pluginKeybindMaskCmd(bool pressed, const std::vector& mods, uint32_t key) { @@ -23,11 +24,11 @@ static std::string pluginKeybindMaskCmd(bool pressed, const std::vector } static std::string pluginScrollCmd(int delta) { - return "/eval hl.plugin.test.scroll(" + std::to_string(delta) + ")"; + return std::format("/eval hl.plugin.test.scroll({})", delta); } static std::string pluginClickCmd(bool pressed, uint32_t button) { - return "/eval hl.plugin.test.click(" + std::to_string(button) + ", " + std::to_string(pressed ? 1 : 0) + ")"; + return std::format("/eval hl.plugin.test.click({}, {})", button, pressed ? 1 : 0); } // Because i don't feel like changing someone elses code. @@ -104,7 +105,7 @@ static CUniquePointer spawnRemoteControlKitty() { SUBTEST(bind) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'))"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'))", flagFile)), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); // await flag @@ -116,7 +117,7 @@ SUBTEST(bind) { SUBTEST(bindKey) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('Y', hl.dsp.exec_cmd('touch " + flagFile + "'))"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('Y', hl.dsp.exec_cmd('touch {}'))", flagFile)), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 0, 29))); // await flag @@ -128,7 +129,7 @@ SUBTEST(bindKey) { SUBTEST(longPress) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { long_press = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ long_press = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); @@ -144,7 +145,7 @@ SUBTEST(longPress) { } SUBTEST(keyLongPress) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { long_press = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('Y', hl.dsp.exec_cmd('touch {}'), {{ long_press = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 0, 29))); @@ -161,7 +162,7 @@ SUBTEST(keyLongPress) { SUBTEST(longPressRelease) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { long_press = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ long_press = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); @@ -177,7 +178,7 @@ SUBTEST(longPressRelease) { } SUBTEST(longPressOnlyKeyRelease) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { long_press = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ long_press = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); @@ -195,7 +196,7 @@ SUBTEST(longPressOnlyKeyRelease) { SUBTEST(repeat) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { repeating = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ repeating = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); @@ -225,7 +226,7 @@ SUBTEST(keyRepeat) { } EXPECT(ok, true); - EXPECT(getFromSocket("/eval hl.bind('Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { repeating = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('Y', hl.dsp.exec_cmd('touch {}'), {{ repeating = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 0, 29))); @@ -255,7 +256,7 @@ SUBTEST(repeatRelease) { } EXPECT(ok, true); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { repeating = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ repeating = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); @@ -277,7 +278,7 @@ SUBTEST(repeatRelease) { SUBTEST(repeatOnlyKeyRelease) { EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { repeating = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ repeating = true }})", flagFile)), "ok"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok"); // press keybind OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); @@ -591,7 +592,7 @@ SUBTEST(bindsAfterScroll) { NLog::log("{}Testing binds after scroll", Colors::GREEN); clearFlag(); - OK(getFromSocket("/eval hl.bind('ALT + w', hl.dsp.exec_cmd('touch " + flagFile + "'))")); + OK(getFromSocket(std::format("/eval hl.bind('ALT + w', hl.dsp.exec_cmd('touch {}'))", flagFile))); // press keybind before scroll OK(getFromSocket(pluginKeybindCmd(true, 0, 108))); // Alt_R press @@ -620,7 +621,7 @@ SUBTEST(submapUniversal) { NLog::log("{}Testing submap universal", Colors::GREEN); EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { submap_universal = true })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ submap_universal = true }})", flagFile)), "ok"); EXPECT_CONTAINS(getFromSocket("/submap"), "default"); // keybind works on default submap @@ -649,7 +650,8 @@ SUBTEST(perDeviceKeybind) { // Inclusive EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { device = { inclusive = true, list = { 'test-keyboard-1' } } })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ device = {{ inclusive = true, list = {{ 'test-keyboard-1' }} }} }})", flagFile)), + "ok"); OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); EXPECT(attemptCheckFlag(20, 50), true); OK(getFromSocket(pluginKeybindCmd(false, 0, 29))); @@ -657,7 +659,8 @@ SUBTEST(perDeviceKeybind) { // Exclusive EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { device = { inclusive = false, list = { 'test-keyboard-1' } } })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ device = {{ inclusive = false, list = {{ 'test-keyboard-1' }} }} }})", flagFile)), + "ok"); OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); EXPECT(attemptCheckFlag(20, 50), false); OK(getFromSocket(pluginKeybindCmd(false, 0, 29))); @@ -665,8 +668,9 @@ SUBTEST(perDeviceKeybind) { // With description EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + - "'), { description = 'test description', device = { inclusive = true, list = { 'test-keyboard-1' } } })"), + EXPECT(getFromSocket(std::format( + "/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ description = 'test description', device = {{ inclusive = true, list = {{ 'test-keyboard-1' }} }} }})", + flagFile)), "ok"); OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); EXPECT(attemptCheckFlag(20, 50), true); @@ -675,7 +679,7 @@ SUBTEST(perDeviceKeybind) { // Tags EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { device = { inclusive = true, list = { 'test-tag' } } })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ device = {{ inclusive = true, list = {{ 'test-tag' }} }} }})", flagFile)), "ok"); OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); EXPECT(attemptCheckFlag(20, 50), true); OK(getFromSocket(pluginKeybindCmd(false, 0, 29))); @@ -687,7 +691,8 @@ SUBTEST(unbind) { // unbind should normalize the string: no spaces, lowercase OK EXPECT(checkFlag(), false); - EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + "'), { device = { inclusive = true, list = { 'test-keyboard-1' } } })"), "ok"); + EXPECT(getFromSocket(std::format("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ device = {{ inclusive = true, list = {{ 'test-keyboard-1' }} }} }})", flagFile)), + "ok"); EXPECT(getFromSocket("/eval hl.unbind(' super + y ')"), "ok"); OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); diff --git a/hyprtester/src/tests/main/layer.cpp b/hyprtester/src/tests/main/layer.cpp index 49bc53026..abe205f2e 100644 --- a/hyprtester/src/tests/main/layer.cpp +++ b/hyprtester/src/tests/main/layer.cpp @@ -21,7 +21,7 @@ static bool spawnLayer(const std::string& namespace_, const std::vector #include #include +#include #include #include #include @@ -692,9 +693,9 @@ TEST_CASE(rollFocus) { // rotate the windows vector along with the actual windows // the rolling behavior of the window focus should follow the // rotating behavior of std::ranges::rotate - OK(getFromSocket("/dispatch hl.dsp.layout('" + dir + "')")); + OK(getFromSocket(std::format("/dispatch hl.dsp.layout('{}')", dir))); std::ranges::rotate(windows.begin(), pivot, windows.end()); - ASSERT_CONTAINS(getFromSocket("/activewindow"), "class: " + windows.back()); + ASSERT_CONTAINS(getFromSocket("/activewindow"), std::format("class: {}", windows.back())); }; for (auto const& win : windows) { @@ -782,7 +783,7 @@ TEST_CASE(centerMasterColumnResize) { // focus a window by class and read its {left edge x, height} from /activewindow auto geomOf = [&](const std::string& cls) -> std::pair { - getFromSocket("/dispatch hl.dsp.focus({ window = 'class:" + cls + "' })"); + getFromSocket(std::format("/dispatch hl.dsp.focus({{ window = 'class:{}' }})", cls)); const auto STR = getFromSocket("/activewindow"); const auto AT = Tests::getAttribute(STR, "at"); // "x,y" const auto SZ = Tests::getAttribute(STR, "size"); // "w,h" @@ -793,7 +794,7 @@ TEST_CASE(centerMasterColumnResize) { // resizeactive-style relative resize of a specific window along y auto resizeY = [&](const std::string& cls, int dy) { - return getFromSocket("/dispatch hl.dsp.window.resize({ x = 0, y = " + std::to_string(dy) + ", relative = true, window = 'class:" + cls + "' })"); + return getFromSocket(std::format("/dispatch hl.dsp.window.resize({{ x = 0, y = {}, relative = true, window = 'class:{}' }})", dy, cls)); }; // `top` and `bottom` share one column and must resize vertically (one grows, the other shrinks, diff --git a/hyprtester/src/tests/main/scroll.cpp b/hyprtester/src/tests/main/scroll.cpp index add4a7aaf..de3e24d17 100644 --- a/hyprtester/src/tests/main/scroll.cpp +++ b/hyprtester/src/tests/main/scroll.cpp @@ -3,6 +3,8 @@ #include "../../hyprctlCompat.hpp" #include "tests.hpp" +#include + #include using namespace Hyprutils::Utils; @@ -26,7 +28,7 @@ static std::string getClientBlock(const std::string& clients, const std::string& return NPOS; }; - const std::string CLASS_TARGET = "class: " + cls + "\n"; + const std::string CLASS_TARGET = std::format("class: {}\n", cls); // block by block till you find the class within a block size_t blockStart = findNextBlockHeader(clients, 0); @@ -56,7 +58,7 @@ static bool spawnLayer(const std::string& namespace_, const std::vector #include #include +#include #include #include #include @@ -32,7 +33,7 @@ static std::string spawnKittyActivating(const std::string& class_ = "kitty_activ (void)close(fd); const std::vector args = { - "-o", "allow_remote_control=yes", "--", "/bin/sh", "-c", "while [ -f \"" + tmpFilename + "\" ]; do :; done; kitten @ focus-window; sleep infinity"}; + "-o", "allow_remote_control=yes", "--", "/bin/sh", "-c", std::format("while [ -f \"{}\" ]; do :; done; kitten @ focus-window; sleep infinity", tmpFilename)}; if (!Tests::spawnKitty(class_, args)) { NLog::red("Error: failed to spawn kitty"); @@ -71,7 +72,7 @@ TEST_CASE(swapWindow) { // Test swapwindow by direction { getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_A' })"); - auto pos = "at: " + Tests::getAttribute(getFromSocket("/activewindow"), "at"); + auto pos = std::format("at: {}", Tests::getAttribute(getFromSocket("/activewindow"), "at")); NLog::log("{}Testing kitty_A {}, swapwindow with direction 'r'", Colors::YELLOW, pos); OK(getFromSocket("/dispatch hl.dsp.window.swap({ direction = 'right' })")); @@ -83,7 +84,7 @@ TEST_CASE(swapWindow) { // Test swapwindow by class { getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_A' })"); - auto pos = "at: " + Tests::getAttribute(getFromSocket("/activewindow"), "at"); + auto pos = std::format("at: {}", Tests::getAttribute(getFromSocket("/activewindow"), "at")); NLog::log("{}Testing kitty_A {}, swapwindow with class:kitty_B", Colors::YELLOW, pos); OK(getFromSocket("/dispatch hl.dsp.window.swap({ target = 'class:kitty_B' })")); @@ -97,7 +98,7 @@ TEST_CASE(swapWindow) { getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_B' })"); auto addr = getWindowAddress(getFromSocket("/activewindow")); getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_A' })"); - auto pos = "at: " + Tests::getAttribute(getFromSocket("/activewindow"), "at"); + auto pos = std::format("at: {}", Tests::getAttribute(getFromSocket("/activewindow"), "at")); NLog::log("{}Testing kitty_A {}, swapwindow with address:0x{}(kitty_B)", Colors::YELLOW, pos, addr); OK(getFromSocket(std::format("/dispatch hl.dsp.window.swap({{ target = 'address:0x{}' }})", addr))); @@ -120,7 +121,7 @@ TEST_CASE(swapWindow) { { getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_B' })"); auto addr = getWindowAddress(getFromSocket("/activewindow")); - auto ws = "workspace: " + Tests::getAttribute(getFromSocket("/activewindow"), "workspace"); + auto ws = std::format("workspace: {}", Tests::getAttribute(getFromSocket("/activewindow"), "workspace")); NLog::log("{}Sending address:0x{}(kitty_B) to workspace \"swapwindow2\"", Colors::YELLOW, addr); OK(getFromSocket("/dispatch hl.dsp.window.move({ workspace = 'name:swapwindow2', follow = false })")); @@ -1356,7 +1357,7 @@ TEST_CASE(monitorrule) { Tests::spawnKitty("monitor_kitty"); ASSERT(Tests::windowCount(), 1); const auto MON_SRC_ID = Tests::getAttribute(getFromSocket("/activewindow"), "monitor"); - ASSERT_CONTAINS(MONALL, "HEADLESS-3 (ID " + MON_SRC_ID); + ASSERT_CONTAINS(MONALL, std::format("HEADLESS-3 (ID {}", MON_SRC_ID)); EXPECT_CONTAINS(getFromSocket("/activeworkspace"), "HEADLESS-3"); Tests::killAllWindows(); @@ -1368,7 +1369,7 @@ TEST_CASE(monitorrule) { Tests::spawnKitty("silent_kitty"); ASSERT(Tests::windowCount(), 1); const auto SILENT_SRC_ID = Tests::getAttribute(getFromSocket("/clients"), "monitor"); - ASSERT_CONTAINS(MONALL, "HEADLESS-3 (ID " + SILENT_SRC_ID); + ASSERT_CONTAINS(MONALL, std::format("HEADLESS-3 (ID {}", SILENT_SRC_ID)); EXPECT_CONTAINS(getFromSocket("/activeworkspace"), "HEADLESS-2"); } diff --git a/hyprtester/src/tests/shared.cpp b/hyprtester/src/tests/shared.cpp index 9464a053c..ed3fef4c0 100644 --- a/hyprtester/src/tests/shared.cpp +++ b/hyprtester/src/tests/shared.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include "../shared.hpp" #include "../hyprctlCompat.hpp" @@ -104,7 +105,7 @@ bool Tests::killAllWindows() { auto pos = str.find("Window "); while (pos != std::string::npos) { auto pos2 = str.find(" -> ", pos); - getFromSocket("/dispatch hl.dsp.window.kill({ window = 'address:0x" + str.substr(pos + 7, pos2 - pos - 7) + "' })"); + getFromSocket(std::format("/dispatch hl.dsp.window.kill({{ window = 'address:0x{}' }})", str.substr(pos + 7, pos2 - pos - 7))); pos = str.find("Window ", pos + 5); } diff --git a/meta/generateLuaStubs.py b/meta/generateLuaStubs.py index cd9927ba2..4bf1a7b7e 100644 --- a/meta/generateLuaStubs.py +++ b/meta/generateLuaStubs.py @@ -416,7 +416,7 @@ def query_struct_to_type(struct_name: str) -> str: if name.startswith("S") and len(name) > 1: name = name[1:] if name.endswith("Query"): - name = name + "Filter" + name = f"{name}Filter" return f"HL.{name}" @@ -504,7 +504,7 @@ def emit_class_block(class_name: str, fields: list[tuple[str, str, bool]], opera lines.append(f"---@field ['{quoted}'] {type_with_optional}") if (emit_local_var): - local_name = "__" + class_name.replace(".", "_") + local_name = f"__{class_name.replace('.', '_')}" lines.append(f"local {local_name} = {{}}") return lines @@ -783,7 +783,7 @@ def generate_stub(root: Path) -> str: class_name = namespace_class_name(path) fields: list[tuple[str, str, bool]] = [] - full_prefix = "hl" + ("." + ".".join(path) if path else "") + full_prefix = ".".join(["hl", *path]) for method in sorted(node.methods): full_name = f"{full_prefix}.{method}" diff --git a/src/Compositor.cpp b/src/Compositor.cpp index 5d3f7306b..7de3b5953 100644 --- a/src/Compositor.cpp +++ b/src/Compositor.cpp @@ -191,7 +191,8 @@ CCompositor::CCompositor(bool onlyConfig) : m_onlyConfigVerification(onlyConfig) setMallocThreshold(); - m_hyprTempDataRoot = std::string{getenv("XDG_RUNTIME_DIR")} + "/hypr"; + const auto* XDG_RUNTIME_DIR = getenv("XDG_RUNTIME_DIR"); + m_hyprTempDataRoot = std::format("{}/hypr", XDG_RUNTIME_DIR ? XDG_RUNTIME_DIR : ""); if (m_hyprTempDataRoot.starts_with("/hypr")) { std::println("Bailing out, $XDG_RUNTIME_DIR is invalid"); @@ -216,7 +217,7 @@ CCompositor::CCompositor(bool onlyConfig) : m_onlyConfigVerification(onlyConfig) throw std::runtime_error("CCompositor() failed"); } - m_instancePath = m_hyprTempDataRoot + "/" + m_instanceSignature; + m_instancePath = std::format("{}/{}", m_hyprTempDataRoot, m_instanceSignature); if (std::filesystem::exists(m_instancePath)) { std::println("Bailing out, {} exists??", m_instancePath); @@ -393,7 +394,7 @@ void CCompositor::initServer(std::string socketName, int socketFd) { } else { // get socket, avoid using 0 for (int candidate = 1; candidate <= 32; candidate++) { - const auto CANDIDATESTR = ("wayland-" + std::to_string(candidate)); + const auto CANDIDATESTR = std::format("wayland-{}", candidate); const auto RETVAL = wl_display_add_socket(m_wlDisplay, CANDIDATESTR.c_str()); if (RETVAL >= 0) { m_wlDisplaySocket = CANDIDATESTR; @@ -764,7 +765,7 @@ void CCompositor::initManagers(eManagersInitStage stage) { } void CCompositor::createLockFile() { - const auto PATH = m_instancePath + "/hyprland.lock"; + const auto PATH = std::format("{}/hyprland.lock", m_instancePath); std::ofstream ofs(PATH, std::ios::trunc); @@ -774,7 +775,7 @@ void CCompositor::createLockFile() { } void CCompositor::removeLockFile() { - const auto PATH = m_instancePath + "/hyprland.lock"; + const auto PATH = std::format("{}/hyprland.lock", m_instancePath); if (std::filesystem::exists(PATH)) std::filesystem::remove(PATH); diff --git a/src/config/lua/ConfigManager.cpp b/src/config/lua/ConfigManager.cpp index 6b3f2ad77..51baf9789 100644 --- a/src/config/lua/ConfigManager.cpp +++ b/src/config/lua/ConfigManager.cpp @@ -97,7 +97,7 @@ static std::optional resolveExplicitLuaRequireFile(CConfigManager* candidates.emplace_back(BASE); if (!BASE.ends_with(".lua")) - candidates.emplace_back(BASE + ".lua"); + candidates.emplace_back(std::format("{}.lua", BASE)); candidates.emplace_back((std::filesystem::path(BASE) / "init.lua").string()); @@ -533,7 +533,7 @@ void CConfigManager::reinitLuaState() { lua_setfield(m_lua, LUA_REGISTRYINDEX, "hl_lua_manager"); std::filesystem::path configDir = std::filesystem::path(m_mainConfigPath).parent_path(); - const std::string luaPath = (configDir / "?.lua").string() + ";" + (configDir / "?/init.lua").string(); + const std::string luaPath = std::format("{};{}", (configDir / "?.lua").string(), (configDir / "?/init.lua").string()); lua_getglobal(m_lua, "package"); lua_getfield(m_lua, -1, "path"); std::string combinedLuaPath = luaPath; @@ -788,7 +788,7 @@ void CConfigManager::postConfigReload() { errorStr += "Your config has errors:\n"; for (const auto& e : m_errors) { - errorStr += e + "\n"; + errorStr += std::format("{}\n", e); if (std::ranges::count(errorStr, '\n') > 15) { errorStr += "... more"; @@ -802,8 +802,9 @@ void CConfigManager::postConfigReload() { ErrorOverlay::overlay()->queueCreate(errorStr, ErrorOverlay::Colors::ERROR); } else if (*PAUTOGENERATED) ErrorOverlay::overlay()->queueCreate( - "Warning: You're using an autogenerated config! Edit the config file to get rid of this message. (config file: " + getMainConfigPath() + - " )\nSUPER+Q -> kitty (if it doesn't launch, make sure it's installed or choose a different terminal in the config)\nSUPER+M -> exit Hyprland", + std::format("Warning: You're using an autogenerated config! Edit the config file to get rid of this message. (config file: {} )\nSUPER+Q -> kitty (if it doesn't " + "launch, make sure it's installed or choose a different terminal in the config)\nSUPER+M -> exit Hyprland", + getMainConfigPath()), ErrorOverlay::Colors::WARNING); else ErrorOverlay::overlay()->destroy(); @@ -1058,7 +1059,7 @@ std::string CConfigManager::getMainConfigPath() { std::string CConfigManager::getErrors() { std::string errStr; for (const auto& e : m_errors) { - errStr += e + "\n"; + errStr += std::format("{}\n", e); } if (!errStr.empty()) @@ -1289,8 +1290,8 @@ std::expected CConfigManager::registerPluginLuaFunction(void* if (namespace_ == "load") return std::unexpected("namespace 'load' is reserved"); - const auto key = namespace_ + "." + name; - if (std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return r.namespace_ + "." + r.name == key; }) != m_pluginLuaFunctions.end()) + const auto key = std::format("{}.{}", namespace_, name); + if (std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return std::format("{}.{}", r.namespace_, r.name) == key; }) != m_pluginLuaFunctions.end()) return std::unexpected("name collision: already registered"); const uint64_t id = nextPluginLuaFnID++; @@ -1306,8 +1307,8 @@ std::expected CConfigManager::unregisterPluginLuaFunction(voi if (!handle) return std::unexpected("invalid handle"); - const auto key = namespace_ + "." + name; - auto it = std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return r.namespace_ + "." + r.name == key; }); + const auto key = std::format("{}.{}", namespace_, name); + auto it = std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return std::format("{}.{}", r.namespace_, r.name) == key; }); if (it == m_pluginLuaFunctions.end()) return std::unexpected("no such function"); diff --git a/src/config/lua/bindings/LuaBindingsConfigRules.cpp b/src/config/lua/bindings/LuaBindingsConfigRules.cpp index 3df1b77fc..d60af52f9 100644 --- a/src/config/lua/bindings/LuaBindingsConfigRules.cpp +++ b/src/config/lua/bindings/LuaBindingsConfigRules.cpp @@ -447,7 +447,7 @@ static int hlAnimation(lua_State* L) { if (!Animation::mgr()->springExists(springName)) return Internal::configError(L, std::format(R"(hl.animation("{}"): no such spring "{}")", leaf, springName)); - curveName = "spring:" + springName; + curveName = std::format("spring:{}", springName); } else return Internal::configError(L, std::format(R"(hl.animation("{}"): bezier or spring is required)", leaf)); @@ -521,9 +521,9 @@ static int hlEnv(lua_State* L) { if (dbus) { std::string CMD; #ifdef USES_SYSTEMD - CMD = "systemctl --user import-environment '" + name + "' && hash dbus-update-activation-environment 2>/dev/null && "; + CMD = std::format("systemctl --user import-environment '{}' && hash dbus-update-activation-environment 2>/dev/null && ", name); #endif - CMD += "dbus-update-activation-environment --systemd '" + name + "'"; + CMD += std::format("dbus-update-activation-environment --systemd '{}'", name); if (mgr->isFirstLaunch()) Config::Supplementary::executor()->addExecOnce({CMD, false}); else diff --git a/src/config/lua/bindings/LuaBindingsDispatchers.cpp b/src/config/lua/bindings/LuaBindingsDispatchers.cpp index 748b641a4..e9eb852cd 100644 --- a/src/config/lua/bindings/LuaBindingsDispatchers.cpp +++ b/src/config/lua/bindings/LuaBindingsDispatchers.cpp @@ -693,7 +693,7 @@ static int dsp_mouseResize(lua_State* L) { if (!keepAspectRatio) return Internal::configError(L, std::format("resize: bad argument 1: {}", keepAspectRatio.error())); - return Internal::checkResult(L, CA::mouse("resizewindow " + *keepAspectRatio)); + return Internal::checkResult(L, CA::mouse(std::format("resizewindow {}", *keepAspectRatio))); } static int hlWindowClose(lua_State* L) { @@ -1206,7 +1206,7 @@ static int hlNoop(lua_State* L) { static int dsp_toggleSpecial(lua_State* L) { std::string name = lua_isnil(L, lua_upvalueindex(1)) ? "" : lua_tostring(L, lua_upvalueindex(1)); - const auto& [workspaceID, workspaceName, isAutoID] = getWorkspaceIDNameFromString("special:" + name); + const auto& [workspaceID, workspaceName, isAutoID] = getWorkspaceIDNameFromString(std::format("special:{}", name)); if (workspaceID == WORKSPACE_INVALID || !State::workspaceState()->isSpecial(workspaceID)) return Internal::dispatcherError(L, "Invalid special workspace", ERR, C_INVARG); diff --git a/src/config/lua/bindings/LuaBindingsToplevel.cpp b/src/config/lua/bindings/LuaBindingsToplevel.cpp index 9bacdeffe..db18b1ebb 100644 --- a/src/config/lua/bindings/LuaBindingsToplevel.cpp +++ b/src/config/lua/bindings/LuaBindingsToplevel.cpp @@ -390,7 +390,7 @@ static int hlOn(lua_State* L) { const auto& known = CLuaEventHandler::knownEvents(); std::string list; for (const auto& e : known) { - list += e + ", "; + list += std::format("{}, ", e); } list.pop_back(); list.pop_back(); diff --git a/src/config/lua/layout/LuaLayoutProvider.cpp b/src/config/lua/layout/LuaLayoutProvider.cpp index 8cb68b1ab..845e90d60 100644 --- a/src/config/lua/layout/LuaLayoutProvider.cpp +++ b/src/config/lua/layout/LuaLayoutProvider.cpp @@ -21,7 +21,7 @@ using namespace Config::Lua::Layouts; static std::string normalizeLuaLayoutName(std::string name) { if (!name.starts_with("lua:")) - name = "lua:" + name; + name = std::format("lua:{}", name); return name; } diff --git a/src/config/lua/types/LuaConfigInt.cpp b/src/config/lua/types/LuaConfigInt.cpp index 24220e87c..6397c835e 100644 --- a/src/config/lua/types/LuaConfigInt.cpp +++ b/src/config/lua/types/LuaConfigInt.cpp @@ -36,7 +36,7 @@ SParseError CLuaConfigInt::parse(lua_State* s) { for (const auto& [k, _] : *m_map) { if (!keys.empty()) keys += ", "; - keys += "\"" + k + "\""; + keys += std::format("\"{}\"", k); } return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = std::format("unknown string value \"{}\", acceptable values are: {}", str, keys)}; } diff --git a/src/config/shared/monitor/Parser.cpp b/src/config/shared/monitor/Parser.cpp index 20681b3b8..7f62775c0 100644 --- a/src/config/shared/monitor/Parser.cpp +++ b/src/config/shared/monitor/Parser.cpp @@ -7,6 +7,7 @@ #include #include #include +#include using namespace Config; using namespace Hyprutils::String; @@ -84,7 +85,8 @@ static bool parseModeLine(const std::string& modeline, drmModeModeInfo& mode) { Log::logger->log(Log::ERR, "Invalid flag {} in modeline", key); } - snprintf(mode.name, sizeof(mode.name), "%dx%d@%d", mode.hdisplay, mode.vdisplay, mode.vrefresh / 1000); + const auto [nameEnd, size] = std::format_to_n(mode.name, sizeof(mode.name) - 1, "{}x{}@{}", mode.hdisplay, mode.vdisplay, mode.vrefresh / 1000); + *nameEnd = '\0'; return true; } diff --git a/src/desktop/Workspace.cpp b/src/desktop/Workspace.cpp index 60001f472..d9de359df 100644 --- a/src/desktop/Workspace.cpp +++ b/src/desktop/Workspace.cpp @@ -114,7 +114,7 @@ std::string CWorkspace::getConfigName() { if (m_id > 0) return std::to_string(m_id); - return "name:" + m_name; + return std::format("name:{}", m_name); } bool CWorkspace::matchesStaticSelector(const std::string& selector_) { @@ -540,7 +540,7 @@ void CWorkspace::rename(const std::string& name) { m_wasRenamed = true; - IPC::Socket2::sock()->postEvent({.event = "renameworkspace", .data = std::to_string(m_id) + "," + m_name}); + IPC::Socket2::sock()->postEvent({.event = "renameworkspace", .data = std::format("{},{}", m_id, m_name)}); m_events.renamed.emit(); } @@ -557,7 +557,7 @@ void CWorkspace::changeID(int64_t id) { Config::Supplementary::refresher()->scheduleRefresh(Config::Supplementary::REFRESH_ALL); - IPC::Socket2::sock()->postEvent({.event = "changeworkspaceid", .data = std::to_string(OLD_ID) + "," + std::to_string(m_id)}); + IPC::Socket2::sock()->postEvent({.event = "changeworkspaceid", .data = std::format("{},{}", OLD_ID, m_id)}); m_events.idChanged.emit(); } diff --git a/src/desktop/state/FocusState.cpp b/src/desktop/state/FocusState.cpp index 128e9ebd1..5ba4e8f5b 100644 --- a/src/desktop/state/FocusState.cpp +++ b/src/desktop/state/FocusState.cpp @@ -206,7 +206,7 @@ void CFocusState::rawWindowFocus(PHLWINDOW pWindow, eFocusReason reason, SPm_isUrgent = false; // Send an event - IPC::Socket2::sock()->postEvent({.event = "activewindow", .data = pWindow->m_class + "," + pWindow->m_title}); + IPC::Socket2::sock()->postEvent({.event = "activewindow", .data = std::format("{},{}", pWindow->m_class, pWindow->m_title)}); IPC::Socket2::sock()->postEvent({.event = "activewindowv2", .data = std::format("{:x}", rc(pWindow.get()))}); Event::bus()->m_events.window.active.emit(pWindow, reason); @@ -284,8 +284,8 @@ void CFocusState::rawMonitorFocus(PHLMONITOR pMonitor) { const auto WORKSPACE_ID = PWORKSPACE ? std::to_string(PWORKSPACE->m_id) : std::to_string(WORKSPACE_INVALID); const auto WORKSPACE_NAME = PWORKSPACE ? PWORKSPACE->m_name : "?"; - IPC::Socket2::sock()->postEvent({.event = "focusedmon", .data = pMonitor->m_name + "," + WORKSPACE_NAME}); - IPC::Socket2::sock()->postEvent({.event = "focusedmonv2", .data = pMonitor->m_name + "," + WORKSPACE_ID}); + IPC::Socket2::sock()->postEvent({.event = "focusedmon", .data = std::format("{},{}", pMonitor->m_name, WORKSPACE_NAME)}); + IPC::Socket2::sock()->postEvent({.event = "focusedmonv2", .data = std::format("{},{}", pMonitor->m_name, WORKSPACE_ID)}); Event::bus()->m_events.monitor.focused.emit(pMonitor); m_focusMonitor = pMonitor; diff --git a/src/desktop/view/Window.cpp b/src/desktop/view/Window.cpp index 508a1f865..193f40a7a 100644 --- a/src/desktop/view/Window.cpp +++ b/src/desktop/view/Window.cpp @@ -1344,7 +1344,7 @@ std::unordered_map CWindow::getEnv() { #if defined(__linux__) // - std::string environFile = "/proc/" + std::to_string(PID) + "/environ"; + std::string environFile = std::format("/proc/{}/environ", PID); std::ifstream ifs(environFile, std::ios::binary); if (!ifs.good()) @@ -1484,7 +1484,7 @@ void CWindow::onUpdateMeta() { Event::bus()->m_events.window.title.emit(m_self.lock()); if (m_self == Desktop::focusState()->window()) { // if it's the active, let's post an event to update others - IPC::Socket2::sock()->postEvent({.event = "activewindow", .data = m_class + "," + m_title}); + IPC::Socket2::sock()->postEvent({.event = "activewindow", .data = std::format("{},{}", m_class, m_title)}); IPC::Socket2::sock()->postEvent({.event = "activewindowv2", .data = std::format("{:x}", rc(this))}); // no need for a hook event @@ -1501,7 +1501,7 @@ void CWindow::onUpdateMeta() { Event::bus()->m_events.window.class_.emit(m_self.lock()); if (m_self == Desktop::focusState()->window()) { // if it's the active, let's post an event to update others - IPC::Socket2::sock()->postEvent({.event = "activewindow", .data = m_class + "," + m_title}); + IPC::Socket2::sock()->postEvent({.event = "activewindow", .data = std::format("{},{}", m_class, m_title)}); IPC::Socket2::sock()->postEvent({.event = "activewindowv2", .data = std::format("{:x}", rc(this))}); // no need for a hook event @@ -2213,7 +2213,7 @@ void CWindow::mapWindow() { const auto JUSTWORKSPACE = WORKSPACERQ.contains(' ') ? WORKSPACERQ.substr(0, WORKSPACERQ.find_first_of(' ')) : WORKSPACERQ; - if (JUSTWORKSPACE == PWORKSPACE->m_name || JUSTWORKSPACE == "name:" + PWORKSPACE->m_name) + if (JUSTWORKSPACE == PWORKSPACE->m_name || JUSTWORKSPACE == std::format("name:{}", PWORKSPACE->m_name)) requestedWorkspace = ""; Log::logger->log(Log::DEBUG, "Rule workspace matched by {}, {} applied.", m_self.lock(), m_ruleApplicator->static_.workspace); diff --git a/src/devices/IKeyboard.cpp b/src/devices/IKeyboard.cpp index 742356fef..19c0d5731 100644 --- a/src/devices/IKeyboard.cpp +++ b/src/devices/IKeyboard.cpp @@ -99,8 +99,8 @@ void IKeyboard::setKeymap(const SStringRuleNames& rules) { m_xkbKeymap = xkb_keymap_new_from_names2(CONTEXT, &XKBRULES, XKB_KEYMAP_FORMAT_TEXT_V2, XKB_KEYMAP_COMPILE_NO_FLAGS); if (!m_xkbKeymap) { - ErrorOverlay::overlay()->queueError("Invalid keyboard layout passed. ( rules: " + rules.rules + ", model: " + rules.model + ", variant: " + rules.variant + - ", options: " + rules.options + ", layout: " + rules.layout + " )"); + ErrorOverlay::overlay()->queueError(std::format("Invalid keyboard layout passed. ( rules: {}, model: {}, variant: {}, options: {}, layout: {} )", rules.rules, rules.model, + rules.variant, rules.options, rules.layout)); Log::logger->log(Log::ERR, "Keyboard layout {} with variant {} (rules: {}, model: {}, options: {}) couldn't have been loaded.", rules.layout, rules.variant, rules.rules, rules.model, rules.options); diff --git a/src/errorOverlay/Overlay.cpp b/src/errorOverlay/Overlay.cpp index 0ad690be3..dee510538 100644 --- a/src/errorOverlay/Overlay.cpp +++ b/src/errorOverlay/Overlay.cpp @@ -92,7 +92,7 @@ void COverlay::queueCreate(std::string message, const Config::CGradientValueData } void COverlay::queueError(std::string err) { - queueCreate(err + "\nHyprland may not work correctly.", CHyprColor(1.0, 50.0 / 255.0, 50.0 / 255.0, 1.0)); + queueCreate(std::format("{}\nHyprland may not work correctly.", err), CHyprColor(1.0, 50.0 / 255.0, 50.0 / 255.0, 1.0)); } void COverlay::createQueued() { diff --git a/src/helpers/AsyncDialogBox.cpp b/src/helpers/AsyncDialogBox.cpp index 19e4d094f..c362b378a 100644 --- a/src/helpers/AsyncDialogBox.cpp +++ b/src/helpers/AsyncDialogBox.cpp @@ -95,7 +95,7 @@ void CAsyncDialogBox::onWrite(int fd, uint32_t mask) { SP> CAsyncDialogBox::open() { std::string buttonsString = ""; for (auto& b : m_buttons) { - buttonsString += b + ";"; + buttonsString += std::format("{};", b); } if (!buttonsString.empty()) buttonsString.pop_back(); diff --git a/src/helpers/MiscFunctions.cpp b/src/helpers/MiscFunctions.cpp index be4f033ab..449e90a88 100644 --- a/src/helpers/MiscFunctions.cpp +++ b/src/helpers/MiscFunctions.cpp @@ -130,9 +130,9 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) { if (in.length() > 8) { const auto NAME = in.substr(8); - const auto WS = State::workspaceState()->query().name("special:" + NAME).run(); + const auto WS = State::workspaceState()->query().name(std::format("special:{}", NAME)).run(); - return {WS ? WS->m_id : State::workspaceState()->newSpecialID(), "special:" + NAME}; + return {WS ? WS->m_id : State::workspaceState()->newSpecialID(), std::format("special:{}", NAME)}; } result.id = SPECIAL_WORKSPACE_START; @@ -481,7 +481,7 @@ std::optional cleanCmdForWorkspace(const std::string& inWorkspaceNa if (!cmd.empty()) { std::string rules; - const std::string workspaceRule = "workspace " + inWorkspaceName; + const std::string workspaceRule = std::format("workspace {}", inWorkspaceName); if (cmd[0] == '[') { const auto closingBracketIdx = cmd.find_last_of(']'); @@ -501,12 +501,12 @@ std::optional cleanCmdForWorkspace(const std::string& inWorkspaceNa if (!hadWorkspaceRule) rulesList.append(workspaceRule); - rules = "[" + rulesList.join(";") + "]"; + rules = std::format("[{}]", rulesList.join(";")); } else { - rules = "[" + workspaceRule + "]"; + rules = std::format("[{}]", workspaceRule); } - return std::optional(rules + " " + cmd); + return std::optional(std::format("{} {}", rules, cmd)); } return std::nullopt; @@ -544,7 +544,7 @@ int64_t getPPIDof(int64_t pid) { return 0; #else - std::string dir = "/proc/" + std::to_string(pid) + "/status"; + std::string dir = std::format("/proc/{}/status", pid); FILE* infile; infile = fopen(dir.c_str(), "r"); @@ -623,7 +623,7 @@ void throwError(const std::string& err) { std::pair openExclusiveShm() { // Only absolute paths can be shared across different shm_open() calls - std::string name = "/" + g_pTokenManager->getRandomUUID(); + std::string name = std::format("/{}", g_pTokenManager->getRandomUUID()); for (size_t i = 0; i < 69; ++i) { CFileDescriptor fd{shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600)}; @@ -794,7 +794,7 @@ static const std::vector PKGCONF_PATHS = {"/usr/lib/pkgconfig", "/u std::string getSystemLibraryVersion(const std::string& name) { for (const auto& pkgconf : PKGCONF_PATHS) { std::error_code ec; - const std::string PATH = std::string{pkgconf} + "/" + name + ".pc"; + const std::string PATH = std::format("{}/{}.pc", pkgconf, name); if (!std::filesystem::exists(PATH, ec)) continue; diff --git a/src/helpers/SystemInfo.cpp b/src/helpers/SystemInfo.cpp index 190fdc77a..d0ec45de3 100644 --- a/src/helpers/SystemInfo.cpp +++ b/src/helpers/SystemInfo.cpp @@ -165,10 +165,10 @@ std::string SystemInfo::getSystemInfo() { uname(&unameInfo); - result += "System name: " + std::string{unameInfo.sysname} + "\n"; - result += "Node name: " + std::string{unameInfo.nodename} + "\n"; - result += "Release: " + std::string{unameInfo.release} + "\n"; - result += "Version: " + std::string{unameInfo.version} + "\n"; + result += std::format("System name: {}\n", unameInfo.sysname); + result += std::format("Node name: {}\n", unameInfo.nodename); + result += std::format("Release: {}\n", unameInfo.release); + result += std::format("Version: {}\n", unameInfo.version); result += "\n"; result += getBuiltSystemLibraryNames(); result += "\n"; @@ -199,7 +199,7 @@ std::string SystemInfo::getSystemInfo() { #else const std::string GPUINFO = execAndGet("lspci -vnn | grep -E '(VGA|Display|3D)'"); #endif - result += "GPU information: \n" + GPUINFO; + result += std::format("GPU information: \n{}", GPUINFO); if (GPUINFO.contains("NVIDIA") && std::filesystem::exists("/proc/driver/nvidia/version")) { std::ifstream file("/proc/driver/nvidia/version"); std::string line; @@ -218,7 +218,7 @@ std::string SystemInfo::getSystemInfo() { if (std::ifstream file("/etc/os-release"); file.is_open()) { std::stringstream buffer; buffer << file.rdbuf(); - result += "os-release: " + buffer.str() + "\n\n"; + result += std::format("os-release: {}\n\n", buffer.str()); } else result += "os-release: error\n\n"; diff --git a/src/helpers/TagKeeper.cpp b/src/helpers/TagKeeper.cpp index 80bf3957d..0476e88a6 100644 --- a/src/helpers/TagKeeper.cpp +++ b/src/helpers/TagKeeper.cpp @@ -1,9 +1,11 @@ #include "TagKeeper.hpp" +#include + bool CTagKeeper::isTagged(const std::string& tag, bool strict) const { const bool NEGATIVE = tag.starts_with("negative"); const auto MATCH = NEGATIVE ? tag.substr(9) : tag; - const bool TAGGED = m_tags.contains(MATCH) || (!strict && m_tags.contains(MATCH + "*")); + const bool TAGGED = m_tags.contains(MATCH) || (!strict && m_tags.contains(std::format("{}*", MATCH))); return NEGATIVE ? !TAGGED : TAGGED; } @@ -48,5 +50,5 @@ bool CTagKeeper::clearTags() { } bool CTagKeeper::removeDynamicTag(const std::string& s) { - return std::erase_if(m_tags, [&s](const auto& tag) { return tag == s + "*"; }); + return std::erase_if(m_tags, [&s](const auto& tag) { return tag == std::format("{}*", s); }); } diff --git a/src/ipc/s1/Commands.cpp b/src/ipc/s1/Commands.cpp index 495673227..ce5c248f5 100644 --- a/src/ipc/s1/Commands.cpp +++ b/src/ipc/s1/Commands.cpp @@ -139,7 +139,7 @@ std::string CCommandFormatter::getSolitaryBlockedReason(PHLMONITOR m, eHyprCtlOu } } - return format == eHyprCtlOutputFormat::FORMAT_JSON ? "[" + reasonStr + "]" : reasonStr; + return format == eHyprCtlOutputFormat::FORMAT_JSON ? std::format("[{}]", reasonStr) : reasonStr; } const std::array DS_REASONS_JSON = { @@ -168,7 +168,7 @@ std::string CCommandFormatter::getDSBlockedReason(PHLMONITOR m, eHyprCtlOutputFo } } - return format == eHyprCtlOutputFormat::FORMAT_JSON ? "[" + reasonStr + "]" : reasonStr; + return format == eHyprCtlOutputFormat::FORMAT_JSON ? std::format("[{}]", reasonStr) : reasonStr; } const std::array TEARING_REASONS_JSON = { @@ -194,7 +194,7 @@ std::string CCommandFormat } } - return format == eHyprCtlOutputFormat::FORMAT_JSON ? "[" + reasonStr + "]" : reasonStr; + return format == eHyprCtlOutputFormat::FORMAT_JSON ? std::format("[{}]", reasonStr) : reasonStr; } std::string CCommandFormatter::getMonitorData(PHLMONITOR m, eHyprCtlOutputFormat format) { @@ -327,7 +327,7 @@ static std::string getTagsData(PHLWINDOW w, eHyprCtlOutputFormat format) { return std::ranges::fold_left(tags, std::string(), [](const std::string& a, const std::string& b) { return a.empty() ? std::format("\"{}\"", b) : std::format("{}, \"{}\"", a, b); }); else - return std::ranges::fold_left(tags, std::string(), [](const std::string& a, const std::string& b) { return a.empty() ? b : a + ", " + b; }); + return std::ranges::fold_left(tags, std::string(), [](const std::string& a, const std::string& b) { return a.empty() ? b : std::format("{}, {}", a, b); }); } static std::string getGroupedData(PHLWINDOW w, eHyprCtlOutputFormat format) { @@ -992,7 +992,7 @@ static std::string globalShortcutsRequest(eHyprCtlOutputFormat format, std::stri "name": "{}", "description": "{}" }},)#", - escapeJSONStrings(sh.appid + ":" + sh.id), escapeJSONStrings(sh.description)); + escapeJSONStrings(std::format("{}:{}", sh.appid, sh.id)), escapeJSONStrings(sh.description)); } trimTrailingComma(ret); ret += "]\n"; @@ -1150,7 +1150,7 @@ static std::string dispatchRequest(eHyprCtlOutputFormat format, std::string in) return ret; // the user likely is trying to dispatch old hyprlang stuff via lua, let them know - return ret + "\n\n → Note: dispatch in lua is a shorthand for hl.dispatch(...), your syntax might need to be updated."; + return std::format("{}\n\n → Note: dispatch in lua is a shorthand for hl.dispatch(...), your syntax might need to be updated.", ret); } return "current config provider doesn't support dispatch"; @@ -1211,7 +1211,7 @@ static std::string dispatchSetCursor(eHyprCtlOutputFormat format, std::string re const auto SIZESTR = vars[vars.size() - 1]; std::string theme = ""; for (size_t i = 1; i < vars.size() - 1; ++i) - theme += vars[i] + " "; + theme += std::format("{} ", vars[i]); if (!theme.empty()) theme.pop_back(); @@ -1259,7 +1259,7 @@ static std::string switchXKBLayoutRequest(eHyprCtlOutputFormat format, std::stri } catch (std::exception& e) { return "invalid arg 2"; } if (requestedLayout < 0 || sc(requestedLayout) > LAYOUTS - 1) { - return "layout idx out of range of " + std::to_string(LAYOUTS); + return std::format("layout idx out of range of {}", LAYOUTS); } KEEB->updateModifiers(KEEB->m_modifiersState.depressed, KEEB->m_modifiersState.latched, KEEB->m_modifiersState.locked, requestedLayout); @@ -1281,7 +1281,7 @@ static std::string switchXKBLayoutRequest(eHyprCtlOutputFormat format, std::stri for (auto const& k : g_pInputManager->m_keyboards) { auto res = updateKeyboard(k, CMD); if (res.has_value()) - result += *res + "\n"; + result += std::format("{}\n", *res); } return result.empty() ? "ok" : result; } else { @@ -1615,7 +1615,7 @@ static std::string decorationRequest(eHyprCtlOutputFormat format, std::string re if (format == eHyprCtlOutputFormat::FORMAT_JSON) { result += "["; for (auto const& wd : PWINDOW->m_windowDecorations) { - result += "{\n\"decorationName\": \"" + wd->getDisplayName() + "\",\n\"priority\": " + std::to_string(wd->getPositioningInfo().priority) + "\n},"; + result += std::format("{{\n\"decorationName\": \"{}\",\n\"priority\": {}\n}},", wd->getDisplayName(), wd->getPositioningInfo().priority); } trimTrailingComma(result); @@ -1623,7 +1623,7 @@ static std::string decorationRequest(eHyprCtlOutputFormat format, std::string re } else { result = +"Decoration\tPriority\n"; for (auto const& wd : PWINDOW->m_windowDecorations) { - result += wd->getDisplayName() + "\t" + std::to_string(wd->getPositioningInfo().priority) + "\n"; + result += std::format("{}\t{}\n", wd->getDisplayName(), wd->getPositioningInfo().priority); } } @@ -1859,7 +1859,7 @@ static std::string submapRequest(eHyprCtlOutputFormat format, std::string reques if (submap.empty()) submap = "default"; - return format == FORMAT_JSON ? std::format("\"{}\"\n", escapeJSONStrings(submap)) : (submap + "\n"); + return format == FORMAT_JSON ? std::format("\"{}\"\n", escapeJSONStrings(submap)) : std::format("{}\n", submap); } static std::string reloadShaders(eHyprCtlOutputFormat format, std::string request) { diff --git a/src/ipc/s1/S1.cpp b/src/ipc/s1/S1.cpp index 32ce24280..0576269ae 100644 --- a/src/ipc/s1/S1.cpp +++ b/src/ipc/s1/S1.cpp @@ -210,7 +210,7 @@ SResponse CSocket1::dispatch(std::string request, pid_t pid) { return dispatchSingle(std::move(request), pid); } catch (const std::exception& error) { Log::logger->log(Log::ERR, "Error in socket1 request: {}", error.what()); - return "Err: " + std::string{error.what()}; + return std::format("Err: {}", error.what()); } } diff --git a/src/ipc/s1/Unix.cpp b/src/ipc/s1/Unix.cpp index deaa333e3..2d75d90c0 100644 --- a/src/ipc/s1/Unix.cpp +++ b/src/ipc/s1/Unix.cpp @@ -239,7 +239,7 @@ void CUnixImpl::start(FRequestHandler&& handler) { } sockaddr_un address = {.sun_family = AF_UNIX}; - m_socketPath = g_pCompositor->m_instancePath + "/.socket.sock"; + m_socketPath = std::format("{}/.socket.sock", g_pCompositor->m_instancePath); if (m_socketPath.size() > sizeof(address.sun_path) - 1) { Log::logger->log(Log::ERR, "[Socket1::Unix] socket path is too long"); diff --git a/src/ipc/s2/Unix.cpp b/src/ipc/s2/Unix.cpp index 61d0561d2..d3ddf503b 100644 --- a/src/ipc/s2/Unix.cpp +++ b/src/ipc/s2/Unix.cpp @@ -90,7 +90,7 @@ CUnixImpl::CUnixImpl() : m_socket(socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | S } sockaddr_un SERVERADDRESS = {.sun_family = AF_UNIX}; - const auto PATH = g_pCompositor->m_instancePath + "/.socket2.sock"; + const auto PATH = std::format("{}/.socket2.sock", g_pCompositor->m_instancePath); if (PATH.length() > sizeof(SERVERADDRESS.sun_path) - 1) { Log::logger->log(Log::ERR, "[Socket2::UnixImpl] path is too long. (2) IPC will not work."); return; diff --git a/src/managers/DonationNagManager.cpp b/src/managers/DonationNagManager.cpp index a88b35c56..886a283db 100644 --- a/src/managers/DonationNagManager.cpp +++ b/src/managers/DonationNagManager.cpp @@ -136,7 +136,7 @@ void CDonationNagManager::fire() { CDonationNagManager::SStateData CDonationNagManager::getState() { static const auto DATAROOT = NFsUtils::getDataHome(); - const auto STR = NFsUtils::readFileAsString(*DATAROOT + "/" + LAST_NAG_FILE_NAME); + const auto STR = NFsUtils::readFileAsString(std::format("{}/{}", *DATAROOT, LAST_NAG_FILE_NAME)); if (!STR.has_value()) return {}; @@ -154,5 +154,5 @@ CDonationNagManager::SStateData CDonationNagManager::getState() { void CDonationNagManager::writeState(const SStateData& s) { static const auto DATAROOT = NFsUtils::getDataHome(); - NFsUtils::writeToFile(*DATAROOT + "/" + LAST_NAG_FILE_NAME, std::format("{}\n{}", s.epoch, s.major)); + NFsUtils::writeToFile(std::format("{}/{}", *DATAROOT, LAST_NAG_FILE_NAME), std::format("{}\n{}", s.epoch, s.major)); } diff --git a/src/managers/KeybindManager.cpp b/src/managers/KeybindManager.cpp index 518752c00..1eb15c38d 100644 --- a/src/managers/KeybindManager.cpp +++ b/src/managers/KeybindManager.cpp @@ -238,9 +238,9 @@ void CKeybindManager::updateXKBTranslationState() { fclose(KEYMAPFILE); if (!PKEYMAP) { - ErrorOverlay::overlay()->queueCreate("[Runtime Error] Invalid keyboard layout passed. ( rules: " + RULES + ", model: " + MODEL + ", variant: " + VARIANT + - ", options: " + OPTIONS + ", layout: " + LAYOUT + " )", - ErrorOverlay::Colors::ERROR); + ErrorOverlay::overlay()->queueCreate( + std::format("[Runtime Error] Invalid keyboard layout passed. ( rules: {}, model: {}, variant: {}, options: {}, layout: {} )", RULES, MODEL, VARIANT, OPTIONS, LAYOUT), + ErrorOverlay::Colors::ERROR); Log::logger->log(Log::ERR, "[XKBTranslationState] Keyboard layout {} with variant {} (rules: {}, model: {}, options: {}) couldn't have been loaded.", rules.layout, rules.variant, rules.rules, rules.model, rules.options); @@ -406,7 +406,7 @@ bool CKeybindManager::onMouseEvent(const IPointer::SButtonEvent& e, SP bool mouseBindWasActive = ensureMouseBindState(); - const auto KEY_NAME = "mouse:" + std::to_string(e.button); + const auto KEY_NAME = std::format("mouse:{}", e.button); const auto KEY = SPressedKeyWithMods{ .keyName = KEY_NAME, @@ -455,15 +455,15 @@ void CKeybindManager::resizeWithBorder(const IPointer::SButtonEvent& e) { } void CKeybindManager::onSwitchEvent(const std::string& switchName) { - handleKeybinds(0, SPressedKeyWithMods{.keyName = "switch:" + switchName, .submapAtPress = getCurrentSubmap()}, true, nullptr, nullptr); + handleKeybinds(0, SPressedKeyWithMods{.keyName = std::format("switch:{}", switchName), .submapAtPress = getCurrentSubmap()}, true, nullptr, nullptr); } void CKeybindManager::onSwitchOnEvent(const std::string& switchName) { - handleKeybinds(0, SPressedKeyWithMods{.keyName = "switch:on:" + switchName, .submapAtPress = getCurrentSubmap()}, true, nullptr, nullptr); + handleKeybinds(0, SPressedKeyWithMods{.keyName = std::format("switch:on:{}", switchName), .submapAtPress = getCurrentSubmap()}, true, nullptr, nullptr); } void CKeybindManager::onSwitchOffEvent(const std::string& switchName) { - handleKeybinds(0, SPressedKeyWithMods{.keyName = "switch:off:" + switchName, .submapAtPress = getCurrentSubmap()}, true, nullptr, nullptr); + handleKeybinds(0, SPressedKeyWithMods{.keyName = std::format("switch:off:{}", switchName), .submapAtPress = getCurrentSubmap()}, true, nullptr, nullptr); } eMultiKeyCase CKeybindManager::mkKeysymSetMatches(const std::vector& keybindKeysyms, const std::set& pressedKeysyms) { diff --git a/src/managers/VersionKeeperManager.cpp b/src/managers/VersionKeeperManager.cpp index 12fde80de..7cc1b8496 100644 --- a/src/managers/VersionKeeperManager.cpp +++ b/src/managers/VersionKeeperManager.cpp @@ -27,10 +27,10 @@ CVersionKeeperManager::CVersionKeeperManager() { if (!DATAROOT) return; - auto LASTVER = NFsUtils::readFileAsString(*DATAROOT + "/" + VERSION_FILE_NAME); + auto LASTVER = NFsUtils::readFileAsString(std::format("{}/{}", *DATAROOT, VERSION_FILE_NAME)); if (!LASTVER) { - NFsUtils::writeToFile(*DATAROOT + "/" + VERSION_FILE_NAME, "0.0.0"); + NFsUtils::writeToFile(std::format("{}/{}", *DATAROOT, VERSION_FILE_NAME), "0.0.0"); LASTVER = "0.0.0"; return; } @@ -40,7 +40,7 @@ CVersionKeeperManager::CVersionKeeperManager() { return; } - NFsUtils::writeToFile(*DATAROOT + "/" + VERSION_FILE_NAME, HYPRLAND_VERSION); + NFsUtils::writeToFile(std::format("{}/{}", *DATAROOT, VERSION_FILE_NAME), HYPRLAND_VERSION); if (*PNONOTIFY) { Log::logger->log(Log::DEBUG, "CVersionKeeperManager: updated, but update news is disabled in the config :("); diff --git a/src/managers/XCursorManager.cpp b/src/managers/XCursorManager.cpp index 7a4bbddd7..7aa24162c 100644 --- a/src/managers/XCursorManager.cpp +++ b/src/managers/XCursorManager.cpp @@ -294,13 +294,13 @@ std::set CXCursorManager::themePaths(std::string const& theme) { Log::logger->log(Log::DEBUG, "XCursor scanning theme {}", t); while (std::getline(ss, line, ':')) { - auto p = expandTilde(line + "/" + t + "/cursors"); + auto p = expandTilde(std::format("{}/{}/cursors", line, t)); if (std::filesystem::exists(p) && std::filesystem::is_directory(p)) { Log::logger->log(Log::DEBUG, "XCursor using theme path {}", p); paths.insert(p); } - auto inherit = expandTilde(line + "/" + t + "/index.theme"); + auto inherit = expandTilde(std::format("{}/{}/index.theme", line, t)); if (std::filesystem::exists(inherit) && std::filesystem::is_regular_file(inherit)) { auto inheritThemes = getInheritThemes(inherit); for (auto const& i : inheritThemes) { diff --git a/src/managers/input/Eis.cpp b/src/managers/input/Eis.cpp index 9b1654bfa..d34b2add8 100644 --- a/src/managers/input/Eis.cpp +++ b/src/managers/input/Eis.cpp @@ -24,7 +24,7 @@ CEis::CEis(std::string socketName) { const char* xdg = getenv("XDG_RUNTIME_DIR"); if (xdg) - m_socketPath = std::string(xdg) + "/" + socketName; + m_socketPath = std::format("{}/{}", xdg, socketName); if (m_socketPath.empty()) { Log::logger->log(Log::ERR, "[EIS] Socket path is empty"); diff --git a/src/managers/input/InputManager.cpp b/src/managers/input/InputManager.cpp index 634552268..fce6f56aa 100644 --- a/src/managers/input/InputManager.cpp +++ b/src/managers/input/InputManager.cpp @@ -1183,7 +1183,7 @@ void CInputManager::setupKeyboard(SP keeb) { g_pKeybindManager->m_keyToCodeCache.clear(); } - IPC::Socket2::sock()->postEvent({"activelayout", PKEEB->m_hlName + "," + LAYOUT}); + IPC::Socket2::sock()->postEvent({"activelayout", std::format("{},{}", PKEEB->m_hlName, LAYOUT)}); Event::bus()->m_events.input.keyboard.layout.emit(PKEEB, LAYOUT); }); @@ -1284,7 +1284,7 @@ void CInputManager::applyConfigToKeyboard(SP pKeyboard) { const auto LAYOUTSTR = pKeyboard->getActiveLayout(); - IPC::Socket2::sock()->postEvent({"activelayout", pKeyboard->m_hlName + "," + LAYOUTSTR}); + IPC::Socket2::sock()->postEvent({"activelayout", std::format("{},{}", pKeyboard->m_hlName, LAYOUTSTR)}); Event::bus()->m_events.input.keyboard.layout.emit(pKeyboard, LAYOUTSTR); Log::logger->log(Log::DEBUG, "Set the keyboard layout to {} and variant to {} for keyboard \"{}\"", pKeyboard->m_currentRules.layout, pKeyboard->m_currentRules.variant, @@ -1725,7 +1725,7 @@ void CInputManager::onKeyboardMod(SP pKeyboard) { Log::logger->log(Log::DEBUG, "LAYOUT CHANGED TO {} GROUP {}", LAYOUT, MODS.group); - IPC::Socket2::sock()->postEvent({"activelayout", pKeyboard->m_hlName + "," + LAYOUT}); + IPC::Socket2::sock()->postEvent({"activelayout", std::format("{},{}", pKeyboard->m_hlName, LAYOUT)}); Event::bus()->m_events.input.keyboard.layout.emit(pKeyboard, LAYOUT); } } @@ -2118,7 +2118,9 @@ std::string CInputManager::getNameForNewDevice(std::string internalName) { auto proposedNewName = deviceNameToInternalString(internalName); int dupeno = 0; - auto makeNewName = [&]() { return (proposedNewName.empty() ? "unknown-device" : proposedNewName) + (dupeno == 0 ? "" : ("-" + std::to_string(dupeno))); }; + auto makeNewName = [&]() { + return std::format("{}{}", proposedNewName.empty() ? "unknown-device" : proposedNewName, dupeno == 0 ? std::string{} : std::format("-{}", dupeno)); + }; while (std::ranges::find_if(m_hids, [&](const auto& other) { return other->m_hlName == makeNewName(); }) != m_hids.end()) dupeno++; diff --git a/src/managers/input/trackpad/gestures/SpecialWorkspaceGesture.cpp b/src/managers/input/trackpad/gestures/SpecialWorkspaceGesture.cpp index d93be9033..2c75ebfda 100644 --- a/src/managers/input/trackpad/gestures/SpecialWorkspaceGesture.cpp +++ b/src/managers/input/trackpad/gestures/SpecialWorkspaceGesture.cpp @@ -31,7 +31,7 @@ void CSpecialWorkspaceGesture::begin(const ITrackpadGesture::STrackpadGestureBeg m_lastDelta = 0.F; m_monitor.reset(); - m_specialWorkspace = State::workspaceState()->query().name("special:" + m_specialWorkspaceName).run(); + m_specialWorkspace = State::workspaceState()->query().name(std::format("special:{}", m_specialWorkspaceName)).run(); if (m_specialWorkspace) { m_animatingOut = m_specialWorkspace->isVisible(); @@ -50,7 +50,7 @@ void CSpecialWorkspaceGesture::begin(const ITrackpadGesture::STrackpadGestureBeg m_animatingOut = false; - const auto& [workspaceID, workspaceName, isAutoID] = getWorkspaceIDNameFromString("special:" + m_specialWorkspaceName); + const auto& [workspaceID, workspaceName, isAutoID] = getWorkspaceIDNameFromString(std::format("special:{}", m_specialWorkspaceName)); const auto WS = State::workspaceState()->create(workspaceID, m_monitor->m_id, workspaceName); m_monitor->setSpecialWorkspace(WS); m_specialWorkspace = WS; diff --git a/src/managers/permissions/DynamicPermissionManager.cpp b/src/managers/permissions/DynamicPermissionManager.cpp index 0f9283782..1e7943f9e 100644 --- a/src/managers/permissions/DynamicPermissionManager.cpp +++ b/src/managers/permissions/DynamicPermissionManager.cpp @@ -85,7 +85,7 @@ eDynamicPermissionAllowMode CDynamicPermissionManager::clientPermissionMode(wl_c const auto LOOKUP = binaryNameForWlClient(client); Log::logger->log(Log::TRACE, "CDynamicPermissionManager::clientHasPermission: checking permission {} for client {:x} (binary {})", permissionToString(permission), - rc(client), LOOKUP.has_value() ? LOOKUP.value() : "lookup failed: " + LOOKUP.error()); + rc(client), LOOKUP.has_value() ? LOOKUP.value() : std::format("lookup failed: {}", LOOKUP.error())); // first, check if we have the client + perm combo in our cache. auto it = std::ranges::find_if(m_rules, [client, permission](const auto& e) { return e->m_client == client && e->m_type == permission; }); @@ -161,7 +161,7 @@ eDynamicPermissionAllowMode CDynamicPermissionManager::clientPermissionModeWithS lookup = binaryNameForPid(pid); Log::logger->log(Log::TRACE, "CDynamicPermissionManager::clientHasPermission: checking permission {} for key {} (binary {})", permissionToString(permission), str, - lookup.has_value() ? lookup.value() : "lookup failed: " + lookup.error()); + lookup.has_value() ? lookup.value() : std::format("lookup failed: {}", lookup.error())); if (lookup.has_value()) binaryName = *lookup; diff --git a/src/output/Monitor.cpp b/src/output/Monitor.cpp index 7e415311b..0518b3496 100644 --- a/src/output/Monitor.cpp +++ b/src/output/Monitor.cpp @@ -1032,7 +1032,7 @@ bool CMonitor::applyMonitorRule(Config::CMonitorRule&& pMonitorRule) { m_scale = std::round(scaleZero); else { Log::logger->log(Log::ERR, "Invalid scale passed to monitor, {} failed to find a clean divisor", m_scale); - ErrorOverlay::overlay()->queueError("Invalid scale passed to monitor " + m_name + ", failed to find a clean divisor"); + ErrorOverlay::overlay()->queueError(std::format("Invalid scale passed to monitor {}, failed to find a clean divisor", m_name)); m_scale = getDefaultScale(); } } else { @@ -1565,8 +1565,8 @@ void CMonitor::setSpecialWorkspace(const PHLWORKSPACE& pWorkspace) { if (m_activeSpecialWorkspace) { m_activeSpecialWorkspace->m_visible = false; Animation::Workspace::startAnimation(m_activeSpecialWorkspace, Animation::Workspace::ANIMATION_TYPE_OUT, false); - IPC::Socket2::sock()->postEvent({"activespecial", "," + m_name}); - IPC::Socket2::sock()->postEvent({"activespecialv2", ",," + m_name}); + IPC::Socket2::sock()->postEvent({"activespecial", std::format(",{}", m_name)}); + IPC::Socket2::sock()->postEvent({"activespecialv2", std::format(",,{}", m_name)}); // Reset layer surface state when closing special workspace for (auto const& ls : Desktop::layerState()->layers()) { @@ -1614,8 +1614,8 @@ void CMonitor::setSpecialWorkspace(const PHLWORKSPACE& pWorkspace) { PMONITOR->m_activeSpecialWorkspace.reset(); g_layoutManager->recalculateMonitor(PMONITOR, Layout::CLayoutManager::RECALCULATE_MONITOR_REASON_TOGGLE_SPECIAL_WORKSPACE); g_pHyprRenderer->damageMonitor(PMONITOR); - IPC::Socket2::sock()->postEvent({"activespecial", "," + PMONITOR->m_name}); - IPC::Socket2::sock()->postEvent({"activespecialv2", ",," + PMONITOR->m_name}); + IPC::Socket2::sock()->postEvent({"activespecial", std::format(",{}", PMONITOR->m_name)}); + IPC::Socket2::sock()->postEvent({"activespecialv2", std::format(",,{}", PMONITOR->m_name)}); // Reset layer surfaces on the old monitor when special workspace is stolen for (auto const& ls : Desktop::layerState()->layers()) { @@ -1686,8 +1686,8 @@ void CMonitor::setSpecialWorkspace(const PHLWORKSPACE& pWorkspace) { g_pInputManager->refocus(); } - IPC::Socket2::sock()->postEvent({"activespecial", pWorkspace->m_name + "," + m_name}); - IPC::Socket2::sock()->postEvent({"activespecialv2", std::to_string(pWorkspace->m_id) + "," + pWorkspace->m_name + "," + m_name}); + IPC::Socket2::sock()->postEvent({"activespecial", std::format("{},{}", pWorkspace->m_name, m_name)}); + IPC::Socket2::sock()->postEvent({"activespecialv2", std::format("{},{},{}", pWorkspace->m_id, pWorkspace->m_name, m_name)}); g_pHyprRenderer->damageMonitor(m_self.lock()); diff --git a/src/plugins/HookSystem.cpp b/src/plugins/HookSystem.cpp index 15ae0f50b..03d993544 100644 --- a/src/plugins/HookSystem.cpp +++ b/src/plugins/HookSystem.cpp @@ -64,7 +64,7 @@ CFunctionHook::SInstructionProbe CFunctionHook::probeMinimumJumpSize(void* start auto probe = getInstructionLenAt(sc(start) + size); sizes.push_back(probe.len); size += probe.len; - instrs += probe.assembly + "\n"; + instrs += std::format("{}\n", probe.assembly); } return {size, instrs, sizes}; diff --git a/src/plugins/PluginAPI.cpp b/src/plugins/PluginAPI.cpp index 08378455d..292942d62 100644 --- a/src/plugins/PluginAPI.cpp +++ b/src/plugins/PluginAPI.cpp @@ -27,8 +27,8 @@ APICALL const char* __hyprland_api_get_hash() { return std::string{v.substr(0, v.find_last_of('.'))}; }; - static const std::string ver = (std::string{GIT_COMMIT_HASH} + "_aq_" + stripPatch(AQUAMARINE_VERSION) + "_hu_" + stripPatch(HYPRUTILS_VERSION) + "_hg_" + - stripPatch(HYPRGRAPHICS_VERSION) + "_hc_" + stripPatch(HYPRCURSOR_VERSION) + "_hlg_" + stripPatch(HYPRLANG_VERSION)); + static const std::string ver = std::format("{}_aq_{}_hu_{}_hg_{}_hc_{}_hlg_{}", GIT_COMMIT_HASH, stripPatch(AQUAMARINE_VERSION), stripPatch(HYPRUTILS_VERSION), + stripPatch(HYPRGRAPHICS_VERSION), stripPatch(HYPRCURSOR_VERSION), stripPatch(HYPRLANG_VERSION)); return ver.c_str(); } @@ -58,9 +58,9 @@ APICALL bool HyprlandAPI::unregisterCallback(HANDLE handle, SP APICALL std::string HyprlandAPI::invokeHyprctlCommand(const std::string& call, const std::string& args, const std::string& format) { if (args.empty()) - return IPC::Socket1::sock()->invoke(format + "/" + call); + return IPC::Socket1::sock()->invoke(std::format("{}/{}", format, call)); else - return IPC::Socket1::sock()->invoke(format + "/" + call + " " + args); + return IPC::Socket1::sock()->invoke(std::format("{}/{} {}", format, call, args)); } APICALL bool HyprlandAPI::addLayout(HANDLE handle, const std::string& name, IHyprLayout* layout) { @@ -287,11 +287,11 @@ APICALL std::vector HyprlandAPI::findFunctionsByName(HANDLE hand #endif #ifdef __clang__ - static const auto SYMBOLS = execAndGet(("llvm-nm -D -j \"" + FPATH.string() + "\"").c_str()); - static const auto SYMBOLSDEMANGLED = execAndGet(("llvm-nm -D -j --demangle \"" + FPATH.string() + "\"").c_str()); + static const auto SYMBOLS = execAndGet(std::format("llvm-nm -D -j \"{}\"", FPATH.string()).c_str()); + static const auto SYMBOLSDEMANGLED = execAndGet(std::format("llvm-nm -D -j --demangle \"{}\"", FPATH.string()).c_str()); #else - static const auto SYMBOLS = execAndGet(("nm -D -j \"" + FPATH.string() + "\"").c_str()); - static const auto SYMBOLSDEMANGLED = execAndGet(("nm -D -j --demangle=auto \"" + FPATH.string() + "\"").c_str()); + static const auto SYMBOLS = execAndGet(std::format("nm -D -j \"{}\"", FPATH.string()).c_str()); + static const auto SYMBOLSDEMANGLED = execAndGet(std::format("nm -D -j --demangle=auto \"{}\"", FPATH.string()).c_str()); #endif auto demangledFromID = [&](size_t id) -> std::string { diff --git a/src/plugins/PluginAPI.hpp b/src/plugins/PluginAPI.hpp index dbe5ff794..0ad9d519b 100644 --- a/src/plugins/PluginAPI.hpp +++ b/src/plugins/PluginAPI.hpp @@ -30,6 +30,7 @@ Feel like the API is missing something you'd like to use in your plugin? Open an #include "../event/EventBus.hpp" #include +#include #include #include #include @@ -400,8 +401,8 @@ APICALL inline EXPORT const char* __hyprland_api_get_client_hash() { return std::string{v.substr(0, v.find_last_of('.'))}; }; - static const std::string ver = (std::string{GIT_COMMIT_HASH} + "_aq_" + stripPatch(AQUAMARINE_VERSION) + "_hu_" + stripPatch(HYPRUTILS_VERSION) + "_hg_" + - stripPatch(HYPRGRAPHICS_VERSION) + "_hc_" + stripPatch(HYPRCURSOR_VERSION) + "_hlg_" + stripPatch(HYPRLANG_VERSION)); + static const std::string ver = std::format("{}_aq_{}_hu_{}_hg_{}_hc_{}_hlg_{}", GIT_COMMIT_HASH, stripPatch(AQUAMARINE_VERSION), stripPatch(HYPRUTILS_VERSION), + stripPatch(HYPRGRAPHICS_VERSION), stripPatch(HYPRCURSOR_VERSION), stripPatch(HYPRLANG_VERSION)); return ver.c_str(); } diff --git a/src/protocols/Hotkey.cpp b/src/protocols/Hotkey.cpp index d05004606..c095fa284 100644 --- a/src/protocols/Hotkey.cpp +++ b/src/protocols/Hotkey.cpp @@ -36,7 +36,7 @@ static std::string keybindLabel(const SP& k) { if (!k->description.empty()) return k->description; if (!k->arg.empty()) - return k->handler + ", " + k->arg; + return std::format("{}, {}", k->handler, k->arg); return k->handler; } diff --git a/src/protocols/InputCapture.cpp b/src/protocols/InputCapture.cpp index fe9b31159..d6ad005af 100644 --- a/src/protocols/InputCapture.cpp +++ b/src/protocols/InputCapture.cpp @@ -41,7 +41,7 @@ CInputCaptureResource::CInputCaptureResource(SP resourc m_resource->setRelease([this](CHyprlandInputCaptureV1* r, uint32_t activationId, double x, double y) { onRelease(activationId, x, y); }); m_resource->setClearBarriers([this](CHyprlandInputCaptureV1* r) { onClearBarriers(); }); - m_eis = makeUnique("eis-" + std::to_string(eisCounter++)); + m_eis = makeUnique(std::format("eis-{}", eisCounter++)); const int EISFD = m_eis->getFileDescriptor(); if (EISFD >= 0) @@ -181,7 +181,7 @@ void CInputCaptureResource::onAddBarrier(uint32_t zoneSet, uint32_t id, uint32_t Log::logger->log(Log::INFO, "[input-capture]({}) Barrier {} is invalid [{}, {}], [{}, {}]", m_sessionId.c_str(), id, sx1, sy1, sx2, sy2); if (*PENFORCEBARRIERS) { - m_resource->error(HYPRLAND_INPUT_CAPTURE_V1_ERROR_INVALID_BARRIER, "The barrier id " + std::to_string(id) + " is invalid"); + m_resource->error(HYPRLAND_INPUT_CAPTURE_V1_ERROR_INVALID_BARRIER, std::format("The barrier id {} is invalid", id)); return; } } diff --git a/src/render/OpenGL.cpp b/src/render/OpenGL.cpp index 1b6105975..87337c531 100644 --- a/src/render/OpenGL.cpp +++ b/src/render/OpenGL.cpp @@ -927,7 +927,7 @@ void CHyprOpenGLImpl::applyScreenShader(const std::string& path) { std::error_code ec; if (!std::filesystem::is_regular_file(absPath, ec)) { if (ec) - ErrorOverlay::overlay()->queueError("Screen shader parser: Failed to check screen shader path: " + ec.message()); + ErrorOverlay::overlay()->queueError(std::format("Screen shader parser: Failed to check screen shader path: {}", ec.message())); else ErrorOverlay::overlay()->queueError("Screen shader parser: Screen shader path is not a regular file"); return; diff --git a/src/render/Renderer.cpp b/src/render/Renderer.cpp index f6da37bd2..12a9a3238 100644 --- a/src/render/Renderer.cpp +++ b/src/render/Renderer.cpp @@ -1477,7 +1477,7 @@ void IHyprRenderer::requestBackgroundResource() { std::string IHyprRenderer::resolveAssetPath(const std::string& filename) { std::string fullPath; for (auto& e : ASSET_PATHS) { - std::string p = std::string{e} + "/hypr/" + filename; + std::string p = std::format("{}/hypr/{}", e, filename); std::error_code ec; if (std::filesystem::exists(p, ec)) { fullPath = p; @@ -2996,8 +2996,7 @@ std::tuple IHyprRenderer::getRenderTimes(PHLMONITOR pMonito static int handleCrashLoop(void* data) { - Notification::overlay()->addNotification("Hyprland will crash in " + std::to_string(10 - sc(g_pHyprRenderer->m_crashingDistort * 2.f)) + "s.", CHyprColor(0), 5000, - ICON_INFO); + Notification::overlay()->addNotification(std::format("Hyprland will crash in {}s.", 10 - sc(g_pHyprRenderer->m_crashingDistort * 2.f)), CHyprColor(0), 5000, ICON_INFO); g_pHyprRenderer->m_crashingDistort += 0.5f; diff --git a/src/render/ShaderLoader.cpp b/src/render/ShaderLoader.cpp index 908b45858..94751a4b8 100644 --- a/src/render/ShaderLoader.cpp +++ b/src/render/ShaderLoader.cpp @@ -124,7 +124,7 @@ std::string CShaderLoader::processSource(const std::string& source, glslang_stag while (std::getline(stream, line)) { if (!line.starts_with("#line ")) - code += line + "\n"; + code += std::format("{}\n", line); } glslang_shader_delete(shader); @@ -175,12 +175,12 @@ std::string CShaderLoader::loadShader(const std::string& filename) { } const auto home = Hyprutils::Path::getHome(); if (home.has_value()) { - const auto src = NFsUtils::readFileAsString(home.value() + "/hypr/shaders/" + filename); + const auto src = NFsUtils::readFileAsString(std::format("{}/hypr/shaders/{}", home.value(), filename)); if (src.has_value()) return src.value(); } for (auto& e : ASSET_PATHS) { - const auto src = NFsUtils::readFileAsString(std::string{e} + "/hypr/shaders/" + filename); + const auto src = NFsUtils::readFileAsString(std::format("{}/hypr/shaders/{}", e, filename)); if (src.has_value()) return src.value(); } diff --git a/src/state/WorkspacePlacementController.cpp b/src/state/WorkspacePlacementController.cpp index 49fd3d34b..06912e6ca 100644 --- a/src/state/WorkspacePlacementController.cpp +++ b/src/state/WorkspacePlacementController.cpp @@ -227,9 +227,9 @@ void CWorkspacePlacementController::swapActiveWorkspaces(PHLMONITOR pMonitorA, P } // events - IPC::Socket2::sock()->postEvent({.event = "moveworkspace", .data = PWORKSPACEA->m_name + "," + pMonitorB->m_name}); + IPC::Socket2::sock()->postEvent({.event = "moveworkspace", .data = std::format("{},{}", PWORKSPACEA->m_name, pMonitorB->m_name)}); IPC::Socket2::sock()->postEvent({.event = "moveworkspacev2", .data = std::format("{},{},{}", PWORKSPACEA->m_id, PWORKSPACEA->m_name, pMonitorB->m_name)}); - IPC::Socket2::sock()->postEvent({.event = "moveworkspace", .data = PWORKSPACEB->m_name + "," + pMonitorA->m_name}); + IPC::Socket2::sock()->postEvent({.event = "moveworkspace", .data = std::format("{},{}", PWORKSPACEB->m_name, pMonitorA->m_name)}); IPC::Socket2::sock()->postEvent({.event = "moveworkspacev2", .data = std::format("{},{},{}", PWORKSPACEB->m_id, PWORKSPACEB->m_name, pMonitorA->m_name)}); Event::bus()->m_events.workspace.moveToMonitor.emit(PWORKSPACEA, pMonitorB); @@ -373,7 +373,7 @@ void CWorkspacePlacementController::moveWorkspaceToMonitor(PHLWORKSPACE pWorkspa Desktop::globalWindowController()->updateSuspendedStates(); // event - IPC::Socket2::sock()->postEvent({.event = "moveworkspace", .data = pWorkspace->m_name + "," + pMonitor->m_name}); + IPC::Socket2::sock()->postEvent({.event = "moveworkspace", .data = std::format("{},{}", pWorkspace->m_name, pMonitor->m_name)}); IPC::Socket2::sock()->postEvent({.event = "moveworkspacev2", .data = std::format("{},{},{}", pWorkspace->m_id, pWorkspace->m_name, pMonitor->m_name)}); Event::bus()->m_events.workspace.moveToMonitor.emit(pWorkspace, pMonitor); diff --git a/src/xwayland/XWM.cpp b/src/xwayland/XWM.cpp index 5cf5c7e15..2a1cf5db8 100644 --- a/src/xwayland/XWM.cpp +++ b/src/xwayland/XWM.cpp @@ -1577,7 +1577,7 @@ bool SXSelection::sendData(xcb_selection_request_event_t* e, std::string mime) { if (Env::isTrace()) { std::string mimeList = ""; for (const auto& m : MIMES) { - mimeList += "'" + m + "', "; + mimeList += std::format("'{}', ", m); } if (!MIMES.empty()) diff --git a/tests/config/lua/LuaBindingsInternal.cpp b/tests/config/lua/LuaBindingsInternal.cpp index c3a2d1601..fffd8eb22 100644 --- a/tests/config/lua/LuaBindingsInternal.cpp +++ b/tests/config/lua/LuaBindingsInternal.cpp @@ -391,7 +391,7 @@ TEST(ConfigLuaRequire, absolutePathLoadsAndTracksFile) { CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig); const auto L = CConfigManagerPluginLuaTestAccessor::luaState(mgr); - const auto CODE = "mod = require(" + luaString(module.string()) + ")"; + const auto CODE = std::format("mod = require({})", luaString(module.string())); ASSERT_EQ(luaL_dostring(L, CODE.c_str()), LUA_OK) << lua_tostring(L, -1); lua_getglobal(L, "mod"); @@ -517,6 +517,6 @@ TEST(ConfigLuaRequire, packagePathPreservesLuaDefaultsAfterConfigDirectory) { CConfigManager mgr; CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig); - const auto configPath = (tmp.path() / "?.lua").string() + ";" + (tmp.path() / "?/init.lua").string(); - EXPECT_EQ(packagePath(CConfigManagerPluginLuaTestAccessor::luaState(mgr)), configPath + ";" + defaultPath); + const auto configPath = std::format("{};{}", (tmp.path() / "?.lua").string(), (tmp.path() / "?/init.lua").string()); + EXPECT_EQ(packagePath(CConfigManagerPluginLuaTestAccessor::luaState(mgr)), std::format("{};{}", configPath, defaultPath)); }