just in case

This commit is contained in:
Mars 2025-04-27 19:18:07 -04:00
parent b534cbddb0
commit 24b6a72614
Signed by: pupbrained
GPG key ID: 0FF5B8826803F895
9 changed files with 268 additions and 233 deletions

View file

@ -1,34 +1,40 @@
BasedOnStyle: Chromium
AlignAfterOpenBracket: BlockIndent AlignAfterOpenBracket: BlockIndent
AlignArrayOfStructures: Right AlignArrayOfStructures: Right
AlignConsecutiveAssignments: true AlignConsecutiveAssignments:
Enabled: true
AlignConsecutiveDeclarations:
Enabled: true
PadOperators: true
AlignConsecutiveMacros:
Enabled: true
AlignConsecutiveShortCaseStatements: AlignConsecutiveShortCaseStatements:
Enabled: true Enabled: true
AlignConsecutiveDeclarations: true
AlignOperands: DontAlign AlignOperands: DontAlign
AllowShortBlocksOnASingleLine: Always AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: true AllowShortCaseLabelsOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All AllowShortFunctionsOnASingleLine: All
AllowShortLoopsOnASingleLine: true AllowShortLoopsOnASingleLine: true
BasedOnStyle: Chromium
BinPackArguments: false BinPackArguments: false
BinPackParameters: false
ColumnLimit: 120 ColumnLimit: 120
ConstructorInitializerIndentWidth: 2 ConstructorInitializerIndentWidth: 2
ContinuationIndentWidth: 2 ContinuationIndentWidth: 2
Cpp11BracedListStyle: false Cpp11BracedListStyle: false
FixNamespaceComments: false
IndentAccessModifiers: false
IndentExternBlock: Indent
IndentWidth: 2
NamespaceIndentation: All
SpaceBeforeCpp11BracedList: true
SpacesBeforeTrailingComments: 1
QualifierAlignment: Left
IncludeBlocks: Regroup IncludeBlocks: Regroup
IncludeCategories: IncludeCategories:
- Regex: '".*"' # 1. System headers (<iostream>, <vector>, etc.)
- Regex: '^<.*>$'
Priority: 1 Priority: 1
- Regex: '<.*>' # 2. Project headers starting with "src/"
Priority: -1 - Regex: '^"src/.*"'
Priority: 2
# 3. All other quoted headers (including same-directory like "system_data.h")
# This acts as a fallback for quoted includes not matching the above.
- Regex: '^".*"'
Priority: 3
IndentExternBlock: Indent
IndentPPDirectives: BeforeHash
NamespaceIndentation: All
QualifierAlignment: Left
SpaceBeforeCpp11BracedList: true
SpacesBeforeTrailingComments: 1

View file

@ -1,4 +1,3 @@
# noinspection SpellCheckingInspection
Checks: > Checks: >
*, *,
-ctad-maybe-unsupported, -ctad-maybe-unsupported,
@ -23,7 +22,6 @@ Checks: >
-llvm-namespace-comment, -llvm-namespace-comment,
-llvmlibc-*, -llvmlibc-*,
-misc-non-private-member-variables-in-classes, -misc-non-private-member-variables-in-classes,
-modernize-use-nullptr,
-readability-avoid-nested-conditional-operator, -readability-avoid-nested-conditional-operator,
-readability-braces-around-statements, -readability-braces-around-statements,
-readability-function-cognitive-complexity, -readability-function-cognitive-complexity,

View file

@ -124,6 +124,7 @@
bear bear
llvmPackages.clang-tools llvmPackages.clang-tools
cmake cmake
include-what-you-use
lldb lldb
hyperfine hyperfine
meson meson

View file

@ -1,9 +1,15 @@
#include <future>
#include "system_data.h" #include "system_data.h"
#include "src/config/config.h" #include <chrono> // for year_month_day, floor, days...
#include "src/os/os.h" #include <exception> // for exception
#include <future> // for future, async, launch
#include <locale> // for locale
#include <stdexcept> // for runtime_error
#include <tuple> // for tuple, get, make_tuple
#include <utility> // for move
#include "src/config/config.h" // for Config, Weather, NowPlaying
#include "src/os/os.h" // for GetDesktopEnvironment, GetHost...
namespace { namespace {
fn GetDate() -> String { fn GetDate() -> String {
@ -18,7 +24,7 @@ namespace {
return std::format(std::locale::classic(), "{:%B %d}", ymd); return std::format(std::locale::classic(), "{:%B %d}", ymd);
} }
} }
} } // namespace
SystemData SystemData::fetchSystemData(const Config& config) { SystemData SystemData::fetchSystemData(const Config& config) {
SystemData data { SystemData data {

View file

@ -1,7 +1,14 @@
#pragma once #pragma once
#include "src/config/config.h" #include <format> // for formatter, format_to
#include "src/util/types.h" #include <string> // for basic_string
#include <thread> // for formatter
#include "src/config/weather.h" // for WeatherOutput
#include "src/util/macros.h" // for fn
#include "src/util/types.h" // for OsError, DiskSpace, Result, String
struct Config;
/** /**
* @struct BytesToGiB * @struct BytesToGiB

View file

@ -4,7 +4,6 @@
#include <ftxui/screen/screen.hpp> #include <ftxui/screen/screen.hpp>
#include <future> #include <future>
#include <string> #include <string>
#include <utility>
#include <variant> #include <variant>
#include "config/config.h" #include "config/config.h"
@ -79,7 +78,7 @@ namespace ui {
.desktop = " 󰇄 ", .desktop = " 󰇄 ",
.window_manager = "  ", .window_manager = "  ",
}; };
} } // namespace ui
namespace { namespace {
using namespace ftxui; using namespace ftxui;
@ -173,24 +172,23 @@ namespace {
if (data.host) if (data.host)
content.push_back(createRow(hostIcon, "Host", *data.host)); content.push_back(createRow(hostIcon, "Host", *data.host));
else else
ERROR_LOG("Failed to get host info: {}", data.host.error().message); ERROR_LOG_LOC(data.host.error());
if (data.kernel_version) if (data.kernel_version)
content.push_back(createRow(kernelIcon, "Kernel", *data.kernel_version)); content.push_back(createRow(kernelIcon, "Kernel", *data.kernel_version));
else else
ERROR_LOG("Failed to get kernel version: {}", data.kernel_version.error().message); ERROR_LOG_LOC(data.kernel_version.error());
if (data.os_version) if (data.os_version)
content.push_back(createRow(String(osIcon), "OS", *data.os_version)); content.push_back(createRow(String(osIcon), "OS", *data.os_version));
else else
ERROR_LOG("Failed to get OS version: {}", data.os_version.error().message); ERROR_LOG_LOC(data.os_version.error());
if (data.mem_info) if (data.mem_info)
content.push_back(createRow(memoryIcon, "RAM", std::format("{}", BytesToGiB { *data.mem_info }))); content.push_back(createRow(memoryIcon, "RAM", std::format("{}", BytesToGiB { *data.mem_info })));
else else
ERROR_LOG("Failed to get memory info: {}", data.mem_info.error().message); ERROR_LOG_LOC(data.mem_info.error());
// Add Disk usage row
if (data.disk_usage) if (data.disk_usage)
content.push_back(createRow( content.push_back(createRow(
diskIcon, diskIcon,
@ -198,7 +196,7 @@ namespace {
std::format("{}/{}", BytesToGiB { data.disk_usage->used_bytes }, BytesToGiB { data.disk_usage->total_bytes }) std::format("{}/{}", BytesToGiB { data.disk_usage->used_bytes }, BytesToGiB { data.disk_usage->total_bytes })
)); ));
else else
ERROR_LOG("Failed to get disk usage: {}", data.disk_usage.error().message); ERROR_LOG_LOC(data.disk_usage.error());
if (data.shell) if (data.shell)
content.push_back(createRow(shellIcon, "Shell", *data.shell)); content.push_back(createRow(shellIcon, "Shell", *data.shell));
@ -230,20 +228,13 @@ namespace {
text(" "), text(" "),
} }
)); ));
} else {
if (const NowPlayingError& error = nowPlayingResult.error(); std::holds_alternative<NowPlayingCode>(error)) {
switch (std::get<NowPlayingCode>(error)) {
case NowPlayingCode::NoPlayers: DEBUG_LOG("No players found"); break;
case NowPlayingCode::NoActivePlayer: DEBUG_LOG("No active player found"); break;
}
} else } else
ERROR_LOG("Failed to get now playing info: {}", std::get<OsError>(error).message); DEBUG_LOG_LOC(nowPlayingResult.error());
}
} }
return vbox(content) | borderRounded | color(Color::White); return vbox(content) | borderRounded | color(Color::White);
} }
} } // namespace
fn main() -> i32 { fn main() -> i32 {
const Config& config = Config::getInstance(); const Config& config = Config::getInstance();

View file

@ -2,14 +2,12 @@
// clang-format off // clang-format off
#include <dbus-cxx.h> // needs to be at top for Success/None #include <dbus-cxx.h> // needs to be at top for Success/None
// clang-format on
#include <cstring> #include <cstring>
#include <fstream> #include <fstream>
#include <sys/socket.h> #include <sys/socket.h>
#include <sys/statvfs.h> #include <sys/statvfs.h>
#include <sys/sysinfo.h> #include <sys/sysinfo.h>
#include <sys/utsname.h> #include <sys/utsname.h>
#include <system_error>
#include <unistd.h> #include <unistd.h>
#include <wayland-client.h> #include <wayland-client.h>
#include <xcb/xcb.h> #include <xcb/xcb.h>
@ -18,44 +16,11 @@
#include "src/os/linux/display_guards.h" #include "src/os/linux/display_guards.h"
#include "src/util/macros.h" #include "src/util/macros.h"
#include "src/util/types.h" #include "src/util/types.h"
// clang-format on
using namespace std::string_view_literals; using namespace std::string_view_literals;
namespace { namespace {
fn MakeOsErrorFromDBus(const DBus::Error& err) -> OsError {
String name = err.name();
if (name == "org.freedesktop.DBus.Error.ServiceUnknown" || name == "org.freedesktop.DBus.Error.NameHasNoOwner")
return OsError { OsErrorCode::NotFound, std::format("DBus service/name not found: {}", err.message()) };
if (name == "org.freedesktop.DBus.Error.NoReply" || name == "org.freedesktop.DBus.Error.Timeout")
return OsError { OsErrorCode::Timeout, std::format("DBus timeout/no reply: {}", err.message()) };
if (name == "org.freedesktop.DBus.Error.AccessDenied")
return OsError { OsErrorCode::PermissionDenied, std::format("DBus access denied: {}", err.message()) };
return OsError { OsErrorCode::PlatformSpecific, std::format("DBus error: {} - {}", name, err.message()) };
}
fn MakeOsErrorFromErrno(const String& context = "") -> OsError {
const i32 errNo = errno;
const String msg = std::system_category().message(errNo);
const String fullMsg = context.empty() ? msg : std::format("{}: {}", context, msg);
switch (errNo) {
case EACCES:
case EPERM: return OsError { OsErrorCode::PermissionDenied, fullMsg };
case ENOENT: return OsError { OsErrorCode::NotFound, fullMsg };
case ETIMEDOUT: return OsError { OsErrorCode::Timeout, fullMsg };
case ENOTSUP: return OsError { OsErrorCode::NotSupported, fullMsg };
case EIO: return OsError { OsErrorCode::IoError, fullMsg };
case ECONNREFUSED:
case ENETDOWN:
case ENETUNREACH: return OsError { OsErrorCode::NetworkError, fullMsg };
default: return OsError { OsErrorCode::PlatformSpecific, fullMsg };
}
}
fn GetX11WindowManager() -> Result<String, OsError> { fn GetX11WindowManager() -> Result<String, OsError> {
using os::linux::XcbReplyGuard; using os::linux::XcbReplyGuard;
using os::linux::XorgDisplayGuard; using os::linux::XorgDisplayGuard;
@ -64,10 +29,7 @@ namespace {
if (!conn) if (!conn)
if (const i32 err = xcb_connection_has_error(conn.get()); !conn || err != 0) if (const i32 err = xcb_connection_has_error(conn.get()); !conn || err != 0)
return Err( return Err(OsError(OsErrorCode::ApiUnavailable, [&] -> String {
OsError {
OsErrorCode::ApiUnavailable,
[&] -> String {
switch (err) { switch (err) {
case 0: return "Connection object invalid, but no specific XCB error code"; case 0: return "Connection object invalid, but no specific XCB error code";
case XCB_CONN_ERROR: return "Stream/Socket/Pipe Error"; case XCB_CONN_ERROR: return "Stream/Socket/Pipe Error";
@ -79,9 +41,7 @@ namespace {
case XCB_CONN_CLOSED_FDPASSING_FAILED: return "Closed: FD Passing Failed"; case XCB_CONN_CLOSED_FDPASSING_FAILED: return "Closed: FD Passing Failed";
default: return std::format("Unknown Error Code ({})", err); default: return std::format("Unknown Error Code ({})", err);
} }
}(), }()));
}
);
fn internAtom = [&conn](const StringView name) -> Result<xcb_atom_t, OsError> { fn internAtom = [&conn](const StringView name) -> Result<xcb_atom_t, OsError> {
const XcbReplyGuard<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply( const XcbReplyGuard<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(
@ -89,9 +49,7 @@ namespace {
)); ));
if (!reply) if (!reply)
return Err( return Err(OsError(OsErrorCode::PlatformSpecific, std::format("Failed to get X11 atom reply for '{}'", name)));
OsError { OsErrorCode::PlatformSpecific, std::format("Failed to get X11 atom reply for '{}'", name) }
);
return reply->atom; return reply->atom;
}; };
@ -110,7 +68,7 @@ namespace {
if (!utf8StringAtom) if (!utf8StringAtom)
ERROR_LOG("Failed to get UTF8_STRING atom"); ERROR_LOG("Failed to get UTF8_STRING atom");
return Err(OsError { OsErrorCode::PlatformSpecific, "Failed to get X11 atoms" }); return Err(OsError(OsErrorCode::PlatformSpecific, "Failed to get X11 atoms"));
} }
const XcbReplyGuard<xcb_get_property_reply_t> wmWindowReply(xcb_get_property_reply( const XcbReplyGuard<xcb_get_property_reply_t> wmWindowReply(xcb_get_property_reply(
@ -121,7 +79,7 @@ namespace {
if (!wmWindowReply || wmWindowReply->type != XCB_ATOM_WINDOW || wmWindowReply->format != 32 || if (!wmWindowReply || wmWindowReply->type != XCB_ATOM_WINDOW || wmWindowReply->format != 32 ||
xcb_get_property_value_length(wmWindowReply.get()) == 0) xcb_get_property_value_length(wmWindowReply.get()) == 0)
return Err(OsError { OsErrorCode::NotFound, "Failed to get _NET_SUPPORTING_WM_CHECK property" }); return Err(OsError(OsErrorCode::NotFound, "Failed to get _NET_SUPPORTING_WM_CHECK property"));
const xcb_window_t wmRootWindow = *static_cast<xcb_window_t*>(xcb_get_property_value(wmWindowReply.get())); const xcb_window_t wmRootWindow = *static_cast<xcb_window_t*>(xcb_get_property_value(wmWindowReply.get()));
@ -130,7 +88,7 @@ namespace {
)); ));
if (!wmNameReply || wmNameReply->type != *utf8StringAtom || xcb_get_property_value_length(wmNameReply.get()) == 0) if (!wmNameReply || wmNameReply->type != *utf8StringAtom || xcb_get_property_value_length(wmNameReply.get()) == 0)
return Err(OsError { OsErrorCode::NotFound, "Failed to get _NET_WM_NAME property" }); return Err(OsError(OsErrorCode::NotFound, "Failed to get _NET_WM_NAME property"));
const char* nameData = static_cast<const char*>(xcb_get_property_value(wmNameReply.get())); const char* nameData = static_cast<const char*>(xcb_get_property_value(wmNameReply.get()));
const usize length = xcb_get_property_value_length(wmNameReply.get()); const usize length = xcb_get_property_value_length(wmNameReply.get());
@ -144,24 +102,24 @@ namespace {
const WaylandDisplayGuard display; const WaylandDisplayGuard display;
if (!display) if (!display)
return Err(OsError { OsErrorCode::NotFound, "Failed to connect to display (is Wayland running?)" }); return Err(OsError(OsErrorCode::NotFound, "Failed to connect to display (is Wayland running?)"));
const i32 fileDescriptor = display.fd(); const i32 fileDescriptor = display.fd();
if (fileDescriptor < 0) if (fileDescriptor < 0)
return Err(OsError { OsErrorCode::ApiUnavailable, "Failed to get Wayland file descriptor" }); return Err(OsError(OsErrorCode::ApiUnavailable, "Failed to get Wayland file descriptor"));
ucred cred; ucred cred;
socklen_t len = sizeof(cred); socklen_t len = sizeof(cred);
if (getsockopt(fileDescriptor, SOL_SOCKET, SO_PEERCRED, &cred, &len) == -1) if (getsockopt(fileDescriptor, SOL_SOCKET, SO_PEERCRED, &cred, &len) == -1)
return Err(MakeOsErrorFromErrno("Failed to get socket credentials (SO_PEERCRED)")); return Err(OsError::withErrno("Failed to get socket credentials (SO_PEERCRED)"));
Array<char, 128> exeLinkPathBuf; Array<char, 128> exeLinkPathBuf;
auto [out, size] = std::format_to_n(exeLinkPathBuf.data(), exeLinkPathBuf.size() - 1, "/proc/{}/exe", cred.pid); auto [out, size] = std::format_to_n(exeLinkPathBuf.data(), exeLinkPathBuf.size() - 1, "/proc/{}/exe", cred.pid);
if (out >= exeLinkPathBuf.data() + exeLinkPathBuf.size() - 1) if (out >= exeLinkPathBuf.data() + exeLinkPathBuf.size() - 1)
return Err(OsError { OsErrorCode::InternalError, "Failed to format /proc path (PID too large?)" }); return Err(OsError(OsErrorCode::InternalError, "Failed to format /proc path (PID too large?)"));
*out = '\0'; *out = '\0';
@ -172,7 +130,7 @@ namespace {
const isize bytesRead = readlink(exeLinkPath, exeRealPathBuf.data(), exeRealPathBuf.size() - 1); const isize bytesRead = readlink(exeLinkPath, exeRealPathBuf.data(), exeRealPathBuf.size() - 1);
if (bytesRead == -1) if (bytesRead == -1)
return Err(MakeOsErrorFromErrno(std::format("Failed to read link '{}'", exeLinkPath))); return Err(OsError::withErrno(std::format("Failed to read link '{}'", exeLinkPath)));
exeRealPathBuf.at(bytesRead) = '\0'; exeRealPathBuf.at(bytesRead) = '\0';
@ -195,7 +153,7 @@ namespace {
compositorNameView = filenameView; compositorNameView = filenameView;
if (compositorNameView.empty() || compositorNameView == "." || compositorNameView == "/") if (compositorNameView.empty() || compositorNameView == "." || compositorNameView == "/")
return Err(OsError { OsErrorCode::NotFound, "Failed to get compositor name from path" }); return Err(OsError(OsErrorCode::NotFound, "Failed to get compositor name from path"));
if (constexpr StringView wrappedSuffix = "-wrapped"; compositorNameView.length() > 1 + wrappedSuffix.length() && if (constexpr StringView wrappedSuffix = "-wrapped"; compositorNameView.length() > 1 + wrappedSuffix.length() &&
compositorNameView[0] == '.' && compositorNameView.ends_with(wrappedSuffix)) { compositorNameView[0] == '.' && compositorNameView.ends_with(wrappedSuffix)) {
@ -203,7 +161,7 @@ namespace {
compositorNameView.substr(1, compositorNameView.length() - 1 - wrappedSuffix.length()); compositorNameView.substr(1, compositorNameView.length() - 1 - wrappedSuffix.length());
if (cleanedView.empty()) if (cleanedView.empty())
return Err(OsError { OsErrorCode::NotFound, "Compositor name invalid after heuristic" }); return Err(OsError(OsErrorCode::NotFound, "Compositor name invalid after heuristic"));
return String(cleanedView); return String(cleanedView);
} }
@ -219,7 +177,7 @@ namespace {
const SharedPointer<DBus::Message> reply = connection->send_with_reply_blocking(call, 5); const SharedPointer<DBus::Message> reply = connection->send_with_reply_blocking(call, 5);
if (!reply || !reply->is_valid()) if (!reply || !reply->is_valid())
return Err(OsError { OsErrorCode::Timeout, "Failed to get reply from ListNames" }); return Err(OsError(OsErrorCode::Timeout, "Failed to get reply from ListNames"));
Vec<String> allNamesStd; Vec<String> allNamesStd;
DBus::MessageIterator reader(*reply); DBus::MessageIterator reader(*reply);
@ -229,9 +187,9 @@ namespace {
if (StringView(name).contains("org.mpris.MediaPlayer2"sv)) if (StringView(name).contains("org.mpris.MediaPlayer2"sv))
return name; return name;
return Err(OsError { OsErrorCode::NotFound, "No MPRIS players found" }); return Err(OsError(OsErrorCode::NotFound, "No MPRIS players found"));
} catch (const DBus::Error& e) { return Err(MakeOsErrorFromDBus(e)); } catch (const Exception& e) { } catch (const DBus::Error& e) { return Err(OsError::fromDBus(e)); } catch (const Exception& e) {
return Err(OsError { OsErrorCode::InternalError, e.what() }); return Err(OsError(OsErrorCode::InternalError, e.what()));
} }
} }
@ -246,7 +204,7 @@ namespace {
const SharedPointer<DBus::Message> metadataReply = connection->send_with_reply_blocking(metadataCall, 1000); const SharedPointer<DBus::Message> metadataReply = connection->send_with_reply_blocking(metadataCall, 1000);
if (!metadataReply || !metadataReply->is_valid()) { if (!metadataReply || !metadataReply->is_valid()) {
return Err(OsError { OsErrorCode::Timeout, "DBus Get Metadata call timed out or received invalid reply" }); return Err(OsError(OsErrorCode::Timeout, "DBus Get Metadata call timed out or received invalid reply"));
} }
DBus::MessageIterator iter(*metadataReply); DBus::MessageIterator iter(*metadataReply);
@ -255,15 +213,13 @@ namespace {
// MPRIS metadata is variant containing a dict a{sv} // MPRIS metadata is variant containing a dict a{sv}
if (metadataVariant.type() != DBus::DataType::DICT_ENTRY && metadataVariant.type() != DBus::DataType::ARRAY) { if (metadataVariant.type() != DBus::DataType::DICT_ENTRY && metadataVariant.type() != DBus::DataType::ARRAY) {
return Err( return Err(OsError(
OsError {
OsErrorCode::ParseError, OsErrorCode::ParseError,
std::format( std::format(
"Inner metadata variant is not the expected type, expected dict/a{{sv}} but got '{}'", "Inner metadata variant is not the expected type, expected dict/a{{sv}} but got '{}'",
metadataVariant.signature().str() metadataVariant.signature().str()
), )
} ));
);
} }
Map<String, DBus::Variant> metadata = metadataVariant.to_map<String, DBus::Variant>(); // Can throw Map<String, DBus::Variant> metadata = metadataVariant.to_map<String, DBus::Variant>(); // Can throw
@ -307,13 +263,13 @@ namespace {
} }
return MediaInfo(std::move(title), std::move(artist), std::move(album), std::move(appName)); return MediaInfo(std::move(title), std::move(artist), std::move(album), std::move(appName));
} catch (const DBus::Error& e) { return Err(MakeOsErrorFromDBus(e)); } catch (const Exception& e) { } catch (const DBus::Error& e) { return Err(OsError::fromDBus(e)); } catch (const Exception& e) {
return Err( return Err(
OsError { OsErrorCode::InternalError, std::format("Standard exception processing metadata: {}", e.what()) } OsError(OsErrorCode::InternalError, std::format("Standard exception processing metadata: {}", e.what()))
); );
} }
} }
} } // namespace
fn os::GetOSVersion() -> Result<String, OsError> { fn os::GetOSVersion() -> Result<String, OsError> {
constexpr CStr path = "/etc/os-release"; constexpr CStr path = "/etc/os-release";
@ -321,7 +277,7 @@ fn os::GetOSVersion() -> Result<String, OsError> {
std::ifstream file(path); std::ifstream file(path);
if (!file) if (!file)
return Err(OsError { OsErrorCode::NotFound, std::format("Failed to open {}", path) }); return Err(OsError(OsErrorCode::NotFound, std::format("Failed to open {}", path)));
String line; String line;
constexpr StringView prefix = "PRETTY_NAME="; constexpr StringView prefix = "PRETTY_NAME=";
@ -336,30 +292,30 @@ fn os::GetOSVersion() -> Result<String, OsError> {
if (value.empty()) if (value.empty())
return Err( return Err(
OsError { OsErrorCode::ParseError, std::format("PRETTY_NAME value is empty or only quotes in {}", path) } OsError(OsErrorCode::ParseError, std::format("PRETTY_NAME value is empty or only quotes in {}", path))
); );
return value; return value;
} }
} }
return Err(OsError { OsErrorCode::NotFound, std::format("PRETTY_NAME line not found in {}", path) }); return Err(OsError(OsErrorCode::NotFound, std::format("PRETTY_NAME line not found in {}", path)));
} }
fn os::GetMemInfo() -> Result<u64, OsError> { fn os::GetMemInfo() -> Result<u64, OsError> {
struct sysinfo info; struct sysinfo info;
if (sysinfo(&info) != 0) if (sysinfo(&info) != 0)
return Err(MakeOsErrorFromErrno("sysinfo call failed")); return Err(OsError::fromDBus("sysinfo call failed"));
const u64 totalRam = info.totalram; const u64 totalRam = info.totalram;
const u64 memUnit = info.mem_unit; const u64 memUnit = info.mem_unit;
if (memUnit == 0) if (memUnit == 0)
return Err(OsError { OsErrorCode::InternalError, "sysinfo returned mem_unit of zero" }); return Err(OsError(OsErrorCode::InternalError, "sysinfo returned mem_unit of zero"));
if (totalRam > std::numeric_limits<u64>::max() / memUnit) if (totalRam > std::numeric_limits<u64>::max() / memUnit)
return Err(OsError { OsErrorCode::InternalError, "Potential overflow calculating total RAM" }); return Err(OsError(OsErrorCode::InternalError, "Potential overflow calculating total RAM"));
return info.totalram * info.mem_unit; return info.totalram * info.mem_unit;
} }
@ -374,14 +330,14 @@ fn os::GetNowPlaying() -> Result<MediaInfo, NowPlayingError> {
dispatcher = DBus::StandaloneDispatcher::create(); dispatcher = DBus::StandaloneDispatcher::create();
if (!dispatcher) if (!dispatcher)
return Err(OsError { OsErrorCode::ApiUnavailable, "Failed to create DBus dispatcher" }); return Err(OsError(OsErrorCode::ApiUnavailable, "Failed to create DBus dispatcher"));
connection = dispatcher->create_connection(DBus::BusType::SESSION); connection = dispatcher->create_connection(DBus::BusType::SESSION);
if (!connection) if (!connection)
return Err(OsError { OsErrorCode::ApiUnavailable, "Failed to connect to DBus session bus" }); return Err(OsError(OsErrorCode::ApiUnavailable, "Failed to connect to DBus session bus"));
} catch (const DBus::Error& e) { return Err(MakeOsErrorFromDBus(e)); } catch (const Exception& e) { } catch (const DBus::Error& e) { return Err(OsError::fromDBus(e)); } catch (const Exception& e) {
return Err(OsError { OsErrorCode::InternalError, e.what() }); return Err(OsError(OsErrorCode::InternalError, e.what()));
} }
Result<String, NowPlayingError> playerBusName = GetMprisPlayers(connection); Result<String, NowPlayingError> playerBusName = GetMprisPlayers(connection);
@ -458,20 +414,17 @@ fn os::GetHost() -> Result<String, OsError> {
String line; String line;
if (!file) if (!file)
return Err( return Err(OsError(OsErrorCode::NotFound, std::format("Failed to open DMI product identifier file '{}'", path)));
OsError { OsErrorCode::NotFound, std::format("Failed to open DMI product identifier file '{}'", path) }
);
if (!getline(file, line)) if (!getline(file, line))
return Err(OsError { OsErrorCode::ParseError, std::format("DMI product identifier file ('{}') is empty", path) }); return Err(OsError(OsErrorCode::ParseError, std::format("DMI product identifier file ('{}') is empty", path)));
return line; return line;
}; };
return readFirstLine(primaryPath).or_else([&](const OsError& primaryError) -> Result<String, OsError> { return readFirstLine(primaryPath).or_else([&](const OsError& primaryError) -> Result<String, OsError> {
return readFirstLine(fallbackPath).or_else([&](const OsError& fallbackError) -> Result<String, OsError> { return readFirstLine(fallbackPath).or_else([&](const OsError& fallbackError) -> Result<String, OsError> {
return Err( return Err(OsError(
OsError {
OsErrorCode::InternalError, OsErrorCode::InternalError,
std::format( std::format(
"Failed to get host identifier. Primary ('{}'): {}. Fallback ('{}'): {}", "Failed to get host identifier. Primary ('{}'): {}. Fallback ('{}'): {}",
@ -479,9 +432,8 @@ fn os::GetHost() -> Result<String, OsError> {
primaryError.message, primaryError.message,
fallbackPath, fallbackPath,
fallbackError.message fallbackError.message
), )
} ));
);
}); });
}); });
} }
@ -490,10 +442,10 @@ fn os::GetKernelVersion() -> Result<String, OsError> {
utsname uts; utsname uts;
if (uname(&uts) == -1) if (uname(&uts) == -1)
return Err(MakeOsErrorFromErrno("uname call failed")); return Err(OsError::withErrno("uname call failed"));
if (strlen(uts.release) == 0) if (strlen(uts.release) == 0)
return Err(OsError { OsErrorCode::ParseError, "uname returned null kernel release" }); return Err(OsError(OsErrorCode::ParseError, "uname returned null kernel release"));
return uts.release; return uts.release;
} }
@ -502,7 +454,7 @@ fn os::GetDiskUsage() -> Result<DiskSpace, OsError> {
struct statvfs stat; struct statvfs stat;
if (statvfs("/", &stat) == -1) if (statvfs("/", &stat) == -1)
return Err(MakeOsErrorFromErrno(std::format("Failed to get filesystem stats for '/' (statvfs call failed)"))); return Err(OsError::withErrno(std::format("Failed to get filesystem stats for '/' (statvfs call failed)")));
return DiskSpace { return DiskSpace {
.used_bytes = (stat.f_blocks * stat.f_frsize) - (stat.f_bfree * stat.f_frsize), .used_bytes = (stat.f_blocks * stat.f_frsize) - (stat.f_bfree * stat.f_frsize),
@ -510,4 +462,4 @@ fn os::GetDiskUsage() -> Result<DiskSpace, OsError> {
}; };
} }
#endif #endif // __linux__

View file

@ -1,10 +1,9 @@
// ReSharper disable CppDFAConstantParameter
#pragma once #pragma once
// Fixes conflict in Windows with <windows.h> // Fixes conflict in Windows with <windows.h>
#ifdef _WIN32 #ifdef _WIN32
#undef ERROR #undef ERROR
#endif #endif // _WIN32
#include <chrono> #include <chrono>
#include <filesystem> #include <filesystem>
@ -117,9 +116,11 @@ namespace term {
* @param fgColor The foreground color to apply. * @param fgColor The foreground color to apply.
* @return The combined style. * @return The combined style.
*/ */
// ReSharper disable CppDFAConstantParameter
constexpr fn operator|(const Emphasis emph, const Color fgColor)->Style { constexpr fn operator|(const Emphasis emph, const Color fgColor)->Style {
return { .emph = emph, .fg_col = fgColor }; return { .emph = emph, .fg_col = fgColor };
} }
// ReSharper restore CppDFAConstantParameter
/** /**
* @brief Combines a foreground color and an emphasis style into a Style. * @brief Combines a foreground color and an emphasis style into a Style.
@ -181,7 +182,7 @@ namespace term {
// Directly use std::print for unstyled output // Directly use std::print for unstyled output
std::print(fmt, std::forward<Args>(args)...); std::print(fmt, std::forward<Args>(args)...);
} }
} } // namespace term
/** /**
* @enum LogLevel * @enum LogLevel
@ -201,11 +202,12 @@ template <typename... Args>
fn LogImpl(const LogLevel level, const std::source_location& loc, std::format_string<Args...> fmt, Args&&... args) { fn LogImpl(const LogLevel level, const std::source_location& loc, std::format_string<Args...> fmt, Args&&... args) {
using namespace std::chrono; using namespace std::chrono;
using namespace term; using namespace term;
#ifdef _WIN32
#ifdef _MSC_VER
using enum term::Color; using enum term::Color;
#else #else
using enum Color; using enum Color;
#endif #endif // _MSC_VER
const auto [color, levelStr] = [&] { const auto [color, levelStr] = [&] {
switch (level) { switch (level) {
@ -229,19 +231,62 @@ fn LogImpl(const LogLevel level, const std::source_location& loc, std::format_st
std::filesystem::path(loc.file_name()).lexically_normal().string(), std::filesystem::path(loc.file_name()).lexically_normal().string(),
loc.line() loc.line()
); );
#endif #endif // !NDEBUG
Print("\n"); Print("\n");
} }
namespace detail {
template <typename ErrorType>
fn LogAppError(const LogLevel level, const ErrorType& error_obj) {
using DecayedErrorType = std::decay_t<ErrorType>;
std::source_location log_location = std::source_location::current();
String error_message_part;
LogLevel final_log_level = level;
if constexpr (std::is_same_v<DecayedErrorType, OsError>) {
log_location = error_obj.location;
error_message_part = error_obj.message;
} else if constexpr (std::is_same_v<DecayedErrorType, NowPlayingError>) {
if (std::holds_alternative<OsError>(error_obj)) {
const OsError& osErr = std::get<OsError>(error_obj);
log_location = osErr.location;
error_message_part = osErr.message;
} else if (std::holds_alternative<NowPlayingCode>(error_obj)) {
const NowPlayingCode npCode = std::get<NowPlayingCode>(error_obj);
log_location = std::source_location::current();
final_log_level = LogLevel::DEBUG;
switch (npCode) {
case NowPlayingCode::NoPlayers: error_message_part = "No media players found"; break;
case NowPlayingCode::NoActivePlayer: error_message_part = "No active media player found"; break;
default: error_message_part = "Unknown NowPlayingCode"; break;
}
}
} else {
log_location = std::source_location::current();
if constexpr (std::is_base_of_v<std::exception, DecayedErrorType>)
error_message_part = error_obj.what();
else if constexpr (requires { error_obj.message; })
error_message_part = error_obj.message;
else
error_message_part = "Unknown error type logged";
}
LogImpl(final_log_level, log_location, "{}", error_message_part);
}
} // namespace detail
// Suppress unused macro warnings in Clang // Suppress unused macro warnings in Clang
#ifdef __clang__ #ifdef __clang__
#pragma clang diagnostic push #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-macros" #pragma clang diagnostic ignored "-Wunused-macros"
#endif #endif // __clang__
#ifdef NDEBUG #ifdef NDEBUG
#define DEBUG_LOG(...) static_cast<void>(0) #define DEBUG_LOG(...) static_cast<void>(0)
#define DEBUG_LOG_LOC(...) static_cast<void>(0)
#else #else
/** /**
* @def DEBUG_LOG * @def DEBUG_LOG
@ -251,7 +296,17 @@ fn LogImpl(const LogLevel level, const std::source_location& loc, std::format_st
* @param ... Format string and arguments for the log message. * @param ... Format string and arguments for the log message.
*/ */
#define DEBUG_LOG(...) LogImpl(LogLevel::DEBUG, std::source_location::current(), __VA_ARGS__) #define DEBUG_LOG(...) LogImpl(LogLevel::DEBUG, std::source_location::current(), __VA_ARGS__)
#endif /**
* @def DEBUG_LOG_LOC(error_obj)
* @brief Logs an application-specific error at the DEBUG level, using its stored location if available.
* @details Only active in non-release builds (when NDEBUG is not defined).
* @param error_obj The error object (e.g., OsError, NowPlayingError).
*/
#define DEBUG_LOG_LOC(error_obj) \
do { \
[&](const auto& err) { detail::LogAppError(LogLevel::DEBUG, err); }(error_obj); \
} while (0)
#endif // NDEBUG
/** /**
* @def INFO_LOG(...) * @def INFO_LOG(...)
@ -278,17 +333,15 @@ fn LogImpl(const LogLevel level, const std::source_location& loc, std::format_st
#define ERROR_LOG(...) LogImpl(LogLevel::ERROR, std::source_location::current(), __VA_ARGS__) #define ERROR_LOG(...) LogImpl(LogLevel::ERROR, std::source_location::current(), __VA_ARGS__)
/** /**
* @def RETURN_ERR(...) * @def ERROR_LOG_LOC(error_obj)
* @brief Logs an error message and returns a value. * @brief Logs an application-specific error at the ERROR level, using its stored location if available.
* @details Logs the error message with the ERROR log level and returns the specified value. * @param error_obj The error object (e.g., OsError, NowPlayingError).
* @param ... Format string and arguments for the error message.
*/ */
#define RETURN_ERR(...) \ #define ERROR_LOG_LOC(error_obj) \
do { \ do { \
ERROR_LOG(__VA_ARGS__); \ [&](const auto& err) { detail::LogAppError(LogLevel::ERROR, err); }(error_obj); \
return None; \
} while (0) } while (0)
#ifdef __clang__ #ifdef __clang__
#pragma clang diagnostic pop #pragma clang diagnostic pop
#endif #endif // __clang__

View file

@ -7,6 +7,7 @@
#include <map> // std::map alias (Map) #include <map> // std::map alias (Map)
#include <memory> // std::shared_ptr and std::unique_ptr aliases (SharedPointer, UniquePointer) #include <memory> // std::shared_ptr and std::unique_ptr aliases (SharedPointer, UniquePointer)
#include <optional> // std::optional alias (Option) #include <optional> // std::optional alias (Option)
#include <source_location> // std::source_location
#include <string> // std::string and std::string_view aliases (String, StringView) #include <string> // std::string and std::string_view aliases (String, StringView)
#include <system_error> // std::error_code and std::system_error #include <system_error> // std::error_code and std::system_error
#include <utility> // std::pair alias (Pair) #include <utility> // std::pair alias (Pair)
@ -14,7 +15,9 @@
#include <vector> // std::vector alias (Vec) #include <vector> // std::vector alias (Vec)
#ifdef _WIN32 #ifdef _WIN32
#include <winrt/base.h> // winrt::hresult_error (WindowsError) #include <winrt/base.h> // winrt::hresult_error
#elifdef __linux__
#include <dbus-cxx.h> // DBus::Error
#endif #endif
//----------------------------------------------------------------// //----------------------------------------------------------------//
@ -182,14 +185,20 @@ enum class OsErrorCode : u8 {
* Used as the error type in Result for many os:: functions. * Used as the error type in Result for many os:: functions.
*/ */
struct OsError { struct OsError {
String message = "Unknown Error"; ///< A descriptive error message, potentially including platform details. // ReSharper disable CppDFANotInitializedField
OsErrorCode code = OsErrorCode::Other; ///< The general category of the error. String message; ///< A descriptive error message, potentially including platform details.
OsErrorCode code; ///< The general category of the error.
std::source_location location; ///< The source location where the error occurred (file, line, function).
// ReSharper restore CppDFANotInitializedField
OsError(const OsErrorCode errc, String msg) : message(std::move(msg)), code(errc) {} OsError(const OsErrorCode errc, String msg, const std::source_location& loc = std::source_location::current())
: message(std::move(msg)), code(errc), location(loc) {}
explicit OsError(const Exception& exc) : message(exc.what()) {} explicit OsError(const Exception& exc, const std::source_location& loc = std::source_location::current())
: message(exc.what()), code(OsErrorCode::InternalError), location(loc) {}
explicit OsError(const std::error_code& errc) : message(errc.message()) { explicit OsError(const std::error_code& errc, const std::source_location& loc = std::source_location::current())
: message(errc.message()), location(loc) {
using enum OsErrorCode; using enum OsErrorCode;
using enum std::errc; using enum std::errc;
@ -205,10 +214,8 @@ struct OsError {
default: code = errc.category() == std::generic_category() ? InternalError : PlatformSpecific; break; default: code = errc.category() == std::generic_category() ? InternalError : PlatformSpecific; break;
} }
} }
#ifdef _WIN32 #ifdef _WIN32
explicit OsError(const winrt::hresult_error& e) explicit OsError(const winrt::hresult_error& e) : message(winrt::to_string(e.message())) {
: message(winrt::to_string(e.message())) /*, original_code(e.code()) */ {
switch (e.code()) { switch (e.code()) {
case E_ACCESSDENIED: code = OsErrorCode::PermissionDenied; break; case E_ACCESSDENIED: code = OsErrorCode::PermissionDenied; break;
case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND): case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND):
@ -221,7 +228,8 @@ struct OsError {
} }
} }
#else #else
OsError(OsErrorCode code_hint, int errno_val) : message(std::system_category().message(errno_val)), code(code_hint) { OsError(const OsErrorCode code_hint, const int errno_val)
: message(std::system_category().message(errno_val)), code(code_hint) {
using enum OsErrorCode; using enum OsErrorCode;
switch (errno_val) { switch (errno_val) {
@ -233,42 +241,56 @@ struct OsError {
} }
} }
static auto withErrno(const String& context) -> OsError { static auto withErrno(const String& context, const std::source_location& loc = std::source_location::current())
-> OsError {
const i32 errNo = errno; const i32 errNo = errno;
const String msg = std::system_category().message(errNo); const String msg = std::system_category().message(errNo);
const String fullMsg = std::format("{}: {}", context, msg); const String fullMsg = std::format("{}: {}", context, msg);
OsErrorCode code;
switch (errNo) { switch (errNo) {
case EACCES: case EACCES:
case EPERM: return OsError { OsErrorCode::PermissionDenied, fullMsg }; case EPERM: code = OsErrorCode::PermissionDenied; break;
case ENOENT: return OsError { OsErrorCode::NotFound, fullMsg }; case ENOENT: code = OsErrorCode::NotFound; break;
case ETIMEDOUT: return OsError { OsErrorCode::Timeout, fullMsg }; case ETIMEDOUT: code = OsErrorCode::Timeout; break;
case ENOTSUP: return OsError { OsErrorCode::NotSupported, fullMsg }; case ENOTSUP: code = OsErrorCode::NotSupported; break;
case EIO: return OsError { OsErrorCode::IoError, fullMsg }; case EIO: code = OsErrorCode::IoError; break;
case ECONNREFUSED: case ECONNREFUSED:
case ENETDOWN: case ENETDOWN:
case ENETUNREACH: return OsError { OsErrorCode::NetworkError, fullMsg }; case ENETUNREACH: code = OsErrorCode::NetworkError; break;
default: return OsError { OsErrorCode::PlatformSpecific, fullMsg }; default: code = OsErrorCode::PlatformSpecific; break;
} }
return OsError { code, fullMsg, loc };
} }
#ifdef __linux__ #ifdef __linux__
static auto fromDBus(const DBus::Error& err) -> OsError { static auto fromDBus(const DBus::Error& err, const std::source_location& loc = std::source_location::current())
-> OsError {
String name = err.name(); String name = err.name();
OsErrorCode codeHint = OsErrorCode::PlatformSpecific;
String message;
if (name == "org.freedesktop.DBus.Error.ServiceUnknown" || name == "org.freedesktop.DBus.Error.NameHasNoOwner") using namespace std::string_view_literals;
return OsError { OsErrorCode::NotFound, std::format("DBus service/name not found: {}", err.message()) };
if (name == "org.freedesktop.DBus.Error.NoReply" || name == "org.freedesktop.DBus.Error.Timeout") if (name == "org.freedesktop.DBus.Error.ServiceUnknown"sv ||
return OsError { OsErrorCode::Timeout, std::format("DBus timeout/no reply: {}", err.message()) }; name == "org.freedesktop.DBus.Error.NameHasNoOwner"sv) {
codeHint = OsErrorCode::NotFound;
if (name == "org.freedesktop.DBus.Error.AccessDenied") message = std::format("DBus service/name not found: {}", err.message());
return OsError { OsErrorCode::PermissionDenied, std::format("DBus access denied: {}", err.message()) }; } else if (name == "org.freedesktop.DBus.Error.NoReply"sv || name == "org.freedesktop.DBus.Error.Timeout"sv) {
codeHint = OsErrorCode::Timeout;
return OsError { OsErrorCode::PlatformSpecific, std::format("DBus error: {} - {}", name, err.message()) }; message = std::format("DBus timeout/no reply: {}", err.message());
} else if (name == "org.freedesktop.DBus.Error.AccessDenied"sv) {
codeHint = OsErrorCode::PermissionDenied;
message = std::format("DBus access denied: {}", err.message());
} else {
message = std::format("DBus error: {} - {}", name, err.message());
} }
#endif // __linux__
#endif // _WIN32 return OsError { codeHint, message, loc };
}
#endif
#endif
}; };
/** /**
@ -297,8 +319,7 @@ struct MediaInfo {
MediaInfo() = default; MediaInfo() = default;
MediaInfo(Option<String> title, Option<String> artist) MediaInfo(Option<String> title, Option<String> artist) : title(std::move(title)), artist(std::move(artist)) {}
: title(std::move(title)), artist(std::move(artist)) {}
MediaInfo(Option<String> title, Option<String> artist, Option<String> album, Option<String> app) MediaInfo(Option<String> title, Option<String> artist, Option<String> album, Option<String> app)
: title(std::move(title)), artist(std::move(artist)), album(std::move(album)), app_name(std::move(app)) {} : title(std::move(title)), artist(std::move(artist)), album(std::move(album)), app_name(std::move(app)) {}
@ -333,7 +354,7 @@ enum class EnvError : u8 {
* @return A Result containing the value of the environment variable as a String, * @return A Result containing the value of the environment variable as a String,
* or an EnvError if an error occurred. * or an EnvError if an error occurred.
*/ */
inline auto GetEnv(CStr name) -> Result<String, EnvError> { [[nodiscard]] inline auto GetEnv(CStr name) -> Result<String, EnvError> {
#ifdef _WIN32 #ifdef _WIN32
char* rawPtr = nullptr; char* rawPtr = nullptr;
usize bufferSize = 0; usize bufferSize = 0;