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
AlignArrayOfStructures: Right
AlignConsecutiveAssignments: true
AlignConsecutiveAssignments:
Enabled: true
AlignConsecutiveDeclarations:
Enabled: true
PadOperators: true
AlignConsecutiveMacros:
Enabled: true
AlignConsecutiveShortCaseStatements:
Enabled: true
AlignConsecutiveDeclarations: true
AlignOperands: DontAlign
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortLoopsOnASingleLine: true
BasedOnStyle: Chromium
BinPackArguments: false
BinPackParameters: false
ColumnLimit: 120
ConstructorInitializerIndentWidth: 2
ContinuationIndentWidth: 2
Cpp11BracedListStyle: false
FixNamespaceComments: false
IndentAccessModifiers: false
IndentExternBlock: Indent
IndentWidth: 2
NamespaceIndentation: All
SpaceBeforeCpp11BracedList: true
SpacesBeforeTrailingComments: 1
QualifierAlignment: Left
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '".*"'
# 1. System headers (<iostream>, <vector>, etc.)
- Regex: '^<.*>$'
Priority: 1
- Regex: '<.*>'
Priority: -1
# 2. Project headers starting with "src/"
- 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: >
*,
-ctad-maybe-unsupported,
@ -23,7 +22,6 @@ Checks: >
-llvm-namespace-comment,
-llvmlibc-*,
-misc-non-private-member-variables-in-classes,
-modernize-use-nullptr,
-readability-avoid-nested-conditional-operator,
-readability-braces-around-statements,
-readability-function-cognitive-complexity,

View file

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

View file

@ -1,9 +1,15 @@
#include <future>
#include "system_data.h"
#include "src/config/config.h"
#include "src/os/os.h"
#include <chrono> // for year_month_day, floor, days...
#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 {
fn GetDate() -> String {
@ -18,7 +24,7 @@ namespace {
return std::format(std::locale::classic(), "{:%B %d}", ymd);
}
}
}
} // namespace
SystemData SystemData::fetchSystemData(const Config& config) {
SystemData data {

View file

@ -1,7 +1,14 @@
#pragma once
#include "src/config/config.h"
#include "src/util/types.h"
#include <format> // for formatter, format_to
#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

View file

@ -4,7 +4,6 @@
#include <ftxui/screen/screen.hpp>
#include <future>
#include <string>
#include <utility>
#include <variant>
#include "config/config.h"
@ -79,7 +78,7 @@ namespace ui {
.desktop = " 󰇄 ",
.window_manager = "  ",
};
}
} // namespace ui
namespace {
using namespace ftxui;
@ -173,24 +172,23 @@ namespace {
if (data.host)
content.push_back(createRow(hostIcon, "Host", *data.host));
else
ERROR_LOG("Failed to get host info: {}", data.host.error().message);
ERROR_LOG_LOC(data.host.error());
if (data.kernel_version)
content.push_back(createRow(kernelIcon, "Kernel", *data.kernel_version));
else
ERROR_LOG("Failed to get kernel version: {}", data.kernel_version.error().message);
ERROR_LOG_LOC(data.kernel_version.error());
if (data.os_version)
content.push_back(createRow(String(osIcon), "OS", *data.os_version));
else
ERROR_LOG("Failed to get OS version: {}", data.os_version.error().message);
ERROR_LOG_LOC(data.os_version.error());
if (data.mem_info)
content.push_back(createRow(memoryIcon, "RAM", std::format("{}", BytesToGiB { *data.mem_info })));
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)
content.push_back(createRow(
diskIcon,
@ -198,7 +196,7 @@ namespace {
std::format("{}/{}", BytesToGiB { data.disk_usage->used_bytes }, BytesToGiB { data.disk_usage->total_bytes })
));
else
ERROR_LOG("Failed to get disk usage: {}", data.disk_usage.error().message);
ERROR_LOG_LOC(data.disk_usage.error());
if (data.shell)
content.push_back(createRow(shellIcon, "Shell", *data.shell));
@ -230,20 +228,13 @@ namespace {
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
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);
}
}
} // namespace
fn main() -> i32 {
const Config& config = Config::getInstance();

View file

@ -2,14 +2,12 @@
// clang-format off
#include <dbus-cxx.h> // needs to be at top for Success/None
// clang-format on
#include <cstring>
#include <fstream>
#include <sys/socket.h>
#include <sys/statvfs.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#include <system_error>
#include <unistd.h>
#include <wayland-client.h>
#include <xcb/xcb.h>
@ -18,44 +16,11 @@
#include "src/os/linux/display_guards.h"
#include "src/util/macros.h"
#include "src/util/types.h"
// clang-format on
using namespace std::string_view_literals;
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> {
using os::linux::XcbReplyGuard;
using os::linux::XorgDisplayGuard;
@ -64,10 +29,7 @@ namespace {
if (!conn)
if (const i32 err = xcb_connection_has_error(conn.get()); !conn || err != 0)
return Err(
OsError {
OsErrorCode::ApiUnavailable,
[&] -> String {
return Err(OsError(OsErrorCode::ApiUnavailable, [&] -> String {
switch (err) {
case 0: return "Connection object invalid, but no specific XCB error code";
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";
default: return std::format("Unknown Error Code ({})", err);
}
}(),
}
);
}()));
fn internAtom = [&conn](const StringView name) -> Result<xcb_atom_t, OsError> {
const XcbReplyGuard<xcb_intern_atom_reply_t> reply(xcb_intern_atom_reply(
@ -89,9 +49,7 @@ namespace {
));
if (!reply)
return Err(
OsError { OsErrorCode::PlatformSpecific, std::format("Failed to get X11 atom reply for '{}'", name) }
);
return Err(OsError(OsErrorCode::PlatformSpecific, std::format("Failed to get X11 atom reply for '{}'", name)));
return reply->atom;
};
@ -110,7 +68,7 @@ namespace {
if (!utf8StringAtom)
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(
@ -121,7 +79,7 @@ namespace {
if (!wmWindowReply || wmWindowReply->type != XCB_ATOM_WINDOW || wmWindowReply->format != 32 ||
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()));
@ -130,7 +88,7 @@ namespace {
));
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 usize length = xcb_get_property_value_length(wmNameReply.get());
@ -144,24 +102,24 @@ namespace {
const WaylandDisplayGuard 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();
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;
socklen_t len = sizeof(cred);
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;
auto [out, size] = std::format_to_n(exeLinkPathBuf.data(), exeLinkPathBuf.size() - 1, "/proc/{}/exe", cred.pid);
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';
@ -172,7 +130,7 @@ namespace {
const isize bytesRead = readlink(exeLinkPath, exeRealPathBuf.data(), exeRealPathBuf.size() - 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';
@ -195,7 +153,7 @@ namespace {
compositorNameView = filenameView;
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() &&
compositorNameView[0] == '.' && compositorNameView.ends_with(wrappedSuffix)) {
@ -203,7 +161,7 @@ namespace {
compositorNameView.substr(1, compositorNameView.length() - 1 - wrappedSuffix.length());
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);
}
@ -219,7 +177,7 @@ namespace {
const SharedPointer<DBus::Message> reply = connection->send_with_reply_blocking(call, 5);
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;
DBus::MessageIterator reader(*reply);
@ -229,9 +187,9 @@ namespace {
if (StringView(name).contains("org.mpris.MediaPlayer2"sv))
return name;
return Err(OsError { OsErrorCode::NotFound, "No MPRIS players found" });
} catch (const DBus::Error& e) { return Err(MakeOsErrorFromDBus(e)); } catch (const Exception& e) {
return Err(OsError { OsErrorCode::InternalError, e.what() });
return Err(OsError(OsErrorCode::NotFound, "No MPRIS players found"));
} catch (const DBus::Error& e) { return Err(OsError::fromDBus(e)); } catch (const Exception& e) {
return Err(OsError(OsErrorCode::InternalError, e.what()));
}
}
@ -246,7 +204,7 @@ namespace {
const SharedPointer<DBus::Message> metadataReply = connection->send_with_reply_blocking(metadataCall, 1000);
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);
@ -255,15 +213,13 @@ namespace {
// MPRIS metadata is variant containing a dict a{sv}
if (metadataVariant.type() != DBus::DataType::DICT_ENTRY && metadataVariant.type() != DBus::DataType::ARRAY) {
return Err(
OsError {
return Err(OsError(
OsErrorCode::ParseError,
std::format(
"Inner metadata variant is not the expected type, expected dict/a{{sv}} but got '{}'",
metadataVariant.signature().str()
),
}
);
)
));
}
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));
} 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, 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> {
constexpr CStr path = "/etc/os-release";
@ -321,7 +277,7 @@ fn os::GetOSVersion() -> Result<String, OsError> {
std::ifstream file(path);
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;
constexpr StringView prefix = "PRETTY_NAME=";
@ -336,30 +292,30 @@ fn os::GetOSVersion() -> Result<String, OsError> {
if (value.empty())
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 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> {
struct sysinfo info;
if (sysinfo(&info) != 0)
return Err(MakeOsErrorFromErrno("sysinfo call failed"));
return Err(OsError::fromDBus("sysinfo call failed"));
const u64 totalRam = info.totalram;
const u64 memUnit = info.mem_unit;
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)
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;
}
@ -374,14 +330,14 @@ fn os::GetNowPlaying() -> Result<MediaInfo, NowPlayingError> {
dispatcher = DBus::StandaloneDispatcher::create();
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);
if (!connection)
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) {
return Err(OsError { OsErrorCode::InternalError, e.what() });
return Err(OsError(OsErrorCode::ApiUnavailable, "Failed to connect to DBus session bus"));
} catch (const DBus::Error& e) { return Err(OsError::fromDBus(e)); } catch (const Exception& e) {
return Err(OsError(OsErrorCode::InternalError, e.what()));
}
Result<String, NowPlayingError> playerBusName = GetMprisPlayers(connection);
@ -458,20 +414,17 @@ fn os::GetHost() -> Result<String, OsError> {
String line;
if (!file)
return Err(
OsError { OsErrorCode::NotFound, std::format("Failed to open DMI product identifier file '{}'", path) }
);
return Err(OsError(OsErrorCode::NotFound, std::format("Failed to open DMI product identifier file '{}'", path)));
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 readFirstLine(primaryPath).or_else([&](const OsError& primaryError) -> Result<String, OsError> {
return readFirstLine(fallbackPath).or_else([&](const OsError& fallbackError) -> Result<String, OsError> {
return Err(
OsError {
return Err(OsError(
OsErrorCode::InternalError,
std::format(
"Failed to get host identifier. Primary ('{}'): {}. Fallback ('{}'): {}",
@ -479,9 +432,8 @@ fn os::GetHost() -> Result<String, OsError> {
primaryError.message,
fallbackPath,
fallbackError.message
),
}
);
)
));
});
});
}
@ -490,10 +442,10 @@ fn os::GetKernelVersion() -> Result<String, OsError> {
utsname uts;
if (uname(&uts) == -1)
return Err(MakeOsErrorFromErrno("uname call failed"));
return Err(OsError::withErrno("uname call failed"));
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;
}
@ -502,7 +454,7 @@ fn os::GetDiskUsage() -> Result<DiskSpace, OsError> {
struct statvfs stat;
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 {
.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
// Fixes conflict in Windows with <windows.h>
#ifdef _WIN32
#undef ERROR
#endif
#undef ERROR
#endif // _WIN32
#include <chrono>
#include <filesystem>
@ -117,9 +116,11 @@ namespace term {
* @param fgColor The foreground color to apply.
* @return The combined style.
*/
// ReSharper disable CppDFAConstantParameter
constexpr fn operator|(const Emphasis emph, const Color fgColor)->Style {
return { .emph = emph, .fg_col = fgColor };
}
// ReSharper restore CppDFAConstantParameter
/**
* @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
std::print(fmt, std::forward<Args>(args)...);
}
}
} // namespace term
/**
* @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) {
using namespace std::chrono;
using namespace term;
#ifdef _WIN32
#ifdef _MSC_VER
using enum term::Color;
#else
using enum Color;
#endif
#endif // _MSC_VER
const auto [color, levelStr] = [&] {
switch (level) {
@ -229,29 +231,82 @@ fn LogImpl(const LogLevel level, const std::source_location& loc, std::format_st
std::filesystem::path(loc.file_name()).lexically_normal().string(),
loc.line()
);
#endif
#endif // !NDEBUG
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
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-macros"
#endif
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-macros"
#endif // __clang__
#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
/**
/**
* @def DEBUG_LOG
* @brief Logs a message at the DEBUG level.
* @details Only active in non-release builds (when NDEBUG is not defined).
* Includes timestamp, level, message, and source location.
* @param ... Format string and arguments for the log message.
*/
#define DEBUG_LOG(...) LogImpl(LogLevel::DEBUG, std::source_location::current(), __VA_ARGS__)
#endif
#define DEBUG_LOG(...) LogImpl(LogLevel::DEBUG, std::source_location::current(), __VA_ARGS__)
/**
* @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(...)
@ -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__)
/**
* @def RETURN_ERR(...)
* @brief Logs an error message and returns a value.
* @details Logs the error message with the ERROR log level and returns the specified value.
* @param ... Format string and arguments for the error message.
* @def ERROR_LOG_LOC(error_obj)
* @brief Logs an application-specific error at the ERROR level, using its stored location if available.
* @param error_obj The error object (e.g., OsError, NowPlayingError).
*/
#define RETURN_ERR(...) \
#define ERROR_LOG_LOC(error_obj) \
do { \
ERROR_LOG(__VA_ARGS__); \
return None; \
[&](const auto& err) { detail::LogAppError(LogLevel::ERROR, err); }(error_obj); \
} while (0)
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#pragma clang diagnostic pop
#endif // __clang__

View file

@ -7,6 +7,7 @@
#include <map> // std::map alias (Map)
#include <memory> // std::shared_ptr and std::unique_ptr aliases (SharedPointer, UniquePointer)
#include <optional> // std::optional alias (Option)
#include <source_location> // std::source_location
#include <string> // std::string and std::string_view aliases (String, StringView)
#include <system_error> // std::error_code and std::system_error
#include <utility> // std::pair alias (Pair)
@ -14,7 +15,9 @@
#include <vector> // std::vector alias (Vec)
#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
//----------------------------------------------------------------//
@ -182,14 +185,20 @@ enum class OsErrorCode : u8 {
* Used as the error type in Result for many os:: functions.
*/
struct OsError {
String message = "Unknown Error"; ///< A descriptive error message, potentially including platform details.
OsErrorCode code = OsErrorCode::Other; ///< The general category of the error.
// ReSharper disable CppDFANotInitializedField
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 std::errc;
@ -205,10 +214,8 @@ struct OsError {
default: code = errc.category() == std::generic_category() ? InternalError : PlatformSpecific; break;
}
}
#ifdef _WIN32
explicit OsError(const winrt::hresult_error& e)
: message(winrt::to_string(e.message())) /*, original_code(e.code()) */ {
explicit OsError(const winrt::hresult_error& e) : message(winrt::to_string(e.message())) {
switch (e.code()) {
case E_ACCESSDENIED: code = OsErrorCode::PermissionDenied; break;
case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND):
@ -221,7 +228,8 @@ struct OsError {
}
}
#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;
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 String msg = std::system_category().message(errNo);
const String fullMsg = std::format("{}: {}", context, msg);
OsErrorCode code;
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 EPERM: code = OsErrorCode::PermissionDenied; break;
case ENOENT: code = OsErrorCode::NotFound; break;
case ETIMEDOUT: code = OsErrorCode::Timeout; break;
case ENOTSUP: code = OsErrorCode::NotSupported; break;
case EIO: code = OsErrorCode::IoError; break;
case ECONNREFUSED:
case ENETDOWN:
case ENETUNREACH: return OsError { OsErrorCode::NetworkError, fullMsg };
default: return OsError { OsErrorCode::PlatformSpecific, fullMsg };
}
case ENETUNREACH: code = OsErrorCode::NetworkError; break;
default: code = OsErrorCode::PlatformSpecific; break;
}
#ifdef __linux__
static auto fromDBus(const DBus::Error& err) -> OsError {
return OsError { code, fullMsg, loc };
}
#ifdef __linux__
static auto fromDBus(const DBus::Error& err, const std::source_location& loc = std::source_location::current())
-> OsError {
String name = err.name();
OsErrorCode codeHint = OsErrorCode::PlatformSpecific;
String message;
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()) };
using namespace std::string_view_literals;
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()) };
if (name == "org.freedesktop.DBus.Error.ServiceUnknown"sv ||
name == "org.freedesktop.DBus.Error.NameHasNoOwner"sv) {
codeHint = OsErrorCode::NotFound;
message = std::format("DBus service/name not found: {}", err.message());
} else if (name == "org.freedesktop.DBus.Error.NoReply"sv || name == "org.freedesktop.DBus.Error.Timeout"sv) {
codeHint = OsErrorCode::Timeout;
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(Option<String> title, Option<String> artist)
: title(std::move(title)), artist(std::move(artist)) {}
MediaInfo(Option<String> title, Option<String> artist) : title(std::move(title)), artist(std::move(artist)) {}
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)) {}
@ -333,7 +354,7 @@ enum class EnvError : u8 {
* @return A Result containing the value of the environment variable as a String,
* 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
char* rawPtr = nullptr;
usize bufferSize = 0;