logging/format: use std::format_string to catch formatting string errors at compile time (#3377)

* fix(log): use constexpr format string

* deprecate getFormat
This commit is contained in:
memchr 2023-09-20 07:26:20 +00:00 committed by GitHub
parent d8d0cd75c2
commit 6594b50e57
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 130 additions and 171 deletions

View File

@ -12,6 +12,7 @@
#include <ranges> #include <ranges>
#include <algorithm> #include <algorithm>
#include <signal.h> #include <signal.h>
#include <format>
#include <iostream> #include <iostream>
#include <string> #include <string>
@ -106,20 +107,6 @@ std::vector<SInstanceData> instances() {
return result; return result;
} }
std::string getFormat(const char* fmt, ...) {
char* outputStr = nullptr;
va_list args;
va_start(args, fmt);
vasprintf(&outputStr, fmt, args);
va_end(args);
std::string output = std::string(outputStr);
free(outputStr);
return output;
}
void request(std::string arg, int minArgs = 0) { void request(std::string arg, int minArgs = 0) {
const auto SERVERSOCKET = socket(AF_UNIX, SOCK_STREAM, 0); const auto SERVERSOCKET = socket(AF_UNIX, SOCK_STREAM, 0);
@ -248,19 +235,19 @@ void instancesRequest(bool json) {
if (!json) { if (!json) {
for (auto& el : inst) { for (auto& el : inst) {
result += getFormat("instance %s:\n\ttime: %llu\n\tpid: %llu\n\twl socket: %s\n\n", el.id.c_str(), el.time, el.pid, el.wlSocket.c_str()); result += std::format("instance {}:\n\ttime: {}\n\tpid: {}\n\twl socket: {}\n\n", el.id, el.time, el.pid, el.wlSocket);
} }
} else { } else {
result += '['; result += '[';
for (auto& el : inst) { for (auto& el : inst) {
result += getFormat(R"#( result += std::format(R"#(
{ {{
"instance": "%s", "instance": "{}",
"time": %llu, "time": {},
"pid": %llu, "pid": {},
"wl_socket": "%s" "wl_socket": "{}"
},)#", }},)#",
el.id.c_str(), el.time, el.pid, el.wlSocket.c_str()); el.id, el.time, el.pid, el.wlSocket);
} }
result.pop_back(); result.pop_back();

View File

@ -910,7 +910,7 @@ void CCompositor::focusWindow(CWindow* pWindow, wlr_surface* pSurface) {
// Send an event // Send an event
g_pEventManager->postEvent(SHyprIPCEvent{"activewindow", g_pXWaylandManager->getAppIDClass(pWindow) + "," + pWindow->m_szTitle}); g_pEventManager->postEvent(SHyprIPCEvent{"activewindow", g_pXWaylandManager->getAppIDClass(pWindow) + "," + pWindow->m_szTitle});
g_pEventManager->postEvent(SHyprIPCEvent{"activewindowv2", getFormat("{:x}", (uintptr_t)pWindow)}); g_pEventManager->postEvent(SHyprIPCEvent{"activewindowv2", std::format("{:x}", (uintptr_t)pWindow)});
EMIT_HOOK_EVENT("activeWindow", pWindow); EMIT_HOOK_EVENT("activeWindow", pWindow);
@ -2183,13 +2183,13 @@ CWindow* CCompositor::getWindowByRegex(const std::string& regexp) {
break; break;
} }
case MODE_ADDRESS: { case MODE_ADDRESS: {
std::string addr = getFormat("0x{:x}", (uintptr_t)w.get()); std::string addr = std::format("0x{:x}", (uintptr_t)w.get());
if (matchCheck != addr) if (matchCheck != addr)
continue; continue;
break; break;
} }
case MODE_PID: { case MODE_PID: {
std::string pid = getFormat("{}", w->getPID()); std::string pid = std::format("{}", w->getPID());
if (matchCheck != pid) if (matchCheck != pid)
continue; continue;
break; break;

View File

@ -340,7 +340,7 @@ void CWindow::moveToWorkspace(int workspaceID) {
updateSpecialRenderData(); updateSpecialRenderData();
if (PWORKSPACE) { if (PWORKSPACE) {
g_pEventManager->postEvent(SHyprIPCEvent{"movewindow", getFormat("{:x},{}", (uintptr_t)this, PWORKSPACE->m_szName)}); g_pEventManager->postEvent(SHyprIPCEvent{"movewindow", std::format("{:x},{}", (uintptr_t)this, PWORKSPACE->m_szName)});
EMIT_HOOK_EVENT("moveWindow", (std::vector<void*>{this, PWORKSPACE})); EMIT_HOOK_EVENT("moveWindow", (std::vector<void*>{this, PWORKSPACE}));
} }

View File

@ -1097,7 +1097,7 @@ void CConfigManager::updateBlurredLS(const std::string& name, const bool forceBl
for (auto& lsl : m->m_aLayerSurfaceLayers) { for (auto& lsl : m->m_aLayerSurfaceLayers) {
for (auto& ls : lsl) { for (auto& ls : lsl) {
if (BYADDRESS) { if (BYADDRESS) {
if (getFormat("0x{:x}", (uintptr_t)ls.get()) == matchName) if (std::format("0x{:x}", (uintptr_t)ls.get()) == matchName)
ls->forceBlur = forceBlur; ls->forceBlur = forceBlur;
} else if (ls->szNamespace == matchName) } else if (ls->szNamespace == matchName)
ls->forceBlur = forceBlur; ls->forceBlur = forceBlur;
@ -1206,7 +1206,7 @@ void CConfigManager::handleSource(const std::string& command, const std::string&
if (auto r = glob(absolutePath(rawpath, configCurrentPath).c_str(), GLOB_TILDE, nullptr, glob_buf.get()); r != 0) { if (auto r = glob(absolutePath(rawpath, configCurrentPath).c_str(), GLOB_TILDE, nullptr, glob_buf.get()); r != 0) {
parseError = std::format("source= globbing error: {}", r == GLOB_NOMATCH ? "found no match" : GLOB_ABORTED ? "read error" : "out of memory"); parseError = std::format("source= globbing error: {}", r == GLOB_NOMATCH ? "found no match" : GLOB_ABORTED ? "read error" : "out of memory");
Debug::log(ERR, parseError); Debug::log(ERR, "{}", parseError);
return; return;
} }
@ -1942,7 +1942,7 @@ std::vector<SLayerRule> CConfigManager::getMatchingRules(SLayerSurface* pLS) {
for (auto& lr : m_dLayerRules) { for (auto& lr : m_dLayerRules) {
if (lr.targetNamespace.find("address:0x") == 0) { if (lr.targetNamespace.find("address:0x") == 0) {
if (getFormat("address:0x{:x}", (uintptr_t)pLS) != lr.targetNamespace) if (std::format("address:0x{:x}", (uintptr_t)pLS) != lr.targetNamespace)
continue; continue;
} else { } else {
std::regex NSCHECK(lr.targetNamespace); std::regex NSCHECK(lr.targetNamespace);

View File

@ -45,15 +45,15 @@ void CrashReporter::createAndSaveCrash(int sig) {
finalCrashReport += "--------------------------------------------\n Hyprland Crash Report\n--------------------------------------------\n"; finalCrashReport += "--------------------------------------------\n Hyprland Crash Report\n--------------------------------------------\n";
finalCrashReport += getRandomMessage() + "\n\n"; finalCrashReport += getRandomMessage() + "\n\n";
finalCrashReport += getFormat("Hyprland received signal {} ({})\n\n", sig, (const char*)strsignal(sig)); finalCrashReport += std::format("Hyprland received signal {} ({})\n\n", sig, (const char*)strsignal(sig));
finalCrashReport += getFormat("Version: {}\nTag: {}\n\n", GIT_COMMIT_HASH, GIT_TAG); finalCrashReport += std::format("Version: {}\nTag: {}\n\n", GIT_COMMIT_HASH, GIT_TAG);
if (g_pPluginSystem && !g_pPluginSystem->getAllPlugins().empty()) { if (g_pPluginSystem && !g_pPluginSystem->getAllPlugins().empty()) {
finalCrashReport += "Hyprland seems to be running with plugins. This crash might not be Hyprland's fault.\nPlugins:\n"; finalCrashReport += "Hyprland seems to be running with plugins. This crash might not be Hyprland's fault.\nPlugins:\n";
for (auto& p : g_pPluginSystem->getAllPlugins()) { for (auto& p : g_pPluginSystem->getAllPlugins()) {
finalCrashReport += getFormat("\t{} ({}) {}\n", p->name, p->author, p->version); finalCrashReport += std::format("\t{} ({}) {}\n", p->name, p->author, p->version);
} }
finalCrashReport += "\n\n"; finalCrashReport += "\n\n";
@ -65,7 +65,7 @@ void CrashReporter::createAndSaveCrash(int sig) {
uname(&unameInfo); uname(&unameInfo);
finalCrashReport += finalCrashReport +=
getFormat("\tSystem name: {}\n\tNode name: {}\n\tRelease: {}\n\tVersion: {}\n\n", unameInfo.sysname, unameInfo.nodename, unameInfo.release, unameInfo.version); std::format("\tSystem name: {}\n\tNode name: {}\n\tRelease: {}\n\tVersion: {}\n\n", unameInfo.sysname, unameInfo.nodename, unameInfo.release, unameInfo.version);
#if defined(__DragonFly__) || defined(__FreeBSD__) #if defined(__DragonFly__) || defined(__FreeBSD__)
const std::string GPUINFO = execAndGet("pciconf -lv | fgrep -A4 vga"); const std::string GPUINFO = execAndGet("pciconf -lv | fgrep -A4 vga");
@ -75,7 +75,7 @@ void CrashReporter::createAndSaveCrash(int sig) {
finalCrashReport += "GPU:\n\t" + GPUINFO; finalCrashReport += "GPU:\n\t" + GPUINFO;
finalCrashReport += getFormat("\n\nos-release:\n\t{}\n\n\n", replaceInString(execAndGet("cat /etc/os-release"), "\n", "\n\t")); finalCrashReport += std::format("\n\nos-release:\n\t{}\n\n\n", replaceInString(execAndGet("cat /etc/os-release"), "\n", "\n\t"));
finalCrashReport += "Backtrace:\n"; finalCrashReport += "Backtrace:\n";
@ -107,12 +107,12 @@ void CrashReporter::createAndSaveCrash(int sig) {
#endif #endif
for (size_t i = 0; i < CALLSTACK.size(); ++i) { for (size_t i = 0; i < CALLSTACK.size(); ++i) {
finalCrashReport += getFormat("\t#{} | {}\n", i, CALLSTACK[i].desc); finalCrashReport += std::format("\t#{} | {}\n", i, CALLSTACK[i].desc);
#ifdef __clang__ #ifdef __clang__
const auto CMD = getFormat("llvm-addr2line -e {} -f 0x{:x}", FPATH.c_str(), (uint64_t)CALLSTACK[i].adr); const auto CMD = std::format("llvm-addr2line -e {} -f 0x{:x}", FPATH.c_str(), (uint64_t)CALLSTACK[i].adr);
#else #else
const auto CMD = getFormat("addr2line -e {} -f 0x{:x}", FPATH.c_str(), (uint64_t)CALLSTACK[i].adr); const auto CMD = std::format("addr2line -e {} -f 0x{:x}", FPATH.c_str(), (uint64_t)CALLSTACK[i].adr);
#endif #endif
const auto ADDR2LINE = replaceInString(execAndGet(CMD.c_str()), "\n", "\n\t\t"); const auto ADDR2LINE = replaceInString(execAndGet(CMD.c_str()), "\n", "\n\t\t");
finalCrashReport += "\t\t" + ADDR2LINE.substr(0, ADDR2LINE.length() - 2); finalCrashReport += "\t\t" + ADDR2LINE.substr(0, ADDR2LINE.length() - 2);

View File

@ -37,7 +37,7 @@ std::string monitorsRequest(HyprCtl::eHyprCtlOutputFormat format) {
if (!m->output) if (!m->output)
continue; continue;
result += getFormat( result += std::format(
R"#({{ R"#({{
"id": {}, "id": {},
"name": "{}", "name": "{}",
@ -82,16 +82,16 @@ std::string monitorsRequest(HyprCtl::eHyprCtlOutputFormat format) {
continue; continue;
result += result +=
getFormat("Monitor {} (ID {}):\n\t{}x{}@{:.5f} at {}x{}\n\tdescription: {}\n\tmake: {}\n\tmodel: {}\n\tserial: {}\n\tactive workspace: {} ({})\n\tspecial " std::format("Monitor {} (ID {}):\n\t{}x{}@{:.5f} at {}x{}\n\tdescription: {}\n\tmake: {}\n\tmodel: {}\n\tserial: {}\n\tactive workspace: {} ({})\n\tspecial "
"workspace: {} ({})\n\treserved: {} " "workspace: {} ({})\n\treserved: {} "
"{} {} {}\n\tscale: {:.2f}\n\ttransform: " "{} {} {}\n\tscale: {:.2f}\n\ttransform: "
"{}\n\tfocused: {}\n\tdpmsStatus: {}\n\tvrr: {}\n\n", "{}\n\tfocused: {}\n\tdpmsStatus: {}\n\tvrr: {}\n\n",
m->szName, m->ID, (int)m->vecPixelSize.x, (int)m->vecPixelSize.y, m->refreshRate, (int)m->vecPosition.x, (int)m->vecPosition.y, m->szName, m->ID, (int)m->vecPixelSize.x, (int)m->vecPixelSize.y, m->refreshRate, (int)m->vecPosition.x, (int)m->vecPosition.y,
(m->output->description ? m->output->description : ""), (m->output->make ? m->output->make : ""), (m->output->model ? m->output->model : ""), (m->output->description ? m->output->description : ""), (m->output->make ? m->output->make : ""), (m->output->model ? m->output->model : ""),
(m->output->serial ? m->output->serial : ""), m->activeWorkspace, g_pCompositor->getWorkspaceByID(m->activeWorkspace)->m_szName, m->specialWorkspaceID, (m->output->serial ? m->output->serial : ""), m->activeWorkspace, g_pCompositor->getWorkspaceByID(m->activeWorkspace)->m_szName, m->specialWorkspaceID,
getWorkspaceNameFromSpecialID(m->specialWorkspaceID), (int)m->vecReservedTopLeft.x, (int)m->vecReservedTopLeft.y, (int)m->vecReservedBottomRight.x, getWorkspaceNameFromSpecialID(m->specialWorkspaceID), (int)m->vecReservedTopLeft.x, (int)m->vecReservedTopLeft.y, (int)m->vecReservedBottomRight.x,
(int)m->vecReservedBottomRight.y, m->scale, (int)m->transform, (m.get() == g_pCompositor->m_pLastMonitor ? "yes" : "no"), (int)m->dpmsStatus, (int)m->vecReservedBottomRight.y, m->scale, (int)m->transform, (m.get() == g_pCompositor->m_pLastMonitor ? "yes" : "no"), (int)m->dpmsStatus,
(int)(m->output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED)); (int)(m->output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED));
} }
} }
@ -112,7 +112,6 @@ static std::string getGroupedData(CWindow* w, HyprCtl::eHyprCtlOutputFormat form
} while (curr != w); } while (curr != w);
const auto comma = isJson ? ", " : ","; const auto comma = isJson ? ", " : ",";
const auto fmt = isJson ? "\"0x{:x}\"" : "{:x}";
std::ostringstream result; std::ostringstream result;
bool first = true; bool first = true;
@ -121,8 +120,10 @@ static std::string getGroupedData(CWindow* w, HyprCtl::eHyprCtlOutputFormat form
first = false; first = false;
else else
result << comma; result << comma;
if (isJson)
result << getFormat(fmt, (uintptr_t)gw); result << std::format("\"0x{:x}\"", (uintptr_t)gw);
else
result << std::format("{:x}", (uintptr_t)gw);
} }
return result.str(); return result.str();
@ -130,7 +131,7 @@ static std::string getGroupedData(CWindow* w, HyprCtl::eHyprCtlOutputFormat form
static std::string getWindowData(CWindow* w, HyprCtl::eHyprCtlOutputFormat format) { static std::string getWindowData(CWindow* w, HyprCtl::eHyprCtlOutputFormat format) {
if (format == HyprCtl::FORMAT_JSON) { if (format == HyprCtl::FORMAT_JSON) {
return getFormat( return std::format(
R"#({{ R"#({{
"address": "0x{:x}", "address": "0x{:x}",
"mapped": {}, "mapped": {},
@ -167,7 +168,7 @@ static std::string getWindowData(CWindow* w, HyprCtl::eHyprCtlOutputFormat forma
(w->m_bIsFullscreen ? (g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID) ? (int)g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID)->m_efFullscreenMode : 0) : 0), (w->m_bIsFullscreen ? (g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID) ? (int)g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID)->m_efFullscreenMode : 0) : 0),
w->m_bFakeFullscreenState ? "true" : "false", getGroupedData(w, format), (uintptr_t)w->m_pSwallowed); w->m_bFakeFullscreenState ? "true" : "false", getGroupedData(w, format), (uintptr_t)w->m_pSwallowed);
} else { } else {
return getFormat( return std::format(
"Window {:x} -> {}:\n\tmapped: {}\n\thidden: {}\n\tat: {},{}\n\tsize: {},{}\n\tworkspace: {} ({})\n\tfloating: {}\n\tmonitor: {}\n\tclass: {}\n\ttitle: " "Window {:x} -> {}:\n\tmapped: {}\n\thidden: {}\n\tat: {},{}\n\tsize: {},{}\n\tworkspace: {} ({})\n\tfloating: {}\n\tmonitor: {}\n\tclass: {}\n\ttitle: "
"{}\n\tinitialClass: {}\n\tinitialTitle: {}\n\tpid: " "{}\n\tinitialClass: {}\n\tinitialTitle: {}\n\tpid: "
"{}\n\txwayland: {}\n\tpinned: " "{}\n\txwayland: {}\n\tpinned: "
@ -177,8 +178,8 @@ static std::string getWindowData(CWindow* w, HyprCtl::eHyprCtlOutputFormat forma
(w->m_iWorkspaceID == -1 ? "" : (w->m_iWorkspaceID == -1 ? "" :
g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID) ? g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID)->m_szName : g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID) ? g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID)->m_szName :
std::string("Invalid workspace " + std::to_string(w->m_iWorkspaceID))), std::string("Invalid workspace " + std::to_string(w->m_iWorkspaceID))),
(int)w->m_bIsFloating, (int64_t)w->m_iMonitorID, g_pXWaylandManager->getAppIDClass(w), g_pXWaylandManager->getTitle(w), w->m_szInitialClass, w->m_szInitialTitle, w->getPID(), (int)w->m_bIsFloating, (int64_t)w->m_iMonitorID, g_pXWaylandManager->getAppIDClass(w), g_pXWaylandManager->getTitle(w), w->m_szInitialClass, w->m_szInitialTitle,
(int)w->m_bIsX11, (int)w->m_bPinned, (int)w->m_bIsFullscreen, w->getPID(), (int)w->m_bIsX11, (int)w->m_bPinned, (int)w->m_bIsFullscreen,
(w->m_bIsFullscreen ? (g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID) ? g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID)->m_efFullscreenMode : 0) : 0), (w->m_bIsFullscreen ? (g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID) ? g_pCompositor->getWorkspaceByID(w->m_iWorkspaceID)->m_efFullscreenMode : 0) : 0),
(int)w->m_bFakeFullscreenState, getGroupedData(w, format), (uintptr_t)w->m_pSwallowed); (int)w->m_bFakeFullscreenState, getGroupedData(w, format), (uintptr_t)w->m_pSwallowed);
} }
@ -208,7 +209,7 @@ static std::string getWorkspaceData(CWorkspace* w, HyprCtl::eHyprCtlOutputFormat
const auto PLASTW = w->getLastFocusedWindow(); const auto PLASTW = w->getLastFocusedWindow();
const auto PMONITOR = g_pCompositor->getMonitorFromID(w->m_iMonitorID); const auto PMONITOR = g_pCompositor->getMonitorFromID(w->m_iMonitorID);
if (format == HyprCtl::FORMAT_JSON) { if (format == HyprCtl::FORMAT_JSON) {
return getFormat(R"#({{ return std::format(R"#({{
"id": {}, "id": {},
"name": "{}", "name": "{}",
"monitor": "{}", "monitor": "{}",
@ -217,12 +218,12 @@ static std::string getWorkspaceData(CWorkspace* w, HyprCtl::eHyprCtlOutputFormat
"lastwindow": "0x{:x}", "lastwindow": "0x{:x}",
"lastwindowtitle": "{}" "lastwindowtitle": "{}"
}})#", }})#",
w->m_iID, escapeJSONStrings(w->m_szName), escapeJSONStrings(PMONITOR ? PMONITOR->szName : "?"), g_pCompositor->getWindowsOnWorkspace(w->m_iID), w->m_iID, escapeJSONStrings(w->m_szName), escapeJSONStrings(PMONITOR ? PMONITOR->szName : "?"), g_pCompositor->getWindowsOnWorkspace(w->m_iID),
((int)w->m_bHasFullscreenWindow == 1 ? "true" : "false"), (uintptr_t)PLASTW, PLASTW ? escapeJSONStrings(PLASTW->m_szTitle) : ""); ((int)w->m_bHasFullscreenWindow == 1 ? "true" : "false"), (uintptr_t)PLASTW, PLASTW ? escapeJSONStrings(PLASTW->m_szTitle) : "");
} else { } else {
return getFormat("workspace ID {} ({}) on monitor {}:\n\twindows: {}\n\thasfullscreen: {}\n\tlastwindow: 0x{:x}\n\tlastwindowtitle: {}\n\n", w->m_iID, w->m_szName, return std::format("workspace ID {} ({}) on monitor {}:\n\twindows: {}\n\thasfullscreen: {}\n\tlastwindow: 0x{:x}\n\tlastwindowtitle: {}\n\n", w->m_iID, w->m_szName,
PMONITOR ? PMONITOR->szName : "?", g_pCompositor->getWindowsOnWorkspace(w->m_iID), (int)w->m_bHasFullscreenWindow, (uintptr_t)PLASTW, PMONITOR ? PMONITOR->szName : "?", g_pCompositor->getWindowsOnWorkspace(w->m_iID), (int)w->m_bHasFullscreenWindow, (uintptr_t)PLASTW,
PLASTW ? PLASTW->m_szTitle : ""); PLASTW ? PLASTW->m_szTitle : "");
} }
} }
@ -274,7 +275,7 @@ std::string layersRequest(HyprCtl::eHyprCtlOutputFormat format) {
result += "{\n"; result += "{\n";
for (auto& mon : g_pCompositor->m_vMonitors) { for (auto& mon : g_pCompositor->m_vMonitors) {
result += getFormat( result += std::format(
R"#("{}": {{ R"#("{}": {{
"levels": {{ "levels": {{
)#", )#",
@ -282,13 +283,13 @@ std::string layersRequest(HyprCtl::eHyprCtlOutputFormat format) {
int layerLevel = 0; int layerLevel = 0;
for (auto& level : mon->m_aLayerSurfaceLayers) { for (auto& level : mon->m_aLayerSurfaceLayers) {
result += getFormat( result += std::format(
R"#( R"#(
"{}": [ "{}": [
)#", )#",
layerLevel); layerLevel);
for (auto& layer : level) { for (auto& layer : level) {
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"x": {}, "x": {},
@ -321,15 +322,15 @@ std::string layersRequest(HyprCtl::eHyprCtlOutputFormat format) {
} else { } else {
for (auto& mon : g_pCompositor->m_vMonitors) { for (auto& mon : g_pCompositor->m_vMonitors) {
result += getFormat("Monitor {}:\n", mon->szName); result += std::format("Monitor {}:\n", mon->szName);
int layerLevel = 0; int layerLevel = 0;
static const std::array<std::string, 4> levelNames = {"background", "bottom", "top", "overlay"}; static const std::array<std::string, 4> levelNames = {"background", "bottom", "top", "overlay"};
for (auto& level : mon->m_aLayerSurfaceLayers) { for (auto& level : mon->m_aLayerSurfaceLayers) {
result += getFormat("\tLayer level {} ({}):\n", layerLevel, levelNames[layerLevel]); result += std::format("\tLayer level {} ({}):\n", layerLevel, levelNames[layerLevel]);
for (auto& layer : level) { for (auto& layer : level) {
result += getFormat("\t\tLayer {:x}: xywh: {} {} {} {}, namespace: {}\n", (uintptr_t)layer.get(), layer->geometry.x, layer->geometry.y, layer->geometry.width, result += std::format("\t\tLayer {:x}: xywh: {} {} {} {}, namespace: {}\n", (uintptr_t)layer.get(), layer->geometry.x, layer->geometry.y, layer->geometry.width,
layer->geometry.height, layer->szNamespace); layer->geometry.height, layer->szNamespace);
} }
layerLevel++; layerLevel++;
@ -349,7 +350,7 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
result += "\"mice\": [\n"; result += "\"mice\": [\n";
for (auto& m : g_pInputManager->m_lMice) { for (auto& m : g_pInputManager->m_lMice) {
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"name": "{}", "name": "{}",
@ -365,7 +366,7 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
result += "\"keyboards\": [\n"; result += "\"keyboards\": [\n";
for (auto& k : g_pInputManager->m_lKeyboards) { for (auto& k : g_pInputManager->m_lKeyboards) {
const auto KM = g_pInputManager->getActiveLayoutForKeyboard(&k); const auto KM = g_pInputManager->getActiveLayoutForKeyboard(&k);
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"name": "{}", "name": "{}",
@ -388,7 +389,7 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
result += "\"tablets\": [\n"; result += "\"tablets\": [\n";
for (auto& d : g_pInputManager->m_lTabletPads) { for (auto& d : g_pInputManager->m_lTabletPads) {
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"type": "tabletPad", "type": "tabletPad",
@ -401,7 +402,7 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
} }
for (auto& d : g_pInputManager->m_lTablets) { for (auto& d : g_pInputManager->m_lTablets) {
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"name": "{}" "name": "{}"
@ -410,13 +411,13 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
} }
for (auto& d : g_pInputManager->m_lTabletTools) { for (auto& d : g_pInputManager->m_lTabletTools) {
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"type": "tabletTool", "type": "tabletTool",
"belongsTo": "0x{:x}" "belongsTo": "0x{:x}"
}},)#", }},)#",
(uintptr_t)&d, d.wlrTabletTool ? d.wlrTabletTool->data : 0); (uintptr_t)&d, d.wlrTabletTool ? (uintptr_t)d.wlrTabletTool->data : 0);
} }
trimTrailingComma(result); trimTrailingComma(result);
@ -425,7 +426,7 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
result += "\"touch\": [\n"; result += "\"touch\": [\n";
for (auto& d : g_pInputManager->m_lTouchDevices) { for (auto& d : g_pInputManager->m_lTouchDevices) {
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"name": "{}" "name": "{}"
@ -439,7 +440,7 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
result += "\"switches\": [\n"; result += "\"switches\": [\n";
for (auto& d : g_pInputManager->m_lSwitches) { for (auto& d : g_pInputManager->m_lSwitches) {
result += getFormat( result += std::format(
R"#( {{ R"#( {{
"address": "0x{:x}", "address": "0x{:x}",
"name": "{}" "name": "{}"
@ -456,7 +457,7 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
result += "mice:\n"; result += "mice:\n";
for (auto& m : g_pInputManager->m_lMice) { for (auto& m : g_pInputManager->m_lMice) {
result += getFormat( result += std::format(
"\tMouse at {:x}:\n\t\t{}\n\t\t\tdefault speed: {:.5f}\n", (uintptr_t)&m, m.name, "\tMouse at {:x}:\n\t\t{}\n\t\t\tdefault speed: {:.5f}\n", (uintptr_t)&m, m.name,
(wlr_input_device_is_libinput(m.mouse) ? libinput_device_config_accel_get_default_speed((libinput_device*)wlr_libinput_get_device_handle(m.mouse)) : 0.f)); (wlr_input_device_is_libinput(m.mouse) ? libinput_device_config_accel_get_default_speed((libinput_device*)wlr_libinput_get_device_handle(m.mouse)) : 0.f));
} }
@ -465,35 +466,35 @@ std::string devicesRequest(HyprCtl::eHyprCtlOutputFormat format) {
for (auto& k : g_pInputManager->m_lKeyboards) { for (auto& k : g_pInputManager->m_lKeyboards) {
const auto KM = g_pInputManager->getActiveLayoutForKeyboard(&k); const auto KM = g_pInputManager->getActiveLayoutForKeyboard(&k);
result += result += std::format("\tKeyboard at {:x}:\n\t\t{}\n\t\t\trules: r \"{}\", m \"{}\", l \"{}\", v \"{}\", o \"{}\"\n\t\t\tactive keymap: {}\n\t\t\tmain: {}\n",
getFormat("\tKeyboard at {:x}:\n\t\t{}\n\t\t\trules: r \"{}\", m \"{}\", l \"{}\", v \"{}\", o \"{}\"\n\t\t\tactive keymap: {}\n\t\t\tmain: {}\n", (uintptr_t)&k, (uintptr_t)&k, k.name, k.currentRules.rules, k.currentRules.model, k.currentRules.layout, k.currentRules.variant, k.currentRules.options, KM,
k.name, k.currentRules.rules, k.currentRules.model, k.currentRules.layout, k.currentRules.variant, k.currentRules.options, KM, (k.active ? "yes" : "no")); (k.active ? "yes" : "no"));
} }
result += "\n\nTablets:\n"; result += "\n\nTablets:\n";
for (auto& d : g_pInputManager->m_lTabletPads) { for (auto& d : g_pInputManager->m_lTabletPads) {
result += getFormat("\tTablet Pad at {:x} (belongs to {:x} -> {})\n", (uintptr_t)&d, (uintptr_t)d.pTabletParent, d.pTabletParent ? d.pTabletParent->name : ""); result += std::format("\tTablet Pad at {:x} (belongs to {:x} -> {})\n", (uintptr_t)&d, (uintptr_t)d.pTabletParent, d.pTabletParent ? d.pTabletParent->name : "");
} }
for (auto& d : g_pInputManager->m_lTablets) { for (auto& d : g_pInputManager->m_lTablets) {
result += getFormat("\tTablet at {:x}:\n\t\t{}\n", (uintptr_t)&d, d.name); result += std::format("\tTablet at {:x}:\n\t\t{}\n", (uintptr_t)&d, d.name);
} }
for (auto& d : g_pInputManager->m_lTabletTools) { for (auto& d : g_pInputManager->m_lTabletTools) {
result += getFormat("\tTablet Tool at {:x} (belongs to {:x})\n", (uintptr_t)&d, d.wlrTabletTool ? d.wlrTabletTool->data : 0); result += std::format("\tTablet Tool at {:x} (belongs to {:x})\n", (uintptr_t)&d, d.wlrTabletTool ? (uintptr_t)d.wlrTabletTool->data : 0);
} }
result += "\n\nTouch:\n"; result += "\n\nTouch:\n";
for (auto& d : g_pInputManager->m_lTouchDevices) { for (auto& d : g_pInputManager->m_lTouchDevices) {
result += getFormat("\tTouch Device at {:x}:\n\t\t{}\n", (uintptr_t)&d, d.name); result += std::format("\tTouch Device at {:x}:\n\t\t{}\n", (uintptr_t)&d, d.name);
} }
result += "\n\nSwitches:\n"; result += "\n\nSwitches:\n";
for (auto& d : g_pInputManager->m_lSwitches) { for (auto& d : g_pInputManager->m_lSwitches) {
result += getFormat("\tSwitch Device at {:x}:\n\t\t{}\n", (uintptr_t)&d, d.pWlrDevice ? d.pWlrDevice->name : ""); result += std::format("\tSwitch Device at {:x}:\n\t\t{}\n", (uintptr_t)&d, d.pWlrDevice ? d.pWlrDevice->name : "");
} }
} }
@ -506,21 +507,21 @@ std::string animationsRequest(HyprCtl::eHyprCtlOutputFormat format) {
ret += "animations:\n"; ret += "animations:\n";
for (auto& ac : g_pConfigManager->getAnimationConfig()) { for (auto& ac : g_pConfigManager->getAnimationConfig()) {
ret += getFormat("\n\tname: {}\n\t\toverriden: {}\n\t\tbezier: {}\n\t\tenabled: {}\n\t\tspeed: {:.2f}\n\t\tstyle: {}\n", ac.first, (int)ac.second.overridden, ret += std::format("\n\tname: {}\n\t\toverriden: {}\n\t\tbezier: {}\n\t\tenabled: {}\n\t\tspeed: {:.2f}\n\t\tstyle: {}\n", ac.first, (int)ac.second.overridden,
ac.second.internalBezier, ac.second.internalEnabled, ac.second.internalSpeed, ac.second.internalStyle); ac.second.internalBezier, ac.second.internalEnabled, ac.second.internalSpeed, ac.second.internalStyle);
} }
ret += "beziers:\n"; ret += "beziers:\n";
for (auto& bz : g_pAnimationManager->getAllBeziers()) { for (auto& bz : g_pAnimationManager->getAllBeziers()) {
ret += getFormat("\n\tname: {}\n", bz.first); ret += std::format("\n\tname: {}\n", bz.first);
} }
} else { } else {
// json // json
ret += "[["; ret += "[[";
for (auto& ac : g_pConfigManager->getAnimationConfig()) { for (auto& ac : g_pConfigManager->getAnimationConfig()) {
ret += getFormat(R"#( ret += std::format(R"#(
{{ {{
"name": "{}", "name": "{}",
"overridden": {}, "overridden": {},
@ -529,8 +530,8 @@ std::string animationsRequest(HyprCtl::eHyprCtlOutputFormat format) {
"speed": {:.2f}, "speed": {:.2f},
"style": "{}" "style": "{}"
}},)#", }},)#",
ac.first, ac.second.overridden ? "true" : "false", ac.second.internalBezier, ac.second.internalEnabled ? "true" : "false", ac.second.internalSpeed, ac.first, ac.second.overridden ? "true" : "false", ac.second.internalBezier, ac.second.internalEnabled ? "true" : "false", ac.second.internalSpeed,
ac.second.internalStyle); ac.second.internalStyle);
} }
ret[ret.length() - 1] = ']'; ret[ret.length() - 1] = ']';
@ -538,11 +539,11 @@ std::string animationsRequest(HyprCtl::eHyprCtlOutputFormat format) {
ret += ",\n["; ret += ",\n[";
for (auto& bz : g_pAnimationManager->getAllBeziers()) { for (auto& bz : g_pAnimationManager->getAllBeziers()) {
ret += getFormat(R"#( ret += std::format(R"#(
{{ {{
"name": "{}" "name": "{}"
}},)#", }},)#",
bz.first); bz.first);
} }
trimTrailingComma(ret); trimTrailingComma(ret);
@ -558,16 +559,16 @@ std::string globalShortcutsRequest(HyprCtl::eHyprCtlOutputFormat format) {
const auto SHORTCUTS = g_pProtocolManager->m_pGlobalShortcutsProtocolManager->getAllShortcuts(); const auto SHORTCUTS = g_pProtocolManager->m_pGlobalShortcutsProtocolManager->getAllShortcuts();
if (format == HyprCtl::eHyprCtlOutputFormat::FORMAT_NORMAL) { if (format == HyprCtl::eHyprCtlOutputFormat::FORMAT_NORMAL) {
for (auto& sh : SHORTCUTS) for (auto& sh : SHORTCUTS)
ret += getFormat("{}:{} -> {}\n", sh.appid, sh.id, sh.description); ret += std::format("{}:{} -> {}\n", sh.appid, sh.id, sh.description);
} else { } else {
ret += "["; ret += "[";
for (auto& sh : SHORTCUTS) { for (auto& sh : SHORTCUTS) {
ret += getFormat(R"#( ret += std::format(R"#(
{{ {{
"name": "{}", "name": "{}",
"description": "{}" "description": "{}"
}},)#", }},)#",
escapeJSONStrings(sh.appid + ":" + sh.id), escapeJSONStrings(sh.description)); escapeJSONStrings(sh.appid + ":" + sh.id), escapeJSONStrings(sh.description));
} }
trimTrailingComma(ret); trimTrailingComma(ret);
ret += "]\n"; ret += "]\n";
@ -592,14 +593,14 @@ std::string bindsRequest(HyprCtl::eHyprCtlOutputFormat format) {
if (kb.nonConsuming) if (kb.nonConsuming)
ret += "n"; ret += "n";
ret += getFormat("\n\tmodmask: {}\n\tsubmap: {}\n\tkey: {}\n\tkeycode: {}\n\tdispatcher: {}\n\targ: {}\n\n", kb.modmask, kb.submap, kb.key, kb.keycode, kb.handler, ret += std::format("\n\tmodmask: {}\n\tsubmap: {}\n\tkey: {}\n\tkeycode: {}\n\tdispatcher: {}\n\targ: {}\n\n", kb.modmask, kb.submap, kb.key, kb.keycode, kb.handler,
kb.arg); kb.arg);
} }
} else { } else {
// json // json
ret += "["; ret += "[";
for (auto& kb : g_pKeybindManager->m_lKeybinds) { for (auto& kb : g_pKeybindManager->m_lKeybinds) {
ret += getFormat( ret += std::format(
R"#( R"#(
{{ {{
"locked": {}, "locked": {},
@ -648,7 +649,7 @@ std::string versionRequest(HyprCtl::eHyprCtlOutputFormat format) {
return result; return result;
} else { } else {
std::string result = getFormat( std::string result = std::format(
R"#({{ R"#({{
"branch": "{}", "branch": "{}",
"commit": "{}", "commit": "{}",
@ -779,15 +780,15 @@ std::string cursorPosRequest(HyprCtl::eHyprCtlOutputFormat format) {
const auto CURSORPOS = g_pInputManager->getMouseCoordsInternal().floor(); const auto CURSORPOS = g_pInputManager->getMouseCoordsInternal().floor();
if (format == HyprCtl::FORMAT_NORMAL) { if (format == HyprCtl::FORMAT_NORMAL) {
return getFormat("{}, {}", (int)CURSORPOS.x, (int)CURSORPOS.y); return std::format("{}, {}", (int)CURSORPOS.x, (int)CURSORPOS.y);
} else { } else {
return getFormat(R"#( return std::format(R"#(
{{ {{
"x": {}, "x": {},
"y": {} "y": {}
}} }}
)#", )#",
(int)CURSORPOS.x, (int)CURSORPOS.y); (int)CURSORPOS.x, (int)CURSORPOS.y);
} }
return "error"; return "error";
@ -1039,10 +1040,10 @@ std::string dispatchGetOption(std::string request, HyprCtl::eHyprCtlOutputFormat
return "no such option"; return "no such option";
if (format == HyprCtl::eHyprCtlOutputFormat::FORMAT_NORMAL) if (format == HyprCtl::eHyprCtlOutputFormat::FORMAT_NORMAL)
return getFormat("option {}\n\tint: {}\n\tfloat: {:.5f}\n\tstr: \"{}\"\n\tdata: {:x}\n\tset: {}", curitem, PCFGOPT->intValue, PCFGOPT->floatValue, PCFGOPT->strValue, return std::format("option {}\n\tint: {}\n\tfloat: {:.5f}\n\tstr: \"{}\"\n\tdata: {:x}\n\tset: {}", curitem, PCFGOPT->intValue, PCFGOPT->floatValue, PCFGOPT->strValue,
(uintptr_t)PCFGOPT->data.get(), PCFGOPT->set); (uintptr_t)PCFGOPT->data.get(), PCFGOPT->set);
else { else {
return getFormat( return std::format(
R"#( R"#(
{{ {{
"option": "{}", "option": "{}",
@ -1169,7 +1170,7 @@ std::string dispatchPlugin(std::string request) {
std::string list = ""; std::string list = "";
for (auto& p : PLUGINS) { for (auto& p : PLUGINS) {
list += getFormat("\nPlugin {} by {}:\n\tHandle: {:x}\n\tVersion: {}\n\tDescription: {}\n", p->name, p->author, (uintptr_t)p->m_pHandle, p->version, p->description); list += std::format("\nPlugin {} by {}:\n\tHandle: {:x}\n\tVersion: {}\n\tDescription: {}\n", p->name, p->author, (uintptr_t)p->m_pHandle, p->version, p->description);
} }
return list; return list;

View File

@ -132,7 +132,7 @@ int CHyprMonitorDebugOverlay::draw(int offset) {
yOffset += 17; yOffset += 17;
cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset); cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset);
text = getFormat("{} FPS", (int)FPS); text = std::format("{} FPS", (int)FPS);
cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str()); cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str());
cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents); cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents);
if (cairoExtents.width > maxX) if (cairoExtents.width > maxX)
@ -143,7 +143,7 @@ int CHyprMonitorDebugOverlay::draw(int offset) {
yOffset += 11; yOffset += 11;
cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset); cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset);
text = getFormat("Avg Frametime: {:.2f}ms (var {:.2f}ms)", avgFrametime, varFrametime); text = std::format("Avg Frametime: {:.2f}ms (var {:.2f}ms)", avgFrametime, varFrametime);
cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str()); cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str());
cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents); cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents);
if (cairoExtents.width > maxX) if (cairoExtents.width > maxX)
@ -151,7 +151,7 @@ int CHyprMonitorDebugOverlay::draw(int offset) {
yOffset += 11; yOffset += 11;
cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset); cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset);
text = getFormat("Avg Rendertime: {:.2f}ms (var {:.2f}ms)", avgRenderTime, varRenderTime); text = std::format("Avg Rendertime: {:.2f}ms (var {:.2f}ms)", avgRenderTime, varRenderTime);
cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str()); cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str());
cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents); cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents);
if (cairoExtents.width > maxX) if (cairoExtents.width > maxX)
@ -159,7 +159,7 @@ int CHyprMonitorDebugOverlay::draw(int offset) {
yOffset += 11; yOffset += 11;
cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset); cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset);
text = getFormat("Avg Rendertime (No Overlay): {:.2f}ms (var {:.2f}ms)", avgRenderTimeNoOverlay, varRenderTimeNoOverlay); text = std::format("Avg Rendertime (No Overlay): {:.2f}ms (var {:.2f}ms)", avgRenderTimeNoOverlay, varRenderTimeNoOverlay);
cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str()); cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str());
cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents); cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents);
if (cairoExtents.width > maxX) if (cairoExtents.width > maxX)
@ -167,7 +167,7 @@ int CHyprMonitorDebugOverlay::draw(int offset) {
yOffset += 11; yOffset += 11;
cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset); cairo_move_to(g_pDebugOverlay->m_pCairo, 0, yOffset);
text = getFormat("Avg Anim Tick: {:.2f}ms (var {:.2f}ms) ({:.2f} TPS)", avgAnimMgrTick, varAnimMgrTick, 1.0 / (avgAnimMgrTick / 1000.0)); text = std::format("Avg Anim Tick: {:.2f}ms (var {:.2f}ms) ({:.2f} TPS)", avgAnimMgrTick, varAnimMgrTick, 1.0 / (avgAnimMgrTick / 1000.0));
cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str()); cairo_show_text(g_pDebugOverlay->m_pCairo, text.c_str());
cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents); cairo_text_extents(g_pDebugOverlay->m_pCairo, text.c_str(), &cairoExtents);
if (cairoExtents.width > maxX) if (cairoExtents.width > maxX)

View File

@ -9,8 +9,7 @@
#define LOGMESSAGESIZE 1024 #define LOGMESSAGESIZE 1024
enum LogLevel enum LogLevel {
{
NONE = -1, NONE = -1,
LOG = 0, LOG = 0,
WARN, WARN,
@ -29,7 +28,7 @@ namespace Debug {
void init(const std::string& IS); void init(const std::string& IS);
template <typename... Args> template <typename... Args>
void log(LogLevel level, const std::string& fmt, Args&&... args) { void log(LogLevel level, std::format_string<Args...> fmt, Args&&... args) {
if (disableLogs && *disableLogs) if (disableLogs && *disableLogs)
return; return;
@ -63,20 +62,12 @@ namespace Debug {
#endif #endif
} }
try { // no need for try {} catch {} because std::format_string<Args...> ensures that vformat never throw std::format_error
logMsg += std::vformat(fmt, std::make_format_args(args...)); // because
} catch (std::exception& e) { // 1. any faulty format specifier that sucks will cause a compilation error.
std::string exceptionMsg = e.what(); // 2. and `std::bad_alloc` is catastrophic, (Almost any operation in stdlib could throw this.)
Debug::log(ERR, "caught exception in Debug::log: {}", exceptionMsg); // 3. this is actually what std::format in stdlib does
logMsg += std::vformat(fmt.get(), std::make_format_args(args...));
const auto CALLSTACK = getBacktrace();
Debug::log(LOG, "stacktrace:");
for (size_t i = 0; i < CALLSTACK.size(); ++i) {
Debug::log(NONE, "\t #{} | {}", i, CALLSTACK[i].desc);
}
}
ofs << logMsg << "\n"; ofs << logMsg << "\n";

View File

@ -592,7 +592,7 @@ void Events::listener_mapWindow(void* owner, void* data) {
auto workspaceID = requestedWorkspace != "" ? requestedWorkspace : PWORKSPACE->m_szName; auto workspaceID = requestedWorkspace != "" ? requestedWorkspace : PWORKSPACE->m_szName;
g_pEventManager->postEvent( g_pEventManager->postEvent(
SHyprIPCEvent{"openwindow", getFormat("{:x},{},{},{}", (uintptr_t)PWINDOW, workspaceID, g_pXWaylandManager->getAppIDClass(PWINDOW), PWINDOW->m_szTitle)}); SHyprIPCEvent{"openwindow", std::format("{:x},{},{},{}", (uintptr_t)PWINDOW, workspaceID, g_pXWaylandManager->getAppIDClass(PWINDOW), PWINDOW->m_szTitle)});
EMIT_HOOK_EVENT("openWindow", PWINDOW); EMIT_HOOK_EVENT("openWindow", PWINDOW);
// recalc the values for this window // recalc the values for this window
@ -612,7 +612,7 @@ void Events::listener_unmapWindow(void* owner, void* data) {
return; return;
} }
g_pEventManager->postEvent(SHyprIPCEvent{"closewindow", getFormat("{:x}", (uintptr_t)PWINDOW)}); g_pEventManager->postEvent(SHyprIPCEvent{"closewindow", std::format("{:x}", (uintptr_t)PWINDOW)});
EMIT_HOOK_EVENT("closeWindow", PWINDOW); EMIT_HOOK_EVENT("closeWindow", PWINDOW);
g_pProtocolManager->m_pToplevelExportProtocolManager->onWindowUnmap(PWINDOW); g_pProtocolManager->m_pToplevelExportProtocolManager->onWindowUnmap(PWINDOW);
@ -806,12 +806,12 @@ void Events::listener_setTitleWindow(void* owner, void* data) {
return; return;
PWINDOW->m_szTitle = g_pXWaylandManager->getTitle(PWINDOW); PWINDOW->m_szTitle = g_pXWaylandManager->getTitle(PWINDOW);
g_pEventManager->postEvent(SHyprIPCEvent{"windowtitle", getFormat("{:x}", (uintptr_t)PWINDOW)}); g_pEventManager->postEvent(SHyprIPCEvent{"windowtitle", std::format("{:x}", (uintptr_t)PWINDOW)});
EMIT_HOOK_EVENT("windowTitle", PWINDOW); EMIT_HOOK_EVENT("windowTitle", PWINDOW);
if (PWINDOW == g_pCompositor->m_pLastWindow) { // if it's the active, let's post an event to update others if (PWINDOW == g_pCompositor->m_pLastWindow) { // if it's the active, let's post an event to update others
g_pEventManager->postEvent(SHyprIPCEvent{"activewindow", g_pXWaylandManager->getAppIDClass(PWINDOW) + "," + PWINDOW->m_szTitle}); g_pEventManager->postEvent(SHyprIPCEvent{"activewindow", g_pXWaylandManager->getAppIDClass(PWINDOW) + "," + PWINDOW->m_szTitle});
g_pEventManager->postEvent(SHyprIPCEvent{"activewindowv2", getFormat("{:x}", (uintptr_t)PWINDOW)}); g_pEventManager->postEvent(SHyprIPCEvent{"activewindowv2", std::format("{:x}", (uintptr_t)PWINDOW)});
EMIT_HOOK_EVENT("activeWindow", PWINDOW); EMIT_HOOK_EVENT("activeWindow", PWINDOW);
} }
@ -896,7 +896,7 @@ void Events::listener_activateXDG(wl_listener* listener, void* data) {
if (!PWINDOW || PWINDOW == g_pCompositor->m_pLastWindow) if (!PWINDOW || PWINDOW == g_pCompositor->m_pLastWindow)
return; return;
g_pEventManager->postEvent(SHyprIPCEvent{"urgent", getFormat("{:x}", (uintptr_t)PWINDOW)}); g_pEventManager->postEvent(SHyprIPCEvent{"urgent", std::format("{:x}", (uintptr_t)PWINDOW)});
EMIT_HOOK_EVENT("urgent", PWINDOW); EMIT_HOOK_EVENT("urgent", PWINDOW);
PWINDOW->m_bIsUrgent = true; PWINDOW->m_bIsUrgent = true;
@ -932,7 +932,7 @@ void Events::listener_activateX11(void* owner, void* data) {
if (PWINDOW == g_pCompositor->m_pLastWindow) if (PWINDOW == g_pCompositor->m_pLastWindow)
return; return;
g_pEventManager->postEvent(SHyprIPCEvent{"urgent", getFormat("{:x}", (uintptr_t)PWINDOW)}); g_pEventManager->postEvent(SHyprIPCEvent{"urgent", std::format("{:x}", (uintptr_t)PWINDOW)});
EMIT_HOOK_EVENT("urgent", PWINDOW); EMIT_HOOK_EVENT("urgent", PWINDOW);
if (!*PFOCUSONACTIVATE) if (!*PFOCUSONACTIVATE)
@ -1146,13 +1146,13 @@ void Events::listener_requestMinimize(void* owner, void* data) {
const auto E = (wlr_xwayland_minimize_event*)data; const auto E = (wlr_xwayland_minimize_event*)data;
g_pEventManager->postEvent({"minimize", getFormat("{:x},{}", (uintptr_t)PWINDOW, (int)E->minimize)}); g_pEventManager->postEvent({"minimize", std::format("{:x},{}", (uintptr_t)PWINDOW, (int)E->minimize)});
EMIT_HOOK_EVENT("minimize", (std::vector<void*>{PWINDOW, (void*)E->minimize})); EMIT_HOOK_EVENT("minimize", (std::vector<void*>{PWINDOW, (void*)E->minimize}));
wlr_xwayland_surface_set_minimized(PWINDOW->m_uSurface.xwayland, E->minimize && g_pCompositor->m_pLastWindow != PWINDOW); // fucking DXVK wlr_xwayland_surface_set_minimized(PWINDOW->m_uSurface.xwayland, E->minimize && g_pCompositor->m_pLastWindow != PWINDOW); // fucking DXVK
} else { } else {
const auto E = (wlr_foreign_toplevel_handle_v1_minimized_event*)data; const auto E = (wlr_foreign_toplevel_handle_v1_minimized_event*)data;
g_pEventManager->postEvent({"minimize", getFormat("{:x},{}", (uintptr_t)PWINDOW, E ? (int)E->minimized : 1)}); g_pEventManager->postEvent({"minimize", std::format("{:x},{}", (uintptr_t)PWINDOW, E ? (int)E->minimized : 1)});
EMIT_HOOK_EVENT("minimize", (std::vector<void*>{PWINDOW, (void*)(E ? (uint64_t)E->minimized : 1)})); EMIT_HOOK_EVENT("minimize", (std::vector<void*>{PWINDOW, (void*)(E ? (uint64_t)E->minimized : 1)}));
} }
} }

View File

@ -706,8 +706,4 @@ std::vector<SCallstackFrameInfo> getBacktrace() {
void throwError(const std::string& err) { void throwError(const std::string& err) {
Debug::log(CRIT, "Critical error thrown: {}", err); Debug::log(CRIT, "Critical error thrown: {}", err);
throw std::runtime_error(err); throw std::runtime_error(err);
} }
void sendToLog(uint8_t level, const std::string& s) {
Debug::log((LogLevel)level, s);
}

View File

@ -32,26 +32,10 @@ std::string replaceInString(std::string subject, const std:
std::vector<SCallstackFrameInfo> getBacktrace(); std::vector<SCallstackFrameInfo> getBacktrace();
void throwError(const std::string& err); void throwError(const std::string& err);
// why, C++.
void sendToLog(uint8_t, const std::string&);
template <typename... Args> template <typename... Args>
std::string getFormat(const std::string& fmt, Args&&... args) { [[deprecated("use std::format instead")]] std::string getFormat(std::format_string<Args...> fmt, Args&&... args) {
std::string fmtdMsg; // no need for try {} catch {} because std::format_string<Args...> ensures that vformat never throw std::format_error
// because any suck format specifier will cause a compilation error
try { // this is actually what std::format in stdlib does
fmtdMsg += std::vformat(fmt, std::make_format_args(args...)); return std::vformat(fmt.get(), std::make_format_args(args...));
} catch (std::exception& e) {
std::string exceptionMsg = e.what();
sendToLog(2, std::format("caught exception in getFormat: {}", exceptionMsg));
const auto CALLSTACK = getBacktrace();
sendToLog(0, "stacktrace:");
for (size_t i = 0; i < CALLSTACK.size(); ++i) {
sendToLog(1, std::format("\t #{} | {}", i, CALLSTACK[i].desc));
}
}
return fmtdMsg;
} }

View File

@ -402,7 +402,7 @@ void IHyprLayout::changeWindowFloatingMode(CWindow* pWindow) {
const auto TILED = isWindowTiled(pWindow); const auto TILED = isWindowTiled(pWindow);
// event // event
g_pEventManager->postEvent(SHyprIPCEvent{"changefloatingmode", getFormat("{:x},{}", (uintptr_t)pWindow, (int)TILED)}); g_pEventManager->postEvent(SHyprIPCEvent{"changefloatingmode", std::format("{:x},{}", (uintptr_t)pWindow, (int)TILED)});
EMIT_HOOK_EVENT("changeFloatingMode", pWindow); EMIT_HOOK_EVENT("changeFloatingMode", pWindow);
if (!TILED) { if (!TILED) {

View File

@ -58,8 +58,8 @@
#define RASSERT(expr, reason, ...) \ #define RASSERT(expr, reason, ...) \
if (!(expr)) { \ if (!(expr)) { \
Debug::log(CRIT, "\n==========================================================================================\nASSERTION FAILED! \n\n{}\n\nat: line {} in {}", \ Debug::log(CRIT, "\n==========================================================================================\nASSERTION FAILED! \n\n{}\n\nat: line {} in {}", \
getFormat(reason, ##__VA_ARGS__), __LINE__, \ std::format(reason, ##__VA_ARGS__), __LINE__, \
([]() constexpr->std::string { return std::string(__FILE__).substr(std::string(__FILE__).find_last_of('/') + 1); })()); \ ([]() constexpr -> std::string { return std::string(__FILE__).substr(std::string(__FILE__).find_last_of('/') + 1); })()); \
printf("Assertion failed! See the log in /tmp/hypr/hyprland.log for more info."); \ printf("Assertion failed! See the log in /tmp/hypr/hyprland.log for more info."); \
raise(SIGABRT); \ raise(SIGABRT); \
} }

View File

@ -57,7 +57,7 @@ void CHookSystemManager::emit(const std::vector<SCallbackFNPtr>* callbacks, std:
} catch (std::exception& e) { } catch (std::exception& e) {
// TODO: this works only once...? // TODO: this works only once...?
faultyHandles.push_back(cb.handle); faultyHandles.push_back(cb.handle);
Debug::log(ERR, " [hookSystem] Hook from plugin {:x} caused a SIGSEGV, queueing for unloading.", (uintptr_t)cb.handle); Debug::log(ERR, "[hookSystem] Hook from plugin {:x} caused a SIGSEGV, queueing for unloading.", (uintptr_t)cb.handle);
} }
} }
@ -73,7 +73,7 @@ std::vector<SCallbackFNPtr>* CHookSystemManager::getVecForEvent(const std::strin
if (IT != m_lpRegisteredHooks.end()) if (IT != m_lpRegisteredHooks.end())
return &IT->second; return &IT->second;
Debug::log(LOG, " [hookSystem] New hook event registered: {}", event); Debug::log(LOG, "[hookSystem] New hook event registered: {}", event);
return &m_lpRegisteredHooks.emplace_back(std::make_pair<>(event, std::vector<SCallbackFNPtr>{})).second; return &m_lpRegisteredHooks.emplace_back(std::make_pair<>(event, std::vector<SCallbackFNPtr>{})).second;
} }

View File

@ -1611,7 +1611,7 @@ bool CHyprRenderer::applyMonitorRule(CMonitor* pMonitor, SMonitorRule* pMonitorR
const auto PREFERREDMODE = wlr_output_preferred_mode(pMonitor->output); const auto PREFERREDMODE = wlr_output_preferred_mode(pMonitor->output);
if (!PREFERREDMODE) { if (!PREFERREDMODE) {
Debug::log(ERR, "Monitor {} has NO PREFERRED MODE, and an INVALID one was requested: {}x{}@{:2f}", (int)pMonitorRule->resolution.x, Debug::log(ERR, "Monitor {} has NO PREFERRED MODE, and an INVALID one was requested: {}x{}@{:2f}", pMonitor->ID, (int)pMonitorRule->resolution.x,
(int)pMonitorRule->resolution.y, (float)pMonitorRule->refreshRate); (int)pMonitorRule->resolution.y, (float)pMonitorRule->refreshRate);
return true; return true;
} }
@ -1724,7 +1724,7 @@ bool CHyprRenderer::applyMonitorRule(CMonitor* pMonitor, SMonitorRule* pMonitorR
const auto PREFERREDMODE = wlr_output_preferred_mode(pMonitor->output); const auto PREFERREDMODE = wlr_output_preferred_mode(pMonitor->output);
if (!PREFERREDMODE) { if (!PREFERREDMODE) {
Debug::log(ERR, "Monitor {} has NO PREFERRED MODE, and an INVALID one was requested: {}x{}@{:2f}", (int)pMonitorRule->resolution.x, Debug::log(ERR, "Monitor {} has NO PREFERRED MODE, and an INVALID one was requested: {}x{}@{:2f}", pMonitor->ID, (int)pMonitorRule->resolution.x,
(int)pMonitorRule->resolution.y, (float)pMonitorRule->refreshRate); (int)pMonitorRule->resolution.y, (float)pMonitorRule->refreshRate);
return true; return true;
} }