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
This commit is contained in:
Miko
2026-08-01 18:02:50 +02:00
committed by GitHub
parent 2f9169f05f
commit 88c6386994
65 changed files with 297 additions and 276 deletions
+3 -5
View File
@@ -11,8 +11,6 @@
#include <hyprutils/string/VarList2.hpp> #include <hyprutils/string/VarList2.hpp>
using namespace Hyprutils::String; using namespace Hyprutils::String;
using namespace std::string_literals;
constexpr const char* SOCKET_NAME = ".hyprpaper.sock"; constexpr const char* SOCKET_NAME = ".hyprpaper.sock";
static SP<CCHyprpaperCoreImpl> g_coreImpl; static SP<CCHyprpaperCoreImpl> g_coreImpl;
@@ -48,7 +46,7 @@ static std::expected<std::string, std::string> getFullPath(const std::string_vie
if (!HOME || HOME[0] == '\0') if (!HOME || HOME[0] == '\0')
return std::unexpected("home path but no $HOME"); 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); return resolvePath(sv);
@@ -79,7 +77,7 @@ static std::expected<void, std::string> doWallpaper(const std::string_view& RHS)
if (!PATH) if (!PATH)
return std::unexpected(std::format("bad path: {}", PATH_RAW)); 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); auto socket = Hyprwire::IClientSocket::open(socketPath);
@@ -149,7 +147,7 @@ static std::expected<void, std::string> doListActive() {
if (!HIS || HIS[0] == '\0') if (!HIS || HIS[0] == '\0')
return std::unexpected("can't send: no HYPRLAND_INSTANCE_SIGNATURE (not running under hyprland)"); 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); auto socket = Hyprwire::IClientSocket::open(socketPath);
+12 -14
View File
@@ -81,12 +81,10 @@ static int getUID() {
std::string getRuntimeDir() { std::string getRuntimeDir() {
const auto XDG = getenv("XDG_RUNTIME_DIR"); const auto XDG = getenv("XDG_RUNTIME_DIR");
if (!XDG) { if (!XDG)
const std::string USERID = std::to_string(getUID()); return std::format("/run/user/{}/hypr", getUID());
return "/run/user/" + USERID + "/hypr";
}
return std::string{XDG} + "/hypr"; return std::format("{}/hypr", XDG);
} }
static std::optional<uint64_t> toUInt64(const std::string_view str) { static std::optional<uint64_t> 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}; sockaddr_un serverAddress = {0};
serverAddress.sun_family = AF_UNIX; 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); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1);
if (connect(SERVERSOCKET, rc<sockaddr*>(&serverAddress), SUN_LEN(&serverAddress)) < 0) { if (connect(SERVERSOCKET, rc<sockaddr*>(&serverAddress), SUN_LEN(&serverAddress)) < 0) {
log("Couldn't connect to " + socketPath + ". (4)"); log(std::format("Couldn't connect to {}. (4)", socketPath));
return 4; return 4;
} }
@@ -296,12 +294,12 @@ int requestIPC(std::string_view filename, std::string_view arg) {
sockaddr_un serverAddress = {0}; sockaddr_un serverAddress = {0};
serverAddress.sun_family = AF_UNIX; 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); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1);
if (connect(SERVERSOCKET, rc<sockaddr*>(&serverAddress), SUN_LEN(&serverAddress)) < 0) { if (connect(SERVERSOCKET, rc<sockaddr*>(&serverAddress), SUN_LEN(&serverAddress)) < 0) {
log("Couldn't connect to " + socketPath + ". (3)"); log(std::format("Couldn't connect to {}. (3)", socketPath));
return 3; return 3;
} }
@@ -344,7 +342,7 @@ void batchRequest(std::string_view arg, bool json) {
commands.insert(0, "j/"); commands.insert(0, "j/");
} }
std::string rq = "[[BATCH]]" + commands; std::string rq = std::format("[[BATCH]]{}", commands);
request(rq); request(rq);
} }
@@ -375,7 +373,7 @@ void instancesRequest(bool json) {
result += "\n]"; result += "\n]";
} }
log(result + "\n"); log(std::format("{}\n", result));
} }
std::vector<std::string> splitArgs(int argc, char** argv) { std::vector<std::string> splitArgs(int argc, char** argv) {
@@ -467,7 +465,7 @@ int main(int argc, char** argv) {
continue; continue;
} }
fullRequest += ARGS[i] + " "; fullRequest += std::format("{} ", ARGS[i]);
} }
if (fullRequest.empty()) { if (fullRequest.empty()) {
@@ -477,7 +475,7 @@ int main(int argc, char** argv) {
fullRequest.pop_back(); // remove trailing space fullRequest.pop_back(); // remove trailing space
fullRequest = fullArgs + "/" + fullRequest; fullRequest = std::format("{}/{}", fullArgs, fullRequest);
// instances is HIS-independent // instances is HIS-independent
if (fullRequest.contains("/instances")) { if (fullRequest.contains("/instances")) {
@@ -568,7 +566,7 @@ int main(int argc, char** argv) {
while ((input = readline("> ")) != nullptr) { while ((input = readline("> ")) != nullptr) {
std::string line(input); std::string line(input);
if (!line.empty()) { if (!line.empty()) {
exitStatus = request("/repl " + line); exitStatus = request(std::format("/repl {}", line));
add_history(input); add_history(input);
} }
free(input); free(input);
+4 -4
View File
@@ -27,18 +27,18 @@ static std::string getTempRoot() {
// write the state to a file // write the state to a file
static bool writeState(const std::string& str, const std::string& to) { static bool writeState(const std::string& str, const std::string& to) {
// create temp file in a safe temp root // 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()) if (!of.good())
return false; return false;
of << str; of << str;
of.close(); 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() { 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() { std::string DataState::getHeadersPath() {
@@ -100,7 +100,7 @@ void DataState::addNewPluginRepo(const SPluginRepository& repo) {
}} }}
}; };
for (auto const& p : repo.plugins) { 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 // copy .so to the good place and chmod 755
if (std::filesystem::exists(p.filename)) { if (std::filesystem::exists(p.filename)) {
+5 -7
View File
@@ -38,12 +38,10 @@ static int getUID() {
static std::string getRuntimeDir() { static std::string getRuntimeDir() {
const auto XDG = getenv("XDG_RUNTIME_DIR"); const auto XDG = getenv("XDG_RUNTIME_DIR");
if (!XDG) { if (!XDG)
const std::string USERID = std::to_string(getUID()); return std::format("/run/user/{}/hypr", getUID());
return "/run/user/" + USERID + "/hypr";
}
return std::string{XDG} + "/hypr"; return std::format("{}/hypr", XDG);
} }
std::string NHyprlandSocket::send(const std::string& cmd) { std::string NHyprlandSocket::send(const std::string& cmd) {
@@ -64,12 +62,12 @@ std::string NHyprlandSocket::send(const std::string& cmd) {
sockaddr_un serverAddress = {0}; sockaddr_un serverAddress = {0};
serverAddress.sun_family = AF_UNIX; 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); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1);
if (connect(SERVERSOCKET, rc<sockaddr*>(&serverAddress), SUN_LEN(&serverAddress)) < 0) { if (connect(SERVERSOCKET, rc<sockaddr*>(&serverAddress), SUN_LEN(&serverAddress)) < 0) {
std::println("{}", failureString("Couldn't connect to " + socketPath + ". (4)")); std::println("{}", failureString("Couldn't connect to {}. (4)", socketPath));
return ""; return "";
} }
+51 -50
View File
@@ -51,7 +51,7 @@ static std::string getTempRoot() {
exit(1); exit(1);
} }
const auto STR = ENV + std::string{"/hyprpm/"}; const auto STR = std::format("{}/hyprpm/", ENV);
return STR; return STR;
} }
@@ -203,7 +203,7 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string&
const std::string USERNAME = getpwuid(getuid())->pw_name; const std::string USERNAME = getpwuid(getuid())->pw_name;
m_szWorkingPluginDirectory = getTempRoot() + USERNAME; m_szWorkingPluginDirectory = std::format("{}{}", getTempRoot(), USERNAME);
if (!createSafeDirectory(m_szWorkingPluginDirectory)) { if (!createSafeDirectory(m_szWorkingPluginDirectory)) {
std::println(stderr, "\n{}", failureString("Could not prepare working dir for repo")); 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)); 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)); std::println(stderr, "\n{}", failureString("Could not clone the plugin repository. shell returned:\n{}", ret));
return false; return false;
} }
if (!rev.empty()) { 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) { if (ret.compare(0, 6, "fatal:") == 0) {
std::println(stderr, "\n{}", failureString("Could not check out revision {}. shell returned:\n{}", rev, ret)); std::println(stderr, "\n{}", failureString("Could not check out revision {}. shell returned:\n{}", rev, ret));
return false; 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) if (m_bVerbose)
std::println("{}", verboseString("git submodule update --init returned: {}", ret)); 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<CManifest> pManifest; std::unique_ptr<CManifest> 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")); progress.printMessageAbove(successString("found hyprpm manifest"));
pManifest = std::make_unique<CManifest>(MANIFEST_HYPRPM, m_szWorkingPluginDirectory + "/hyprpm.toml"); pManifest = std::make_unique<CManifest>(MANIFEST_HYPRPM, std::format("{}/hyprpm.toml", m_szWorkingPluginDirectory));
} else if (std::filesystem::exists(m_szWorkingPluginDirectory + "/hyprload.toml")) { } else if (std::filesystem::exists(std::format("{}/hyprload.toml", m_szWorkingPluginDirectory))) {
progress.printMessageAbove(successString("found hyprload manifest")); progress.printMessageAbove(successString("found hyprload manifest"));
pManifest = std::make_unique<CManifest>(MANIFEST_HYPRLOAD, m_szWorkingPluginDirectory + "/hyprload.toml"); pManifest = std::make_unique<CManifest>(MANIFEST_HYPRLOAD, std::format("{}/hyprload.toml", m_szWorkingPluginDirectory));
} }
if (!pManifest) { if (!pManifest) {
@@ -256,17 +256,17 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string&
} }
progress.m_iSteps = 2; 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) { 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) { for (auto const& a : pl.authors) {
message += a + ", "; message += std::format("{}, ", a);
} }
if (pl.authors.size() > 0) { if (pl.authors.size() > 0) {
message.pop_back(); message.pop_back();
message.pop_back(); message.pop_back();
} }
message += " version " + pl.version; message += std::format(" version {}", pl.version);
progress.printMessageAbove(message); 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)); 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) if (m_bVerbose)
std::println("{}", verboseString("git submodule update --init returned: {}", ret)); std::println("{}", verboseString("git submodule update --init returned: {}", ret));
@@ -333,13 +333,13 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string&
break; break;
} }
out += " -> " + *CMD_RAW + "\n" + execAndGet(*CMD_RAW) + "\n"; out += std::format(" -> {}\n{}\n", *CMD_RAW, execAndGet(*CMD_RAW));
} }
if (m_bVerbose) if (m_bVerbose)
std::println("{}", verboseString("shell returned: {}", out)); 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" 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" " 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" " 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 // add repo toml to DataState
SPluginRepository repo; 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) if (repohash.length() > 0)
repohash.pop_back(); repohash.pop_back();
auto lastSlash = url.find_last_of('/'); auto lastSlash = url.find_last_of('/');
@@ -371,7 +371,7 @@ bool CPluginManager::addNewPluginRepo(const std::string& url, const std::string&
repo.rev = rev; repo.rev = rev;
repo.hash = repohash; repo.hash = repohash;
for (auto const& p : pManifest->m_plugins) { 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); DataState::addNewPluginRepo(repo);
@@ -414,7 +414,7 @@ bool CPluginManager::removePluginRepo(const SPluginRepoIdentifier& identifier) {
eHeadersErrors CPluginManager::headersValid() { eHeadersErrors CPluginManager::headersValid() {
const auto HLVER = getHyprlandVersion(false); 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; return HEADERS_MISSING;
// find headers commit // find headers commit
@@ -439,7 +439,7 @@ eHeadersErrors CPluginManager::headersValid() {
if (PATH.ends_with("protocols")) if (PATH.ends_with("protocols"))
continue; continue;
verHeader = trim(PATH.substr(2)) + "/hyprland/src/version.h"; verHeader = std::format("{}/hyprland/src/version.h", trim(PATH.substr(2)));
break; break;
} }
@@ -516,7 +516,7 @@ bool CPluginManager::updateHeaders(bool force) {
progress.print(); progress.print();
const std::string USERNAME = getpwuid(getuid())->pw_name; 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)) { if (!createSafeDirectory(WORKINGDIR)) {
std::println("\n{}", failureString("Could not prepare working dir for hl")); 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 // let us give a bit of leg-room for shallowing
// due to timezones, etc. // 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) if (m_bVerbose && bShallow)
progress.printMessageAbove(verboseString("will shallow since: {}", SHALLOW_DATE)); progress.printMessageAbove(verboseString("will shallow since: {}", SHALLOW_DATE));
std::string ret = std::string ret = execAndGet(std::format("cd {} && git clone --recursive '{}' hyprland-{}{}", getTempRoot(), HL_URL, USERNAME,
execAndGet(std::format("cd {} && git clone --recursive '{}' hyprland-{}{}", getTempRoot(), HL_URL, USERNAME, (bShallow ? " --shallow-since='" + SHALLOW_DATE + "'" : ""))); (bShallow ? std::format(" --shallow-since='{}'", SHALLOW_DATE) : std::string{})));
if (!std::filesystem::exists(WORKINGDIR)) { if (!std::filesystem::exists(WORKINGDIR)) {
progress.printMessageAbove(failureString("Clone failed. Retrying without shallow.")); progress.printMessageAbove(failureString("Clone failed. Retrying without shallow."));
ret = execAndGet(std::format("cd {} && git clone --recursive '{}' hyprland-{}", getTempRoot(), HL_URL, USERNAME)); 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)); std::println(stderr, "\n{}", failureString("Could not clone the Hyprland repository. shell returned:\n{}", ret));
return false; return false;
} }
@@ -557,7 +558,7 @@ bool CPluginManager::updateHeaders(bool force) {
if (m_bVerbose) if (m_bVerbose)
progress.printMessageAbove(verboseString("will run: cd {} && git checkout {} 2>&1", WORKINGDIR, HLVER.hash)); 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")) { if (ret.contains("fatal: unable to read tree")) {
std::println(stderr, "\n{}", std::println(stderr, "\n{}",
@@ -569,7 +570,7 @@ bool CPluginManager::updateHeaders(bool force) {
if (m_bVerbose) if (m_bVerbose)
progress.printMessageAbove(verboseString("git returned (co): {}", ret)); 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) if (m_bVerbose)
progress.printMessageAbove(verboseString("git returned (rs): {}", ret)); progress.printMessageAbove(verboseString("git returned (rs): {}", ret));
@@ -691,7 +692,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) {
progress.print(); progress.print();
const std::string USERNAME = getpwuid(getuid())->pw_name; const std::string USERNAME = getpwuid(getuid())->pw_name;
m_szWorkingPluginDirectory = getTempRoot() + USERNAME; m_szWorkingPluginDirectory = std::format("{}{}", getTempRoot(), USERNAME);
std::vector<std::string> failedRepos; std::vector<std::string> failedRepos;
@@ -709,7 +710,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) {
bool update = forceUpdateAll; bool update = forceUpdateAll;
progress.m_iSteps++; progress.m_iSteps++;
progress.m_szCurrentMessage = "Updating " + repo.name; progress.m_szCurrentMessage = std::format("Updating {}", repo.name);
progress.print(); progress.print();
progress.printMessageAbove(infoString("checking for updates for {}", repo.name)); 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)); 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)); std::println(stderr, "\n{}", failureString("could not clone repo: shell returned: {}", ret));
markRepoFailed(repo, true); markRepoFailed(repo, true);
continue; continue;
@@ -729,7 +730,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) {
if (!repo.rev.empty()) { if (!repo.rev.empty()) {
progress.printMessageAbove(infoString("Plugin has revision set, resetting: {}", repo.rev)); 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) { if (ret.compare(0, 6, "fatal:") == 0) {
std::println(stderr, "\n{}", failureString("could not check out revision {}: shell returned:\n{}", repo.rev, ret)); 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) { if (!update) {
// check if git has updates // 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()) if (!hash.empty())
hash.pop_back(); hash.pop_back();
@@ -764,12 +765,12 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) {
std::unique_ptr<CManifest> pManifest; std::unique_ptr<CManifest> 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")); progress.printMessageAbove(successString("found hyprpm manifest"));
pManifest = std::make_unique<CManifest>(MANIFEST_HYPRPM, m_szWorkingPluginDirectory + "/hyprpm.toml"); pManifest = std::make_unique<CManifest>(MANIFEST_HYPRPM, std::format("{}/hyprpm.toml", m_szWorkingPluginDirectory));
} else if (std::filesystem::exists(m_szWorkingPluginDirectory + "/hyprload.toml")) { } else if (std::filesystem::exists(std::format("{}/hyprload.toml", m_szWorkingPluginDirectory))) {
progress.printMessageAbove(successString("found hyprload manifest")); progress.printMessageAbove(successString("found hyprload manifest"));
pManifest = std::make_unique<CManifest>(MANIFEST_HYPRLOAD, m_szWorkingPluginDirectory + "/hyprload.toml"); pManifest = std::make_unique<CManifest>(MANIFEST_HYPRLOAD, std::format("{}/hyprload.toml", m_szWorkingPluginDirectory));
} }
if (!pManifest) { if (!pManifest) {
@@ -804,7 +805,7 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) {
progress.printMessageAbove(successString("commit pin {} matched hl, resetting", plugin)); 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) if (commitPinFailed)
@@ -836,13 +837,13 @@ bool CPluginManager::updatePlugins(bool forceUpdateAll) {
break; break;
} }
out += " -> " + *CMD_RAW + "\n" + execAndGet(*CMD_RAW) + "\n"; out += std::format(" -> {}\n{}\n", *CMD_RAW, execAndGet(*CMD_RAW));
} }
if (m_bVerbose) if (m_bVerbose)
std::println("{}", verboseString("shell returned: {}", out)); 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, std::println(stderr,
"\n{}\n" "\n{}\n"
" This likely means that the plugin is either outdated, not yet available for your version, or broken.\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 // add repo toml to DataState
SPluginRepository newrepo = repo; SPluginRepository newrepo = repo;
newrepo.plugins.clear(); newrepo.plugins.clear();
execAndGet("cd " + m_szWorkingPluginDirectory + execAndGet(std::format("cd {} && git pull --recurse-submodules && git reset --hard --recurse-submodules",
" && git pull --recurse-submodules && git reset --hard --recurse-submodules"); // repo hash in the state.toml has to match head and not any pin m_szWorkingPluginDirectory)); // 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"); std::string repohash = execAndGet(std::format("cd {} && git rev-parse HEAD", m_szWorkingPluginDirectory));
if (!repohash.empty()) if (!repohash.empty())
repohash.pop_back(); repohash.pop_back();
// a build failure must not record the fetched hash: the next update would consider the // 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) { for (auto const& p : pManifest->m_plugins) {
const auto OLDPLUGINIT = std::ranges::find_if(repo.plugins, [&](const auto& other) { return other.name == p.name; }); 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, 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, .enabled = OLDPLUGINIT != repo.plugins.end() ? OLDPLUGINIT->enabled : false,
.failed = p.failed}); .failed = p.failed});
} }
@@ -1011,7 +1012,7 @@ ePluginLoadStateReturn CPluginManager::ensurePluginsLoadState(bool forceReload)
for (auto const& p : loadedPlugins) { for (auto const& p : loadedPlugins) {
if (forceReload || !enabled(p)) { if (forceReload || !enabled(p)) {
// unload // 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)); std::println("{}", infoString("{} will be unloaded after restarting Hyprland", p));
hyprlandVersionMismatch = true; hyprlandVersionMismatch = true;
} else } else
@@ -1057,9 +1058,9 @@ bool CPluginManager::loadUnloadPlugin(const std::string& path, bool load) {
} }
if (load) if (load)
NHyprlandSocket::send("/plugin load " + path); NHyprlandSocket::send(std::format("/plugin load {}", path));
else else
NHyprlandSocket::send("/plugin unload " + path); NHyprlandSocket::send(std::format("/plugin unload {}", path));
return true; return true;
} }
@@ -1074,7 +1075,7 @@ void CPluginManager::listAllPlugins() {
std::println(" │ Plugin {}", p.name); std::println(" │ Plugin {}", p.name);
if (!p.failed) 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 else
std::println(" └─ enabled: {}Plugin failed to build", Colors::RED); 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) { 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<int>(icon), durationMs, color, message));
} }
std::string CPluginManager::headerError(const eHeadersErrors err) { std::string CPluginManager::headerError(const eHeadersErrors err) {
@@ -1125,7 +1126,7 @@ bool CPluginManager::hasDeps() {
std::vector<std::string> deps = {"cpio", "cmake", "pkg-config", "g++", "gcc", "git"}; std::vector<std::string> deps = {"cpio", "cmake", "pkg-config", "g++", "gcc", "git"};
for (auto const& d : deps) { 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)); std::println(stderr, "{}", failureString("Missing dependency: {}", d));
hasAllDeps = false; hasAllDeps = false;
} }
+1 -1
View File
@@ -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'; })) if (!std::ranges::all_of(mode, [](const char& c) { return c >= '0' && c <= '9'; }))
return false; 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; return proc.runSync() && proc.exitCode() == 0;
} }
+6 -7
View File
@@ -13,6 +13,7 @@
#include <algorithm> #include <algorithm>
#include <csignal> #include <csignal>
#include <cerrno> #include <cerrno>
#include <format>
#include <print> #include <print>
#include <hyprutils/memory/Casts.hpp> #include <hyprutils/memory/Casts.hpp>
using namespace Hyprutils::Memory; using namespace Hyprutils::Memory;
@@ -26,12 +27,10 @@ static int getUID() {
static std::string getRuntimeDir() { static std::string getRuntimeDir() {
const auto XDG = getenv("XDG_RUNTIME_DIR"); const auto XDG = getenv("XDG_RUNTIME_DIR");
if (!XDG) { if (!XDG)
const std::string USERID = std::to_string(getUID()); return std::format("/run/user/{}/hypr", getUID());
return "/run/user/" + USERID + "/hypr";
}
return std::string{XDG} + "/hypr"; return std::format("{}/hypr", XDG);
} }
std::vector<SInstanceData> instances() { std::vector<SInstanceData> instances() {
@@ -55,7 +54,7 @@ std::vector<SInstanceData> instances() {
} catch (std::exception& e) { continue; } } catch (std::exception& e) { continue; }
// read file // read file
std::ifstream ifs(el.path().string() + "/hyprland.lock"); std::ifstream ifs(std::format("{}/hyprland.lock", el.path().string()));
int i = 0; int i = 0;
for (std::string line; std::getline(ifs, line); ++i) { for (std::string line; std::getline(ifs, line); ++i) {
@@ -93,7 +92,7 @@ std::string getFromSocket(const std::string& cmd) {
sockaddr_un serverAddress = {0}; sockaddr_un serverAddress = {0};
serverAddress.sun_family = AF_UNIX; 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); strncpy(serverAddress.sun_path, socketPath.c_str(), sizeof(serverAddress.sun_path) - 1);
@@ -8,6 +8,7 @@
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include <optional> #include <optional>
#include <format>
#include <sys/poll.h> #include <sys/poll.h>
#include <unistd.h> #include <unistd.h>
#include <csignal> #include <csignal>
@@ -49,7 +50,7 @@ namespace {
CClient::CClient() { CClient::CClient() {
NLog::log("{}Attempting to start child-window client", Colors::YELLOW); NLog::log("{}Attempting to start child-window client", Colors::YELLOW);
this->proc = makeShared<CProcess>(binaryDir + "/child-window", std::vector<std::string>{}); this->proc = makeShared<CProcess>(std::format("{}/child-window", binaryDir), std::vector<std::string>{});
this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
@@ -7,6 +7,7 @@
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include <optional> #include <optional>
#include <format>
#include <sys/poll.h> #include <sys/poll.h>
#include <csignal> #include <csignal>
#include <thread> #include <thread>
@@ -34,7 +35,7 @@ namespace {
CClient::CClient() { CClient::CClient() {
Tests::killAllWindows(); Tests::killAllWindows();
this->proc = makeShared<CProcess>(binaryDir + "/keyboard-modifiers", std::vector<std::string>{}); this->proc = makeShared<CProcess>(std::format("{}/keyboard-modifiers", binaryDir), std::vector<std::string>{});
this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
@@ -8,6 +8,7 @@
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include <optional> #include <optional>
#include <format>
#include <sys/poll.h> #include <sys/poll.h>
#include <unistd.h> #include <unistd.h>
#include <csignal> #include <csignal>
@@ -33,7 +34,7 @@ namespace {
} }
CClient::CClient() { CClient::CClient() {
this->proc = makeShared<CProcess>(binaryDir + "/pointer-scroll", std::vector<std::string>{}); this->proc = makeShared<CProcess>(std::format("{}/pointer-scroll", binaryDir), std::vector<std::string>{});
this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
@@ -9,6 +9,7 @@
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include <optional> #include <optional>
#include <format>
#include <sys/poll.h> #include <sys/poll.h>
#include <unistd.h> #include <unistd.h>
#include <csignal> #include <csignal>
@@ -34,7 +35,7 @@ namespace {
} }
CClient::CClient() { CClient::CClient() {
this->proc = makeShared<CProcess>(binaryDir + "/pointer-warp", std::vector<std::string>{}); this->proc = makeShared<CProcess>(std::format("{}/pointer-warp", binaryDir), std::vector<std::string>{});
this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
@@ -8,6 +8,7 @@
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include <optional> #include <optional>
#include <format>
#include <sys/poll.h> #include <sys/poll.h>
#include <csignal> #include <csignal>
#include <thread> #include <thread>
@@ -34,7 +35,7 @@ namespace {
CClient::CClient() { CClient::CClient() {
Tests::killAllWindows(); Tests::killAllWindows();
this->proc = makeShared<CProcess>(binaryDir + "/shortcut-inhibitor", std::vector<std::string>{}); this->proc = makeShared<CProcess>(std::format("{}/shortcut-inhibitor", binaryDir), std::vector<std::string>{});
this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); this->proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
@@ -163,7 +164,7 @@ TEST_CASE(shortcutInhibitor) {
EXPECT(ok, true); EXPECT(ok, true);
//basic keybind test //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)")); OK(getFromSocket("/eval hl.plugin.test.keybind(1, 7, 29)"));
EXPECT(attemptCheckFlag(20, 50), false); EXPECT(attemptCheckFlag(20, 50), false);
OK(getFromSocket("/eval hl.plugin.test.keybind(0, 0, 29)")); OK(getFromSocket("/eval hl.plugin.test.keybind(0, 0, 29)"));
@@ -171,7 +172,7 @@ TEST_CASE(shortcutInhibitor) {
//keybind bypass flag test //keybind bypass flag test
EXPECT(checkFlag(), false); 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)")); OK(getFromSocket("/eval hl.plugin.test.keybind(1, 7, 29)"));
EXPECT(attemptCheckFlag(20, 50), true); EXPECT(attemptCheckFlag(20, 50), true);
OK(getFromSocket("/eval hl.plugin.test.keybind(0, 0, 29)")); OK(getFromSocket("/eval hl.plugin.test.keybind(0, 0, 29)"));
@@ -58,7 +58,7 @@ static bool waitForClientWindow(pid_t pid, int timeoutMs) {
} }
CClient::CClient() { CClient::CClient() {
m_proc = makeShared<CProcess>(binaryDir + "/surface-scale-transform", std::vector<std::string>{}); m_proc = makeShared<CProcess>(std::format("{}/surface-scale-transform", binaryDir), std::vector<std::string>{});
m_proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); m_proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
int pipeFds1[2], pipeFds2[2]; int pipeFds1[2], pipeFds2[2];
@@ -85,8 +85,8 @@ CClient::CClient() {
} while (pollRet == -1 && errno == EINTR); } while (pollRet == -1 && errno == EINTR);
if (pollRet != 1 || !(m_fds.revents & POLLIN)) 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()), throw std::runtime_error(std::format("startup stdout poll failed: ret={} revents={} alive={} pid={} binary={}/surface-scale-transform", pollRet, m_fds.revents,
m_proc->pid(), binaryDir + "/surface-scale-transform")); Tests::processAlive(m_proc->pid()), m_proc->pid(), binaryDir));
m_readBuf.fill(0); m_readBuf.fill(0);
const ssize_t bytesRead = read(m_readFd.get(), m_readBuf.data(), m_readBuf.size() - 1); 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) { 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()) if ((size_t)write(m_writeFd.get(), cmd.c_str(), cmd.length()) != cmd.length())
return ""; return "";
@@ -12,6 +12,7 @@
#include <csignal> #include <csignal>
#include <deque> #include <deque>
#include <optional> #include <optional>
#include <format>
#include <string> #include <string>
#include <sys/poll.h> #include <sys/poll.h>
#include <thread> #include <thread>
@@ -140,7 +141,7 @@ static bool click(uint32_t button, bool pressed) {
} }
static std::optional<int> statusValue(const std::string& line, const std::string& key) { static std::optional<int> statusValue(const std::string& line, const std::string& key) {
const auto KEY = key + "="; const auto KEY = std::format("{}=", key);
auto pos = line.find(KEY); auto pos = line.find(KEY);
if (pos == std::string::npos) if (pos == std::string::npos)
return std::nullopt; return std::nullopt;
@@ -209,7 +210,7 @@ std::optional<std::string> CClient::takeLineContaining(const std::string& marker
CClient::CClient() { CClient::CClient() {
NLog::log("{}Attempting to start xdg-interactive client", Colors::YELLOW); NLog::log("{}Attempting to start xdg-interactive client", Colors::YELLOW);
proc = makeShared<CProcess>(binaryDir + "/xdg-interactive", std::vector<std::string>{}); proc = makeShared<CProcess>(std::format("{}/xdg-interactive", binaryDir), std::vector<std::string>{});
proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY); proc->addEnv("WAYLAND_DISPLAY", WLDISPLAY);
int procInPipeFd[2], procOutPipeFd[2]; int procInPipeFd[2], procOutPipeFd[2];
+6 -4
View File
@@ -3,6 +3,8 @@
#include "../../hyprctlCompat.hpp" #include "../../hyprctlCompat.hpp"
#include "tests.hpp" #include "tests.hpp"
#include <format>
TEST_CASE(dwindleFloatClamp) { TEST_CASE(dwindleFloatClamp) {
for (auto const& win : {"a", "b", "c"}) { for (auto const& win : {"a", "b", "c"}) {
if (!Tests::spawnKitty(win)) { if (!Tests::spawnKitty(win)) {
@@ -202,7 +204,7 @@ TEST_CASE(dwindleForceSplitOnMoveToWorkspace) {
OK(getFromSocket("/dispatch hl.dsp.focus({ workspace = '1' })")); OK(getFromSocket("/dispatch hl.dsp.focus({ workspace = '1' })"));
ASSERT(!!Tests::spawnKitty("kitty"), true); 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("/eval hl.config({ dwindle = { force_split = 2 } })"));
OK(getFromSocket("/dispatch hl.dsp.cursor.move_to_corner({ corner = 3 })")); // top left 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 // Window A, now on top, is to be moved
auto origWinB = getFromSocket("/activewindow"); auto origWinB = getFromSocket("/activewindow");
auto expectPos = "at: " + Tests::getAttribute(origWinB, "at"); auto expectPos = std::format("at: {}", Tests::getAttribute(origWinB, "at"));
auto expectSize = "size: " + Tests::getAttribute(origWinB, "size"); auto expectSize = std::format("size: {}", Tests::getAttribute(origWinB, "size"));
OK(getFromSocket("/dispatch hl.dsp.focus({ window = 'class:a' })")); OK(getFromSocket("/dispatch hl.dsp.focus({ window = 'class:a' })"));
OK(getFromSocket("/dispatch hl.dsp.window.move({ direction = 'down' })")); 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 // 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' })")); OK(getFromSocket("/dispatch hl.dsp.window.move({ direction = 'right' })"));
+1 -1
View File
@@ -32,7 +32,7 @@ TEST_CASE(processSpawning) {
continue; 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); NLog::log("{}Expecting that sleep's parent is Hyprland", Colors::YELLOW);
EXPECT_CONTAINS(sleepParentComm, "Hyprland"); EXPECT_CONTAINS(sleepParentComm, "Hyprland");
+4 -3
View File
@@ -3,6 +3,7 @@
#include "../../hyprctlCompat.hpp" #include "../../hyprctlCompat.hpp"
#include <cstdint> #include <cstdint>
#include <string> #include <string>
#include <format>
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include <hyprutils/memory/WeakPtr.hpp> #include <hyprutils/memory/WeakPtr.hpp>
#include "../shared.hpp" #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) { 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) { TEST_CASE(hyprctlDevicesActiveLayoutIndex) {
@@ -34,9 +35,9 @@ TEST_CASE(hyprctlDevicesActiveLayoutIndex) {
for (uint8_t i = 0; i < 3; i++) { for (uint8_t i = 0; i < 3; i++) {
// set layout // set layout
getFromSocket("/switchxkblayout all " + std::to_string(i)); getFromSocket(std::format("/switchxkblayout all {}", i));
std::string devicesJson = getFromSocket("j/devices"); 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 // check layout index
EXPECT_CONTAINS(devicesJson, expected); EXPECT_CONTAINS(devicesJson, expected);
} }
+26 -21
View File
@@ -1,5 +1,6 @@
#include <filesystem> #include <filesystem>
#include <linux/input-event-codes.h> #include <linux/input-event-codes.h>
#include <format>
#include <thread> #include <thread>
#include "../../shared.hpp" #include "../../shared.hpp"
#include "../../hyprctlCompat.hpp" #include "../../hyprctlCompat.hpp"
@@ -11,7 +12,7 @@ using namespace Hyprutils::Memory;
static std::string flagFile = "/tmp/hyprtester-keybinds.txt"; static std::string flagFile = "/tmp/hyprtester-keybinds.txt";
static std::string pluginKeybindCmd(bool pressed, uint32_t modifier, uint32_t key) { 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<uint8_t>& mods, uint32_t key) { static std::string pluginKeybindMaskCmd(bool pressed, const std::vector<uint8_t>& mods, uint32_t key) {
@@ -23,11 +24,11 @@ static std::string pluginKeybindMaskCmd(bool pressed, const std::vector<uint8_t>
} }
static std::string pluginScrollCmd(int delta) { 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) { 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. // Because i don't feel like changing someone elses code.
@@ -104,7 +105,7 @@ static CUniquePointer<CProcess> spawnRemoteControlKitty() {
SUBTEST(bind) { SUBTEST(bind) {
EXPECT(checkFlag(), false); 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 // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
// await flag // await flag
@@ -116,7 +117,7 @@ SUBTEST(bind) {
SUBTEST(bindKey) { SUBTEST(bindKey) {
EXPECT(checkFlag(), false); 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 // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 0, 29))); OK(getFromSocket(pluginKeybindCmd(true, 0, 29)));
// await flag // await flag
@@ -128,7 +129,7 @@ SUBTEST(bindKey) {
SUBTEST(longPress) { SUBTEST(longPress) {
EXPECT(checkFlag(), false); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
@@ -144,7 +145,7 @@ SUBTEST(longPress) {
} }
SUBTEST(keyLongPress) { SUBTEST(keyLongPress) {
EXPECT(checkFlag(), false); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 0, 29))); OK(getFromSocket(pluginKeybindCmd(true, 0, 29)));
@@ -161,7 +162,7 @@ SUBTEST(keyLongPress) {
SUBTEST(longPressRelease) { SUBTEST(longPressRelease) {
EXPECT(checkFlag(), false); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
@@ -177,7 +178,7 @@ SUBTEST(longPressRelease) {
} }
SUBTEST(longPressOnlyKeyRelease) { SUBTEST(longPressOnlyKeyRelease) {
EXPECT(checkFlag(), false); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
@@ -195,7 +196,7 @@ SUBTEST(longPressOnlyKeyRelease) {
SUBTEST(repeat) { SUBTEST(repeat) {
EXPECT(checkFlag(), false); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
@@ -225,7 +226,7 @@ SUBTEST(keyRepeat) {
} }
EXPECT(ok, true); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 0, 29))); OK(getFromSocket(pluginKeybindCmd(true, 0, 29)));
@@ -255,7 +256,7 @@ SUBTEST(repeatRelease) {
} }
EXPECT(ok, true); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
@@ -277,7 +278,7 @@ SUBTEST(repeatRelease) {
SUBTEST(repeatOnlyKeyRelease) { SUBTEST(repeatOnlyKeyRelease) {
EXPECT(checkFlag(), false); 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"); EXPECT(getFromSocket("r/eval hl.config({ input = { repeat_delay = 100 } })"), "ok");
// press keybind // press keybind
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
@@ -591,7 +592,7 @@ SUBTEST(bindsAfterScroll) {
NLog::log("{}Testing binds after scroll", Colors::GREEN); NLog::log("{}Testing binds after scroll", Colors::GREEN);
clearFlag(); 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 // press keybind before scroll
OK(getFromSocket(pluginKeybindCmd(true, 0, 108))); // Alt_R press OK(getFromSocket(pluginKeybindCmd(true, 0, 108))); // Alt_R press
@@ -620,7 +621,7 @@ SUBTEST(submapUniversal) {
NLog::log("{}Testing submap universal", Colors::GREEN); NLog::log("{}Testing submap universal", Colors::GREEN);
EXPECT(checkFlag(), false); 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"); EXPECT_CONTAINS(getFromSocket("/submap"), "default");
// keybind works on default submap // keybind works on default submap
@@ -649,7 +650,8 @@ SUBTEST(perDeviceKeybind) {
// Inclusive // Inclusive
EXPECT(checkFlag(), false); 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))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
EXPECT(attemptCheckFlag(20, 50), true); EXPECT(attemptCheckFlag(20, 50), true);
OK(getFromSocket(pluginKeybindCmd(false, 0, 29))); OK(getFromSocket(pluginKeybindCmd(false, 0, 29)));
@@ -657,7 +659,8 @@ SUBTEST(perDeviceKeybind) {
// Exclusive // Exclusive
EXPECT(checkFlag(), false); 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))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
EXPECT(attemptCheckFlag(20, 50), false); EXPECT(attemptCheckFlag(20, 50), false);
OK(getFromSocket(pluginKeybindCmd(false, 0, 29))); OK(getFromSocket(pluginKeybindCmd(false, 0, 29)));
@@ -665,8 +668,9 @@ SUBTEST(perDeviceKeybind) {
// With description // With description
EXPECT(checkFlag(), false); EXPECT(checkFlag(), false);
EXPECT(getFromSocket("/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch " + flagFile + EXPECT(getFromSocket(std::format(
"'), { description = 'test description', device = { inclusive = true, list = { 'test-keyboard-1' } } })"), "/eval hl.bind('SUPER + Y', hl.dsp.exec_cmd('touch {}'), {{ description = 'test description', device = {{ inclusive = true, list = {{ 'test-keyboard-1' }} }} }})",
flagFile)),
"ok"); "ok");
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
EXPECT(attemptCheckFlag(20, 50), true); EXPECT(attemptCheckFlag(20, 50), true);
@@ -675,7 +679,7 @@ SUBTEST(perDeviceKeybind) {
// Tags // Tags
EXPECT(checkFlag(), false); 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))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
EXPECT(attemptCheckFlag(20, 50), true); EXPECT(attemptCheckFlag(20, 50), true);
OK(getFromSocket(pluginKeybindCmd(false, 0, 29))); OK(getFromSocket(pluginKeybindCmd(false, 0, 29)));
@@ -687,7 +691,8 @@ SUBTEST(unbind) {
// unbind should normalize the string: no spaces, lowercase OK // unbind should normalize the string: no spaces, lowercase OK
EXPECT(checkFlag(), false); 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"); EXPECT(getFromSocket("/eval hl.unbind(' super + y ')"), "ok");
OK(getFromSocket(pluginKeybindCmd(true, 7, 29))); OK(getFromSocket(pluginKeybindCmd(true, 7, 29)));
+1 -1
View File
@@ -21,7 +21,7 @@ static bool spawnLayer(const std::string& namespace_, const std::vector<std::str
static std::string getLayerLine(const std::string& layers, const std::string& target) { static std::string getLayerLine(const std::string& layers, const std::string& target) {
auto pos = layers.find("namespace: " + target); auto pos = layers.find(std::format("namespace: {}", target));
if (pos == std::string::npos) if (pos == std::string::npos)
return ""; return "";
+5 -4
View File
@@ -5,6 +5,7 @@
#include <array> #include <array>
#include <cmath> #include <cmath>
#include <map> #include <map>
#include <format>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
@@ -692,9 +693,9 @@ TEST_CASE(rollFocus) {
// rotate the windows vector along with the actual windows // rotate the windows vector along with the actual windows
// the rolling behavior of the window focus should follow the // the rolling behavior of the window focus should follow the
// rotating behavior of std::ranges::rotate // 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()); 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) { 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 // focus a window by class and read its {left edge x, height} from /activewindow
auto geomOf = [&](const std::string& cls) -> std::pair<double, double> { auto geomOf = [&](const std::string& cls) -> std::pair<double, double> {
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 STR = getFromSocket("/activewindow");
const auto AT = Tests::getAttribute(STR, "at"); // "x,y" const auto AT = Tests::getAttribute(STR, "at"); // "x,y"
const auto SZ = Tests::getAttribute(STR, "size"); // "w,h" 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 // resizeactive-style relative resize of a specific window along y
auto resizeY = [&](const std::string& cls, int dy) { 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, // `top` and `bottom` share one column and must resize vertically (one grows, the other shrinks,
+4 -2
View File
@@ -3,6 +3,8 @@
#include "../../hyprctlCompat.hpp" #include "../../hyprctlCompat.hpp"
#include "tests.hpp" #include "tests.hpp"
#include <format>
#include <hyprutils/utils/ScopeGuard.hpp> #include <hyprutils/utils/ScopeGuard.hpp>
using namespace Hyprutils::Utils; using namespace Hyprutils::Utils;
@@ -26,7 +28,7 @@ static std::string getClientBlock(const std::string& clients, const std::string&
return NPOS; 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 // block by block till you find the class within a block
size_t blockStart = findNextBlockHeader(clients, 0); size_t blockStart = findNextBlockHeader(clients, 0);
@@ -56,7 +58,7 @@ static bool spawnLayer(const std::string& namespace_, const std::vector<std::str
// Taken from layers tests // Taken from layers tests
static std::string getLayerLine(const std::string& layers, const std::string& target) { static std::string getLayerLine(const std::string& layers, const std::string& target) {
auto pos = layers.find("namespace: " + target); auto pos = layers.find(std::format("namespace: {}", target));
if (pos == std::string::npos) if (pos == std::string::npos)
return ""; return "";
+8 -7
View File
@@ -2,6 +2,7 @@
#include <cmath> #include <cmath>
#include <chrono> #include <chrono>
#include <filesystem> #include <filesystem>
#include <format>
#include <thread> #include <thread>
#include <hyprutils/os/Process.hpp> #include <hyprutils/os/Process.hpp>
#include <hyprutils/memory/WeakPtr.hpp> #include <hyprutils/memory/WeakPtr.hpp>
@@ -32,7 +33,7 @@ static std::string spawnKittyActivating(const std::string& class_ = "kitty_activ
(void)close(fd); (void)close(fd);
const std::vector<std::string> args = { const std::vector<std::string> 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)) { if (!Tests::spawnKitty(class_, args)) {
NLog::red("Error: failed to spawn kitty"); NLog::red("Error: failed to spawn kitty");
@@ -71,7 +72,7 @@ TEST_CASE(swapWindow) {
// Test swapwindow by direction // Test swapwindow by direction
{ {
getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_A' })"); 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); NLog::log("{}Testing kitty_A {}, swapwindow with direction 'r'", Colors::YELLOW, pos);
OK(getFromSocket("/dispatch hl.dsp.window.swap({ direction = 'right' })")); OK(getFromSocket("/dispatch hl.dsp.window.swap({ direction = 'right' })"));
@@ -83,7 +84,7 @@ TEST_CASE(swapWindow) {
// Test swapwindow by class // Test swapwindow by class
{ {
getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_A' })"); 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); NLog::log("{}Testing kitty_A {}, swapwindow with class:kitty_B", Colors::YELLOW, pos);
OK(getFromSocket("/dispatch hl.dsp.window.swap({ target = 'class:kitty_B' })")); 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' })"); getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_B' })");
auto addr = getWindowAddress(getFromSocket("/activewindow")); auto addr = getWindowAddress(getFromSocket("/activewindow"));
getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_A' })"); 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); 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))); 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' })"); getFromSocket("/dispatch hl.dsp.focus({ window = 'class:kitty_B' })");
auto addr = getWindowAddress(getFromSocket("/activewindow")); 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); 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 })")); OK(getFromSocket("/dispatch hl.dsp.window.move({ workspace = 'name:swapwindow2', follow = false })"));
@@ -1356,7 +1357,7 @@ TEST_CASE(monitorrule) {
Tests::spawnKitty("monitor_kitty"); Tests::spawnKitty("monitor_kitty");
ASSERT(Tests::windowCount(), 1); ASSERT(Tests::windowCount(), 1);
const auto MON_SRC_ID = Tests::getAttribute(getFromSocket("/activewindow"), "monitor"); 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"); EXPECT_CONTAINS(getFromSocket("/activeworkspace"), "HEADLESS-3");
Tests::killAllWindows(); Tests::killAllWindows();
@@ -1368,7 +1369,7 @@ TEST_CASE(monitorrule) {
Tests::spawnKitty("silent_kitty"); Tests::spawnKitty("silent_kitty");
ASSERT(Tests::windowCount(), 1); ASSERT(Tests::windowCount(), 1);
const auto SILENT_SRC_ID = Tests::getAttribute(getFromSocket("/clients"), "monitor"); 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"); EXPECT_CONTAINS(getFromSocket("/activeworkspace"), "HEADLESS-2");
} }
+2 -1
View File
@@ -5,6 +5,7 @@
#include <thread> #include <thread>
#include <print> #include <print>
#include <fstream> #include <fstream>
#include <format>
#include "../shared.hpp" #include "../shared.hpp"
#include "../hyprctlCompat.hpp" #include "../hyprctlCompat.hpp"
@@ -104,7 +105,7 @@ bool Tests::killAllWindows() {
auto pos = str.find("Window "); auto pos = str.find("Window ");
while (pos != std::string::npos) { while (pos != std::string::npos) {
auto pos2 = str.find(" -> ", pos); 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); pos = str.find("Window ", pos + 5);
} }
+3 -3
View File
@@ -416,7 +416,7 @@ def query_struct_to_type(struct_name: str) -> str:
if name.startswith("S") and len(name) > 1: if name.startswith("S") and len(name) > 1:
name = name[1:] name = name[1:]
if name.endswith("Query"): if name.endswith("Query"):
name = name + "Filter" name = f"{name}Filter"
return f"HL.{name}" 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}") lines.append(f"---@field ['{quoted}'] {type_with_optional}")
if (emit_local_var): if (emit_local_var):
local_name = "__" + class_name.replace(".", "_") local_name = f"__{class_name.replace('.', '_')}"
lines.append(f"local {local_name} = {{}}") lines.append(f"local {local_name} = {{}}")
return lines return lines
@@ -783,7 +783,7 @@ def generate_stub(root: Path) -> str:
class_name = namespace_class_name(path) class_name = namespace_class_name(path)
fields: list[tuple[str, str, bool]] = [] 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): for method in sorted(node.methods):
full_name = f"{full_prefix}.{method}" full_name = f"{full_prefix}.{method}"
+6 -5
View File
@@ -191,7 +191,8 @@ CCompositor::CCompositor(bool onlyConfig) : m_onlyConfigVerification(onlyConfig)
setMallocThreshold(); 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")) { if (m_hyprTempDataRoot.starts_with("/hypr")) {
std::println("Bailing out, $XDG_RUNTIME_DIR is invalid"); 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"); 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)) { if (std::filesystem::exists(m_instancePath)) {
std::println("Bailing out, {} exists??", m_instancePath); std::println("Bailing out, {} exists??", m_instancePath);
@@ -393,7 +394,7 @@ void CCompositor::initServer(std::string socketName, int socketFd) {
} else { } else {
// get socket, avoid using 0 // get socket, avoid using 0
for (int candidate = 1; candidate <= 32; candidate++) { 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()); const auto RETVAL = wl_display_add_socket(m_wlDisplay, CANDIDATESTR.c_str());
if (RETVAL >= 0) { if (RETVAL >= 0) {
m_wlDisplaySocket = CANDIDATESTR; m_wlDisplaySocket = CANDIDATESTR;
@@ -764,7 +765,7 @@ void CCompositor::initManagers(eManagersInitStage stage) {
} }
void CCompositor::createLockFile() { 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); std::ofstream ofs(PATH, std::ios::trunc);
@@ -774,7 +775,7 @@ void CCompositor::createLockFile() {
} }
void CCompositor::removeLockFile() { void CCompositor::removeLockFile() {
const auto PATH = m_instancePath + "/hyprland.lock"; const auto PATH = std::format("{}/hyprland.lock", m_instancePath);
if (std::filesystem::exists(PATH)) if (std::filesystem::exists(PATH))
std::filesystem::remove(PATH); std::filesystem::remove(PATH);
+11 -10
View File
@@ -97,7 +97,7 @@ static std::optional<std::string> resolveExplicitLuaRequireFile(CConfigManager*
candidates.emplace_back(BASE); candidates.emplace_back(BASE);
if (!BASE.ends_with(".lua")) 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()); 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"); lua_setfield(m_lua, LUA_REGISTRYINDEX, "hl_lua_manager");
std::filesystem::path configDir = std::filesystem::path(m_mainConfigPath).parent_path(); 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_getglobal(m_lua, "package");
lua_getfield(m_lua, -1, "path"); lua_getfield(m_lua, -1, "path");
std::string combinedLuaPath = luaPath; std::string combinedLuaPath = luaPath;
@@ -788,7 +788,7 @@ void CConfigManager::postConfigReload() {
errorStr += "Your config has errors:\n"; errorStr += "Your config has errors:\n";
for (const auto& e : m_errors) { for (const auto& e : m_errors) {
errorStr += e + "\n"; errorStr += std::format("{}\n", e);
if (std::ranges::count(errorStr, '\n') > 15) { if (std::ranges::count(errorStr, '\n') > 15) {
errorStr += "... more"; errorStr += "... more";
@@ -802,8 +802,9 @@ void CConfigManager::postConfigReload() {
ErrorOverlay::overlay()->queueCreate(errorStr, ErrorOverlay::Colors::ERROR); ErrorOverlay::overlay()->queueCreate(errorStr, ErrorOverlay::Colors::ERROR);
} else if (*PAUTOGENERATED) } else if (*PAUTOGENERATED)
ErrorOverlay::overlay()->queueCreate( ErrorOverlay::overlay()->queueCreate(
"Warning: You're using an autogenerated config! Edit the config file to get rid of this message. (config file: " + getMainConfigPath() + 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 "
" )\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", "launch, make sure it's installed or choose a different terminal in the config)\nSUPER+M -> exit Hyprland",
getMainConfigPath()),
ErrorOverlay::Colors::WARNING); ErrorOverlay::Colors::WARNING);
else else
ErrorOverlay::overlay()->destroy(); ErrorOverlay::overlay()->destroy();
@@ -1058,7 +1059,7 @@ std::string CConfigManager::getMainConfigPath() {
std::string CConfigManager::getErrors() { std::string CConfigManager::getErrors() {
std::string errStr; std::string errStr;
for (const auto& e : m_errors) { for (const auto& e : m_errors) {
errStr += e + "\n"; errStr += std::format("{}\n", e);
} }
if (!errStr.empty()) if (!errStr.empty())
@@ -1289,8 +1290,8 @@ std::expected<void, std::string> CConfigManager::registerPluginLuaFunction(void*
if (namespace_ == "load") if (namespace_ == "load")
return std::unexpected("namespace 'load' is reserved"); return std::unexpected("namespace 'load' is reserved");
const auto key = namespace_ + "." + name; const auto key = std::format("{}.{}", namespace_, name);
if (std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return r.namespace_ + "." + r.name == key; }) != m_pluginLuaFunctions.end()) 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"); return std::unexpected("name collision: already registered");
const uint64_t id = nextPluginLuaFnID++; const uint64_t id = nextPluginLuaFnID++;
@@ -1306,8 +1307,8 @@ std::expected<void, std::string> CConfigManager::unregisterPluginLuaFunction(voi
if (!handle) if (!handle)
return std::unexpected("invalid handle"); return std::unexpected("invalid handle");
const auto key = namespace_ + "." + name; const auto key = std::format("{}.{}", namespace_, name);
auto it = std::ranges::find_if(m_pluginLuaFunctions, [&key](const SPluginLuaFunction& r) { return r.namespace_ + "." + r.name == key; }); 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()) if (it == m_pluginLuaFunctions.end())
return std::unexpected("no such function"); return std::unexpected("no such function");
@@ -447,7 +447,7 @@ static int hlAnimation(lua_State* L) {
if (!Animation::mgr()->springExists(springName)) if (!Animation::mgr()->springExists(springName))
return Internal::configError(L, std::format(R"(hl.animation("{}"): no such spring "{}")", leaf, springName)); return Internal::configError(L, std::format(R"(hl.animation("{}"): no such spring "{}")", leaf, springName));
curveName = "spring:" + springName; curveName = std::format("spring:{}", springName);
} else } else
return Internal::configError(L, std::format(R"(hl.animation("{}"): bezier or spring is required)", leaf)); 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) { if (dbus) {
std::string CMD; std::string CMD;
#ifdef USES_SYSTEMD #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 #endif
CMD += "dbus-update-activation-environment --systemd '" + name + "'"; CMD += std::format("dbus-update-activation-environment --systemd '{}'", name);
if (mgr->isFirstLaunch()) if (mgr->isFirstLaunch())
Config::Supplementary::executor()->addExecOnce({CMD, false}); Config::Supplementary::executor()->addExecOnce({CMD, false});
else else
@@ -693,7 +693,7 @@ static int dsp_mouseResize(lua_State* L) {
if (!keepAspectRatio) if (!keepAspectRatio)
return Internal::configError(L, std::format("resize: bad argument 1: {}", keepAspectRatio.error())); 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) { static int hlWindowClose(lua_State* L) {
@@ -1206,7 +1206,7 @@ static int hlNoop(lua_State* L) {
static int dsp_toggleSpecial(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)); 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)) if (workspaceID == WORKSPACE_INVALID || !State::workspaceState()->isSpecial(workspaceID))
return Internal::dispatcherError(L, "Invalid special workspace", ERR, C_INVARG); return Internal::dispatcherError(L, "Invalid special workspace", ERR, C_INVARG);
@@ -390,7 +390,7 @@ static int hlOn(lua_State* L) {
const auto& known = CLuaEventHandler::knownEvents(); const auto& known = CLuaEventHandler::knownEvents();
std::string list; std::string list;
for (const auto& e : known) { for (const auto& e : known) {
list += e + ", "; list += std::format("{}, ", e);
} }
list.pop_back(); list.pop_back();
list.pop_back(); list.pop_back();
+1 -1
View File
@@ -21,7 +21,7 @@ using namespace Config::Lua::Layouts;
static std::string normalizeLuaLayoutName(std::string name) { static std::string normalizeLuaLayoutName(std::string name) {
if (!name.starts_with("lua:")) if (!name.starts_with("lua:"))
name = "lua:" + name; name = std::format("lua:{}", name);
return name; return name;
} }
+1 -1
View File
@@ -36,7 +36,7 @@ SParseError CLuaConfigInt::parse(lua_State* s) {
for (const auto& [k, _] : *m_map) { for (const auto& [k, _] : *m_map) {
if (!keys.empty()) if (!keys.empty())
keys += ", "; keys += ", ";
keys += "\"" + k + "\""; keys += std::format("\"{}\"", k);
} }
return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = std::format("unknown string value \"{}\", acceptable values are: {}", str, keys)}; return {.errorCode = PARSE_ERROR_BAD_VALUE, .message = std::format("unknown string value \"{}\", acceptable values are: {}", str, keys)};
} }
+3 -1
View File
@@ -7,6 +7,7 @@
#include <hyprutils/string/String.hpp> #include <hyprutils/string/String.hpp>
#include <string> #include <string>
#include <algorithm> #include <algorithm>
#include <format>
using namespace Config; using namespace Config;
using namespace Hyprutils::String; 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); 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; return true;
} }
+3 -3
View File
@@ -114,7 +114,7 @@ std::string CWorkspace::getConfigName() {
if (m_id > 0) if (m_id > 0)
return std::to_string(m_id); return std::to_string(m_id);
return "name:" + m_name; return std::format("name:{}", m_name);
} }
bool CWorkspace::matchesStaticSelector(const std::string& selector_) { bool CWorkspace::matchesStaticSelector(const std::string& selector_) {
@@ -540,7 +540,7 @@ void CWorkspace::rename(const std::string& name) {
m_wasRenamed = true; 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(); m_events.renamed.emit();
} }
@@ -557,7 +557,7 @@ void CWorkspace::changeID(int64_t id) {
Config::Supplementary::refresher()->scheduleRefresh(Config::Supplementary::REFRESH_ALL); 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(); m_events.idChanged.emit();
} }
+3 -3
View File
@@ -206,7 +206,7 @@ void CFocusState::rawWindowFocus(PHLWINDOW pWindow, eFocusReason reason, SP<CWLS
pWindow->m_isUrgent = false; pWindow->m_isUrgent = false;
// Send an event // 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<uintptr_t>(pWindow.get()))}); IPC::Socket2::sock()->postEvent({.event = "activewindowv2", .data = std::format("{:x}", rc<uintptr_t>(pWindow.get()))});
Event::bus()->m_events.window.active.emit(pWindow, reason); 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_ID = PWORKSPACE ? std::to_string(PWORKSPACE->m_id) : std::to_string(WORKSPACE_INVALID);
const auto WORKSPACE_NAME = PWORKSPACE ? PWORKSPACE->m_name : "?"; 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 = "focusedmon", .data = std::format("{},{}", pMonitor->m_name, WORKSPACE_NAME)});
IPC::Socket2::sock()->postEvent({.event = "focusedmonv2", .data = pMonitor->m_name + "," + WORKSPACE_ID}); IPC::Socket2::sock()->postEvent({.event = "focusedmonv2", .data = std::format("{},{}", pMonitor->m_name, WORKSPACE_ID)});
Event::bus()->m_events.monitor.focused.emit(pMonitor); Event::bus()->m_events.monitor.focused.emit(pMonitor);
m_focusMonitor = pMonitor; m_focusMonitor = pMonitor;
+4 -4
View File
@@ -1344,7 +1344,7 @@ std::unordered_map<std::string, std::string> CWindow::getEnv() {
#if defined(__linux__) #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); std::ifstream ifs(environFile, std::ios::binary);
if (!ifs.good()) if (!ifs.good())
@@ -1484,7 +1484,7 @@ void CWindow::onUpdateMeta() {
Event::bus()->m_events.window.title.emit(m_self.lock()); 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 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<uintptr_t>(this))}); IPC::Socket2::sock()->postEvent({.event = "activewindowv2", .data = std::format("{:x}", rc<uintptr_t>(this))});
// no need for a hook event // no need for a hook event
@@ -1501,7 +1501,7 @@ void CWindow::onUpdateMeta() {
Event::bus()->m_events.window.class_.emit(m_self.lock()); 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 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<uintptr_t>(this))}); IPC::Socket2::sock()->postEvent({.event = "activewindowv2", .data = std::format("{:x}", rc<uintptr_t>(this))});
// no need for a hook event // 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; 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 = ""; requestedWorkspace = "";
Log::logger->log(Log::DEBUG, "Rule workspace matched by {}, {} applied.", m_self.lock(), m_ruleApplicator->static_.workspace); Log::logger->log(Log::DEBUG, "Rule workspace matched by {}, {} applied.", m_self.lock(), m_ruleApplicator->static_.workspace);
+2 -2
View File
@@ -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); m_xkbKeymap = xkb_keymap_new_from_names2(CONTEXT, &XKBRULES, XKB_KEYMAP_FORMAT_TEXT_V2, XKB_KEYMAP_COMPILE_NO_FLAGS);
if (!m_xkbKeymap) { if (!m_xkbKeymap) {
ErrorOverlay::overlay()->queueError("Invalid keyboard layout passed. ( rules: " + rules.rules + ", model: " + rules.model + ", variant: " + rules.variant + ErrorOverlay::overlay()->queueError(std::format("Invalid keyboard layout passed. ( rules: {}, model: {}, variant: {}, options: {}, layout: {} )", rules.rules, rules.model,
", options: " + rules.options + ", layout: " + rules.layout + " )"); 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, 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); rules.model, rules.options);
+1 -1
View File
@@ -92,7 +92,7 @@ void COverlay::queueCreate(std::string message, const Config::CGradientValueData
} }
void COverlay::queueError(std::string err) { 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() { void COverlay::createQueued() {
+1 -1
View File
@@ -95,7 +95,7 @@ void CAsyncDialogBox::onWrite(int fd, uint32_t mask) {
SP<CPromise<std::string>> CAsyncDialogBox::open() { SP<CPromise<std::string>> CAsyncDialogBox::open() {
std::string buttonsString = ""; std::string buttonsString = "";
for (auto& b : m_buttons) { for (auto& b : m_buttons) {
buttonsString += b + ";"; buttonsString += std::format("{};", b);
} }
if (!buttonsString.empty()) if (!buttonsString.empty())
buttonsString.pop_back(); buttonsString.pop_back();
+9 -9
View File
@@ -130,9 +130,9 @@ SWorkspaceIDName getWorkspaceIDNameFromString(const std::string& in) {
if (in.length() > 8) { if (in.length() > 8) {
const auto NAME = in.substr(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; result.id = SPECIAL_WORKSPACE_START;
@@ -481,7 +481,7 @@ std::optional<std::string> cleanCmdForWorkspace(const std::string& inWorkspaceNa
if (!cmd.empty()) { if (!cmd.empty()) {
std::string rules; std::string rules;
const std::string workspaceRule = "workspace " + inWorkspaceName; const std::string workspaceRule = std::format("workspace {}", inWorkspaceName);
if (cmd[0] == '[') { if (cmd[0] == '[') {
const auto closingBracketIdx = cmd.find_last_of(']'); const auto closingBracketIdx = cmd.find_last_of(']');
@@ -501,12 +501,12 @@ std::optional<std::string> cleanCmdForWorkspace(const std::string& inWorkspaceNa
if (!hadWorkspaceRule) if (!hadWorkspaceRule)
rulesList.append(workspaceRule); rulesList.append(workspaceRule);
rules = "[" + rulesList.join(";") + "]"; rules = std::format("[{}]", rulesList.join(";"));
} else { } else {
rules = "[" + workspaceRule + "]"; rules = std::format("[{}]", workspaceRule);
} }
return std::optional<std::string>(rules + " " + cmd); return std::optional<std::string>(std::format("{} {}", rules, cmd));
} }
return std::nullopt; return std::nullopt;
@@ -544,7 +544,7 @@ int64_t getPPIDof(int64_t pid) {
return 0; return 0;
#else #else
std::string dir = "/proc/" + std::to_string(pid) + "/status"; std::string dir = std::format("/proc/{}/status", pid);
FILE* infile; FILE* infile;
infile = fopen(dir.c_str(), "r"); infile = fopen(dir.c_str(), "r");
@@ -623,7 +623,7 @@ void throwError(const std::string& err) {
std::pair<CFileDescriptor, std::string> openExclusiveShm() { std::pair<CFileDescriptor, std::string> openExclusiveShm() {
// Only absolute paths can be shared across different shm_open() calls // 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) { for (size_t i = 0; i < 69; ++i) {
CFileDescriptor fd{shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600)}; CFileDescriptor fd{shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600)};
@@ -794,7 +794,7 @@ static const std::vector<const char*> PKGCONF_PATHS = {"/usr/lib/pkgconfig", "/u
std::string getSystemLibraryVersion(const std::string& name) { std::string getSystemLibraryVersion(const std::string& name) {
for (const auto& pkgconf : PKGCONF_PATHS) { for (const auto& pkgconf : PKGCONF_PATHS) {
std::error_code ec; 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)) if (!std::filesystem::exists(PATH, ec))
continue; continue;
+6 -6
View File
@@ -165,10 +165,10 @@ std::string SystemInfo::getSystemInfo() {
uname(&unameInfo); uname(&unameInfo);
result += "System name: " + std::string{unameInfo.sysname} + "\n"; result += std::format("System name: {}\n", unameInfo.sysname);
result += "Node name: " + std::string{unameInfo.nodename} + "\n"; result += std::format("Node name: {}\n", unameInfo.nodename);
result += "Release: " + std::string{unameInfo.release} + "\n"; result += std::format("Release: {}\n", unameInfo.release);
result += "Version: " + std::string{unameInfo.version} + "\n"; result += std::format("Version: {}\n", unameInfo.version);
result += "\n"; result += "\n";
result += getBuiltSystemLibraryNames(); result += getBuiltSystemLibraryNames();
result += "\n"; result += "\n";
@@ -199,7 +199,7 @@ std::string SystemInfo::getSystemInfo() {
#else #else
const std::string GPUINFO = execAndGet("lspci -vnn | grep -E '(VGA|Display|3D)'"); const std::string GPUINFO = execAndGet("lspci -vnn | grep -E '(VGA|Display|3D)'");
#endif #endif
result += "GPU information: \n" + GPUINFO; result += std::format("GPU information: \n{}", GPUINFO);
if (GPUINFO.contains("NVIDIA") && std::filesystem::exists("/proc/driver/nvidia/version")) { if (GPUINFO.contains("NVIDIA") && std::filesystem::exists("/proc/driver/nvidia/version")) {
std::ifstream file("/proc/driver/nvidia/version"); std::ifstream file("/proc/driver/nvidia/version");
std::string line; std::string line;
@@ -218,7 +218,7 @@ std::string SystemInfo::getSystemInfo() {
if (std::ifstream file("/etc/os-release"); file.is_open()) { if (std::ifstream file("/etc/os-release"); file.is_open()) {
std::stringstream buffer; std::stringstream buffer;
buffer << file.rdbuf(); buffer << file.rdbuf();
result += "os-release: " + buffer.str() + "\n\n"; result += std::format("os-release: {}\n\n", buffer.str());
} else } else
result += "os-release: error\n\n"; result += "os-release: error\n\n";
+4 -2
View File
@@ -1,9 +1,11 @@
#include "TagKeeper.hpp" #include "TagKeeper.hpp"
#include <format>
bool CTagKeeper::isTagged(const std::string& tag, bool strict) const { bool CTagKeeper::isTagged(const std::string& tag, bool strict) const {
const bool NEGATIVE = tag.starts_with("negative"); const bool NEGATIVE = tag.starts_with("negative");
const auto MATCH = NEGATIVE ? tag.substr(9) : tag; 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; return NEGATIVE ? !TAGGED : TAGGED;
} }
@@ -48,5 +50,5 @@ bool CTagKeeper::clearTags() {
} }
bool CTagKeeper::removeDynamicTag(const std::string& s) { 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); });
} }
+12 -12
View File
@@ -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<const char*, Monitor::CMonitor::DS_CHECKS_COUNT> DS_REASONS_JSON = { const std::array<const char*, Monitor::CMonitor::DS_CHECKS_COUNT> 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<const char*, Monitor::CMonitor::TC_CHECKS_COUNT> TEARING_REASONS_JSON = { const std::array<const char*, Monitor::CMonitor::TC_CHECKS_COUNT> 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) { 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(), 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); }); [](const std::string& a, const std::string& b) { return a.empty() ? std::format("\"{}\"", b) : std::format("{}, \"{}\"", a, b); });
else 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) { static std::string getGroupedData(PHLWINDOW w, eHyprCtlOutputFormat format) {
@@ -992,7 +992,7 @@ static std::string globalShortcutsRequest(eHyprCtlOutputFormat format, std::stri
"name": "{}", "name": "{}",
"description": "{}" "description": "{}"
}},)#", }},)#",
escapeJSONStrings(sh.appid + ":" + sh.id), escapeJSONStrings(sh.description)); escapeJSONStrings(std::format("{}:{}", sh.appid, sh.id)), escapeJSONStrings(sh.description));
} }
trimTrailingComma(ret); trimTrailingComma(ret);
ret += "]\n"; ret += "]\n";
@@ -1150,7 +1150,7 @@ static std::string dispatchRequest(eHyprCtlOutputFormat format, std::string in)
return ret; return ret;
// the user likely is trying to dispatch old hyprlang stuff via lua, let them know // 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"; 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]; const auto SIZESTR = vars[vars.size() - 1];
std::string theme = ""; std::string theme = "";
for (size_t i = 1; i < vars.size() - 1; ++i) for (size_t i = 1; i < vars.size() - 1; ++i)
theme += vars[i] + " "; theme += std::format("{} ", vars[i]);
if (!theme.empty()) if (!theme.empty())
theme.pop_back(); theme.pop_back();
@@ -1259,7 +1259,7 @@ static std::string switchXKBLayoutRequest(eHyprCtlOutputFormat format, std::stri
} catch (std::exception& e) { return "invalid arg 2"; } } catch (std::exception& e) { return "invalid arg 2"; }
if (requestedLayout < 0 || sc<uint64_t>(requestedLayout) > LAYOUTS - 1) { if (requestedLayout < 0 || sc<uint64_t>(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); 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) { for (auto const& k : g_pInputManager->m_keyboards) {
auto res = updateKeyboard(k, CMD); auto res = updateKeyboard(k, CMD);
if (res.has_value()) if (res.has_value())
result += *res + "\n"; result += std::format("{}\n", *res);
} }
return result.empty() ? "ok" : result; return result.empty() ? "ok" : result;
} else { } else {
@@ -1615,7 +1615,7 @@ static std::string decorationRequest(eHyprCtlOutputFormat format, std::string re
if (format == eHyprCtlOutputFormat::FORMAT_JSON) { if (format == eHyprCtlOutputFormat::FORMAT_JSON) {
result += "["; result += "[";
for (auto const& wd : PWINDOW->m_windowDecorations) { 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); trimTrailingComma(result);
@@ -1623,7 +1623,7 @@ static std::string decorationRequest(eHyprCtlOutputFormat format, std::string re
} else { } else {
result = +"Decoration\tPriority\n"; result = +"Decoration\tPriority\n";
for (auto const& wd : PWINDOW->m_windowDecorations) { 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()) if (submap.empty())
submap = "default"; 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) { static std::string reloadShaders(eHyprCtlOutputFormat format, std::string request) {
+1 -1
View File
@@ -210,7 +210,7 @@ SResponse CSocket1::dispatch(std::string request, pid_t pid) {
return dispatchSingle(std::move(request), pid); return dispatchSingle(std::move(request), pid);
} catch (const std::exception& error) { } catch (const std::exception& error) {
Log::logger->log(Log::ERR, "Error in socket1 request: {}", error.what()); Log::logger->log(Log::ERR, "Error in socket1 request: {}", error.what());
return "Err: " + std::string{error.what()}; return std::format("Err: {}", error.what());
} }
} }
+1 -1
View File
@@ -239,7 +239,7 @@ void CUnixImpl::start(FRequestHandler&& handler) {
} }
sockaddr_un address = {.sun_family = AF_UNIX}; 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) { if (m_socketPath.size() > sizeof(address.sun_path) - 1) {
Log::logger->log(Log::ERR, "[Socket1::Unix] socket path is too long"); Log::logger->log(Log::ERR, "[Socket1::Unix] socket path is too long");
+1 -1
View File
@@ -90,7 +90,7 @@ CUnixImpl::CUnixImpl() : m_socket(socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | S
} }
sockaddr_un SERVERADDRESS = {.sun_family = AF_UNIX}; 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) { if (PATH.length() > sizeof(SERVERADDRESS.sun_path) - 1) {
Log::logger->log(Log::ERR, "[Socket2::UnixImpl] path is too long. (2) IPC will not work."); Log::logger->log(Log::ERR, "[Socket2::UnixImpl] path is too long. (2) IPC will not work.");
return; return;
+2 -2
View File
@@ -136,7 +136,7 @@ void CDonationNagManager::fire() {
CDonationNagManager::SStateData CDonationNagManager::getState() { CDonationNagManager::SStateData CDonationNagManager::getState() {
static const auto DATAROOT = NFsUtils::getDataHome(); 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()) if (!STR.has_value())
return {}; return {};
@@ -154,5 +154,5 @@ CDonationNagManager::SStateData CDonationNagManager::getState() {
void CDonationNagManager::writeState(const SStateData& s) { void CDonationNagManager::writeState(const SStateData& s) {
static const auto DATAROOT = NFsUtils::getDataHome(); 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));
} }
+7 -7
View File
@@ -238,9 +238,9 @@ void CKeybindManager::updateXKBTranslationState() {
fclose(KEYMAPFILE); fclose(KEYMAPFILE);
if (!PKEYMAP) { if (!PKEYMAP) {
ErrorOverlay::overlay()->queueCreate("[Runtime Error] Invalid keyboard layout passed. ( rules: " + RULES + ", model: " + MODEL + ", variant: " + VARIANT + ErrorOverlay::overlay()->queueCreate(
", options: " + OPTIONS + ", layout: " + LAYOUT + " )", std::format("[Runtime Error] Invalid keyboard layout passed. ( rules: {}, model: {}, variant: {}, options: {}, layout: {} )", RULES, MODEL, VARIANT, OPTIONS, LAYOUT),
ErrorOverlay::Colors::ERROR); ErrorOverlay::Colors::ERROR);
Log::logger->log(Log::ERR, "[XKBTranslationState] Keyboard layout {} with variant {} (rules: {}, model: {}, options: {}) couldn't have been loaded.", rules.layout, 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); rules.variant, rules.rules, rules.model, rules.options);
@@ -406,7 +406,7 @@ bool CKeybindManager::onMouseEvent(const IPointer::SButtonEvent& e, SP<IPointer>
bool mouseBindWasActive = ensureMouseBindState(); 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{ const auto KEY = SPressedKeyWithMods{
.keyName = KEY_NAME, .keyName = KEY_NAME,
@@ -455,15 +455,15 @@ void CKeybindManager::resizeWithBorder(const IPointer::SButtonEvent& e) {
} }
void CKeybindManager::onSwitchEvent(const std::string& switchName) { 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) { 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) { 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<KeybindKey>& keybindKeysyms, const std::set<KeybindKey>& pressedKeysyms) { eMultiKeyCase CKeybindManager::mkKeysymSetMatches(const std::vector<KeybindKey>& keybindKeysyms, const std::set<KeybindKey>& pressedKeysyms) {
+3 -3
View File
@@ -27,10 +27,10 @@ CVersionKeeperManager::CVersionKeeperManager() {
if (!DATAROOT) if (!DATAROOT)
return; return;
auto LASTVER = NFsUtils::readFileAsString(*DATAROOT + "/" + VERSION_FILE_NAME); auto LASTVER = NFsUtils::readFileAsString(std::format("{}/{}", *DATAROOT, VERSION_FILE_NAME));
if (!LASTVER) { 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"; LASTVER = "0.0.0";
return; return;
} }
@@ -40,7 +40,7 @@ CVersionKeeperManager::CVersionKeeperManager() {
return; return;
} }
NFsUtils::writeToFile(*DATAROOT + "/" + VERSION_FILE_NAME, HYPRLAND_VERSION); NFsUtils::writeToFile(std::format("{}/{}", *DATAROOT, VERSION_FILE_NAME), HYPRLAND_VERSION);
if (*PNONOTIFY) { if (*PNONOTIFY) {
Log::logger->log(Log::DEBUG, "CVersionKeeperManager: updated, but update news is disabled in the config :("); Log::logger->log(Log::DEBUG, "CVersionKeeperManager: updated, but update news is disabled in the config :(");
+2 -2
View File
@@ -294,13 +294,13 @@ std::set<std::string> CXCursorManager::themePaths(std::string const& theme) {
Log::logger->log(Log::DEBUG, "XCursor scanning theme {}", t); Log::logger->log(Log::DEBUG, "XCursor scanning theme {}", t);
while (std::getline(ss, line, ':')) { 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)) { if (std::filesystem::exists(p) && std::filesystem::is_directory(p)) {
Log::logger->log(Log::DEBUG, "XCursor using theme path {}", p); Log::logger->log(Log::DEBUG, "XCursor using theme path {}", p);
paths.insert(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)) { if (std::filesystem::exists(inherit) && std::filesystem::is_regular_file(inherit)) {
auto inheritThemes = getInheritThemes(inherit); auto inheritThemes = getInheritThemes(inherit);
for (auto const& i : inheritThemes) { for (auto const& i : inheritThemes) {
+1 -1
View File
@@ -24,7 +24,7 @@ CEis::CEis(std::string socketName) {
const char* xdg = getenv("XDG_RUNTIME_DIR"); const char* xdg = getenv("XDG_RUNTIME_DIR");
if (xdg) if (xdg)
m_socketPath = std::string(xdg) + "/" + socketName; m_socketPath = std::format("{}/{}", xdg, socketName);
if (m_socketPath.empty()) { if (m_socketPath.empty()) {
Log::logger->log(Log::ERR, "[EIS] Socket path is empty"); Log::logger->log(Log::ERR, "[EIS] Socket path is empty");
+6 -4
View File
@@ -1183,7 +1183,7 @@ void CInputManager::setupKeyboard(SP<IKeyboard> keeb) {
g_pKeybindManager->m_keyToCodeCache.clear(); 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); Event::bus()->m_events.input.keyboard.layout.emit(PKEEB, LAYOUT);
}); });
@@ -1284,7 +1284,7 @@ void CInputManager::applyConfigToKeyboard(SP<IKeyboard> pKeyboard) {
const auto LAYOUTSTR = pKeyboard->getActiveLayout(); 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); 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, 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<IKeyboard> pKeyboard) {
Log::logger->log(Log::DEBUG, "LAYOUT CHANGED TO {} GROUP {}", LAYOUT, MODS.group); 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); 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); auto proposedNewName = deviceNameToInternalString(internalName);
int dupeno = 0; 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()) while (std::ranges::find_if(m_hids, [&](const auto& other) { return other->m_hlName == makeNewName(); }) != m_hids.end())
dupeno++; dupeno++;
@@ -31,7 +31,7 @@ void CSpecialWorkspaceGesture::begin(const ITrackpadGesture::STrackpadGestureBeg
m_lastDelta = 0.F; m_lastDelta = 0.F;
m_monitor.reset(); 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) { if (m_specialWorkspace) {
m_animatingOut = m_specialWorkspace->isVisible(); m_animatingOut = m_specialWorkspace->isVisible();
@@ -50,7 +50,7 @@ void CSpecialWorkspaceGesture::begin(const ITrackpadGesture::STrackpadGestureBeg
m_animatingOut = false; 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); const auto WS = State::workspaceState()->create(workspaceID, m_monitor->m_id, workspaceName);
m_monitor->setSpecialWorkspace(WS); m_monitor->setSpecialWorkspace(WS);
m_specialWorkspace = WS; m_specialWorkspace = WS;
@@ -85,7 +85,7 @@ eDynamicPermissionAllowMode CDynamicPermissionManager::clientPermissionMode(wl_c
const auto LOOKUP = binaryNameForWlClient(client); const auto LOOKUP = binaryNameForWlClient(client);
Log::logger->log(Log::TRACE, "CDynamicPermissionManager::clientHasPermission: checking permission {} for client {:x} (binary {})", permissionToString(permission), Log::logger->log(Log::TRACE, "CDynamicPermissionManager::clientHasPermission: checking permission {} for client {:x} (binary {})", permissionToString(permission),
rc<uintptr_t>(client), LOOKUP.has_value() ? LOOKUP.value() : "lookup failed: " + LOOKUP.error()); rc<uintptr_t>(client), LOOKUP.has_value() ? LOOKUP.value() : std::format("lookup failed: {}", LOOKUP.error()));
// first, check if we have the client + perm combo in our cache. // 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; }); 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); lookup = binaryNameForPid(pid);
Log::logger->log(Log::TRACE, "CDynamicPermissionManager::clientHasPermission: checking permission {} for key {} (binary {})", permissionToString(permission), str, 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()) if (lookup.has_value())
binaryName = *lookup; binaryName = *lookup;
+7 -7
View File
@@ -1032,7 +1032,7 @@ bool CMonitor::applyMonitorRule(Config::CMonitorRule&& pMonitorRule) {
m_scale = std::round(scaleZero); m_scale = std::round(scaleZero);
else { else {
Log::logger->log(Log::ERR, "Invalid scale passed to monitor, {} failed to find a clean divisor", m_scale); 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(); m_scale = getDefaultScale();
} }
} else { } else {
@@ -1565,8 +1565,8 @@ void CMonitor::setSpecialWorkspace(const PHLWORKSPACE& pWorkspace) {
if (m_activeSpecialWorkspace) { if (m_activeSpecialWorkspace) {
m_activeSpecialWorkspace->m_visible = false; m_activeSpecialWorkspace->m_visible = false;
Animation::Workspace::startAnimation(m_activeSpecialWorkspace, Animation::Workspace::ANIMATION_TYPE_OUT, false); Animation::Workspace::startAnimation(m_activeSpecialWorkspace, Animation::Workspace::ANIMATION_TYPE_OUT, false);
IPC::Socket2::sock()->postEvent({"activespecial", "," + m_name}); IPC::Socket2::sock()->postEvent({"activespecial", std::format(",{}", m_name)});
IPC::Socket2::sock()->postEvent({"activespecialv2", ",," + m_name}); IPC::Socket2::sock()->postEvent({"activespecialv2", std::format(",,{}", m_name)});
// Reset layer surface state when closing special workspace // Reset layer surface state when closing special workspace
for (auto const& ls : Desktop::layerState()->layers()) { for (auto const& ls : Desktop::layerState()->layers()) {
@@ -1614,8 +1614,8 @@ void CMonitor::setSpecialWorkspace(const PHLWORKSPACE& pWorkspace) {
PMONITOR->m_activeSpecialWorkspace.reset(); PMONITOR->m_activeSpecialWorkspace.reset();
g_layoutManager->recalculateMonitor(PMONITOR, Layout::CLayoutManager::RECALCULATE_MONITOR_REASON_TOGGLE_SPECIAL_WORKSPACE); g_layoutManager->recalculateMonitor(PMONITOR, Layout::CLayoutManager::RECALCULATE_MONITOR_REASON_TOGGLE_SPECIAL_WORKSPACE);
g_pHyprRenderer->damageMonitor(PMONITOR); g_pHyprRenderer->damageMonitor(PMONITOR);
IPC::Socket2::sock()->postEvent({"activespecial", "," + PMONITOR->m_name}); IPC::Socket2::sock()->postEvent({"activespecial", std::format(",{}", PMONITOR->m_name)});
IPC::Socket2::sock()->postEvent({"activespecialv2", ",," + 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 // Reset layer surfaces on the old monitor when special workspace is stolen
for (auto const& ls : Desktop::layerState()->layers()) { for (auto const& ls : Desktop::layerState()->layers()) {
@@ -1686,8 +1686,8 @@ void CMonitor::setSpecialWorkspace(const PHLWORKSPACE& pWorkspace) {
g_pInputManager->refocus(); g_pInputManager->refocus();
} }
IPC::Socket2::sock()->postEvent({"activespecial", pWorkspace->m_name + "," + m_name}); IPC::Socket2::sock()->postEvent({"activespecial", std::format("{},{}", 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({"activespecialv2", std::format("{},{},{}", pWorkspace->m_id, pWorkspace->m_name, m_name)});
g_pHyprRenderer->damageMonitor(m_self.lock()); g_pHyprRenderer->damageMonitor(m_self.lock());
+1 -1
View File
@@ -64,7 +64,7 @@ CFunctionHook::SInstructionProbe CFunctionHook::probeMinimumJumpSize(void* start
auto probe = getInstructionLenAt(sc<uint8_t*>(start) + size); auto probe = getInstructionLenAt(sc<uint8_t*>(start) + size);
sizes.push_back(probe.len); sizes.push_back(probe.len);
size += probe.len; size += probe.len;
instrs += probe.assembly + "\n"; instrs += std::format("{}\n", probe.assembly);
} }
return {size, instrs, sizes}; return {size, instrs, sizes};
+8 -8
View File
@@ -27,8 +27,8 @@ APICALL const char* __hyprland_api_get_hash() {
return std::string{v.substr(0, v.find_last_of('.'))}; 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_" + static const std::string ver = std::format("{}_aq_{}_hu_{}_hg_{}_hc_{}_hlg_{}", GIT_COMMIT_HASH, stripPatch(AQUAMARINE_VERSION), stripPatch(HYPRUTILS_VERSION),
stripPatch(HYPRGRAPHICS_VERSION) + "_hc_" + stripPatch(HYPRCURSOR_VERSION) + "_hlg_" + stripPatch(HYPRLANG_VERSION)); stripPatch(HYPRGRAPHICS_VERSION), stripPatch(HYPRCURSOR_VERSION), stripPatch(HYPRLANG_VERSION));
return ver.c_str(); return ver.c_str();
} }
@@ -58,9 +58,9 @@ APICALL bool HyprlandAPI::unregisterCallback(HANDLE handle, SP<HOOK_CALLBACK_FN>
APICALL std::string HyprlandAPI::invokeHyprctlCommand(const std::string& call, const std::string& args, const std::string& format) { APICALL std::string HyprlandAPI::invokeHyprctlCommand(const std::string& call, const std::string& args, const std::string& format) {
if (args.empty()) if (args.empty())
return IPC::Socket1::sock()->invoke(format + "/" + call); return IPC::Socket1::sock()->invoke(std::format("{}/{}", format, call));
else 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) { APICALL bool HyprlandAPI::addLayout(HANDLE handle, const std::string& name, IHyprLayout* layout) {
@@ -287,11 +287,11 @@ APICALL std::vector<SFunctionMatch> HyprlandAPI::findFunctionsByName(HANDLE hand
#endif #endif
#ifdef __clang__ #ifdef __clang__
static const auto SYMBOLS = execAndGet(("llvm-nm -D -j \"" + FPATH.string() + "\"").c_str()); static const auto SYMBOLS = execAndGet(std::format("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 SYMBOLSDEMANGLED = execAndGet(std::format("llvm-nm -D -j --demangle \"{}\"", FPATH.string()).c_str());
#else #else
static const auto SYMBOLS = execAndGet(("nm -D -j \"" + FPATH.string() + "\"").c_str()); static const auto SYMBOLS = execAndGet(std::format("nm -D -j \"{}\"", FPATH.string()).c_str());
static const auto SYMBOLSDEMANGLED = execAndGet(("nm -D -j --demangle=auto \"" + FPATH.string() + "\"").c_str()); static const auto SYMBOLSDEMANGLED = execAndGet(std::format("nm -D -j --demangle=auto \"{}\"", FPATH.string()).c_str());
#endif #endif
auto demangledFromID = [&](size_t id) -> std::string { auto demangledFromID = [&](size_t id) -> std::string {
+3 -2
View File
@@ -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 "../event/EventBus.hpp"
#include <any> #include <any>
#include <format>
#include <functional> #include <functional>
#include <string> #include <string>
#include <string_view> #include <string_view>
@@ -400,8 +401,8 @@ APICALL inline EXPORT const char* __hyprland_api_get_client_hash() {
return std::string{v.substr(0, v.find_last_of('.'))}; 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_" + static const std::string ver = std::format("{}_aq_{}_hu_{}_hg_{}_hc_{}_hlg_{}", GIT_COMMIT_HASH, stripPatch(AQUAMARINE_VERSION), stripPatch(HYPRUTILS_VERSION),
stripPatch(HYPRGRAPHICS_VERSION) + "_hc_" + stripPatch(HYPRCURSOR_VERSION) + "_hlg_" + stripPatch(HYPRLANG_VERSION)); stripPatch(HYPRGRAPHICS_VERSION), stripPatch(HYPRCURSOR_VERSION), stripPatch(HYPRLANG_VERSION));
return ver.c_str(); return ver.c_str();
} }
+1 -1
View File
@@ -36,7 +36,7 @@ static std::string keybindLabel(const SP<SKeybind>& k) {
if (!k->description.empty()) if (!k->description.empty())
return k->description; return k->description;
if (!k->arg.empty()) if (!k->arg.empty())
return k->handler + ", " + k->arg; return std::format("{}, {}", k->handler, k->arg);
return k->handler; return k->handler;
} }
+2 -2
View File
@@ -41,7 +41,7 @@ CInputCaptureResource::CInputCaptureResource(SP<CHyprlandInputCaptureV1> resourc
m_resource->setRelease([this](CHyprlandInputCaptureV1* r, uint32_t activationId, double x, double y) { onRelease(activationId, x, y); }); 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_resource->setClearBarriers([this](CHyprlandInputCaptureV1* r) { onClearBarriers(); });
m_eis = makeUnique<CEis>("eis-" + std::to_string(eisCounter++)); m_eis = makeUnique<CEis>(std::format("eis-{}", eisCounter++));
const int EISFD = m_eis->getFileDescriptor(); const int EISFD = m_eis->getFileDescriptor();
if (EISFD >= 0) 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); Log::logger->log(Log::INFO, "[input-capture]({}) Barrier {} is invalid [{}, {}], [{}, {}]", m_sessionId.c_str(), id, sx1, sy1, sx2, sy2);
if (*PENFORCEBARRIERS) { 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; return;
} }
} }
+1 -1
View File
@@ -927,7 +927,7 @@ void CHyprOpenGLImpl::applyScreenShader(const std::string& path) {
std::error_code ec; std::error_code ec;
if (!std::filesystem::is_regular_file(absPath, ec)) { if (!std::filesystem::is_regular_file(absPath, ec)) {
if (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 else
ErrorOverlay::overlay()->queueError("Screen shader parser: Screen shader path is not a regular file"); ErrorOverlay::overlay()->queueError("Screen shader parser: Screen shader path is not a regular file");
return; return;
+2 -3
View File
@@ -1477,7 +1477,7 @@ void IHyprRenderer::requestBackgroundResource() {
std::string IHyprRenderer::resolveAssetPath(const std::string& filename) { std::string IHyprRenderer::resolveAssetPath(const std::string& filename) {
std::string fullPath; std::string fullPath;
for (auto& e : ASSET_PATHS) { 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; std::error_code ec;
if (std::filesystem::exists(p, ec)) { if (std::filesystem::exists(p, ec)) {
fullPath = p; fullPath = p;
@@ -2996,8 +2996,7 @@ std::tuple<float, float, float> IHyprRenderer::getRenderTimes(PHLMONITOR pMonito
static int handleCrashLoop(void* data) { static int handleCrashLoop(void* data) {
Notification::overlay()->addNotification("Hyprland will crash in " + std::to_string(10 - sc<int>(g_pHyprRenderer->m_crashingDistort * 2.f)) + "s.", CHyprColor(0), 5000, Notification::overlay()->addNotification(std::format("Hyprland will crash in {}s.", 10 - sc<int>(g_pHyprRenderer->m_crashingDistort * 2.f)), CHyprColor(0), 5000, ICON_INFO);
ICON_INFO);
g_pHyprRenderer->m_crashingDistort += 0.5f; g_pHyprRenderer->m_crashingDistort += 0.5f;
+3 -3
View File
@@ -124,7 +124,7 @@ std::string CShaderLoader::processSource(const std::string& source, glslang_stag
while (std::getline(stream, line)) { while (std::getline(stream, line)) {
if (!line.starts_with("#line ")) if (!line.starts_with("#line "))
code += line + "\n"; code += std::format("{}\n", line);
} }
glslang_shader_delete(shader); glslang_shader_delete(shader);
@@ -175,12 +175,12 @@ std::string CShaderLoader::loadShader(const std::string& filename) {
} }
const auto home = Hyprutils::Path::getHome(); const auto home = Hyprutils::Path::getHome();
if (home.has_value()) { 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()) if (src.has_value())
return src.value(); return src.value();
} }
for (auto& e : ASSET_PATHS) { 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()) if (src.has_value())
return src.value(); return src.value();
} }
+3 -3
View File
@@ -227,9 +227,9 @@ void CWorkspacePlacementController::swapActiveWorkspaces(PHLMONITOR pMonitorA, P
} }
// events // 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 = "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)}); 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); Event::bus()->m_events.workspace.moveToMonitor.emit(PWORKSPACEA, pMonitorB);
@@ -373,7 +373,7 @@ void CWorkspacePlacementController::moveWorkspaceToMonitor(PHLWORKSPACE pWorkspa
Desktop::globalWindowController()->updateSuspendedStates(); Desktop::globalWindowController()->updateSuspendedStates();
// event // 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)}); 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); Event::bus()->m_events.workspace.moveToMonitor.emit(pWorkspace, pMonitor);
+1 -1
View File
@@ -1577,7 +1577,7 @@ bool SXSelection::sendData(xcb_selection_request_event_t* e, std::string mime) {
if (Env::isTrace()) { if (Env::isTrace()) {
std::string mimeList = ""; std::string mimeList = "";
for (const auto& m : MIMES) { for (const auto& m : MIMES) {
mimeList += "'" + m + "', "; mimeList += std::format("'{}', ", m);
} }
if (!MIMES.empty()) if (!MIMES.empty())
+3 -3
View File
@@ -391,7 +391,7 @@ TEST(ConfigLuaRequire, absolutePathLoadsAndTracksFile) {
CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig); CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
const auto L = CConfigManagerPluginLuaTestAccessor::luaState(mgr); 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); ASSERT_EQ(luaL_dostring(L, CODE.c_str()), LUA_OK) << lua_tostring(L, -1);
lua_getglobal(L, "mod"); lua_getglobal(L, "mod");
@@ -517,6 +517,6 @@ TEST(ConfigLuaRequire, packagePathPreservesLuaDefaultsAfterConfigDirectory) {
CConfigManager mgr; CConfigManager mgr;
CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig); CConfigManagerPluginLuaTestAccessor::initializeOwnedLuaState(mgr, mainConfig);
const auto configPath = (tmp.path() / "?.lua").string() + ";" + (tmp.path() / "?/init.lua").string(); const auto configPath = std::format("{};{}", (tmp.path() / "?.lua").string(), (tmp.path() / "?/init.lua").string());
EXPECT_EQ(packagePath(CConfigManagerPluginLuaTestAccessor::luaState(mgr)), configPath + ";" + defaultPath); EXPECT_EQ(packagePath(CConfigManagerPluginLuaTestAccessor::luaState(mgr)), std::format("{};{}", configPath, defaultPath));
} }