diff --git a/.clang-format b/.clang-format index 0d77533..e34dcd1 100644 --- a/.clang-format +++ b/.clang-format @@ -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 (, , 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 diff --git a/.clang-tidy b/.clang-tidy index 531105e..12b2afc 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -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, diff --git a/flake.nix b/flake.nix index 5683c7f..e545c26 100644 --- a/flake.nix +++ b/flake.nix @@ -124,6 +124,7 @@ bear llvmPackages.clang-tools cmake + include-what-you-use lldb hyperfine meson diff --git a/src/core/system_data.cpp b/src/core/system_data.cpp index f9a06f7..87766a5 100644 --- a/src/core/system_data.cpp +++ b/src/core/system_data.cpp @@ -1,9 +1,15 @@ -#include - #include "system_data.h" -#include "src/config/config.h" -#include "src/os/os.h" +#include // for year_month_day, floor, days... +#include // for exception +#include // for future, async, launch +#include // for locale +#include // for runtime_error +#include // for tuple, get, make_tuple +#include // 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 { diff --git a/src/core/system_data.h b/src/core/system_data.h index a5415ca..5ce2c0e 100644 --- a/src/core/system_data.h +++ b/src/core/system_data.h @@ -1,7 +1,14 @@ #pragma once -#include "src/config/config.h" -#include "src/util/types.h" +#include // for formatter, format_to +#include // for basic_string +#include // 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 diff --git a/src/main.cpp b/src/main.cpp index 43b56cb..6397459 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,7 +4,6 @@ #include #include #include -#include #include #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(error)) { - switch (std::get(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(error).message); - } + } else + DEBUG_LOG_LOC(nowPlayingResult.error()); } return vbox(content) | borderRounded | color(Color::White); } -} +} // namespace fn main() -> i32 { const Config& config = Config::getInstance(); diff --git a/src/os/linux.cpp b/src/os/linux.cpp index 1d3b39d..a4e5a38 100644 --- a/src/os/linux.cpp +++ b/src/os/linux.cpp @@ -2,14 +2,12 @@ // clang-format off #include // needs to be at top for Success/None -// clang-format on #include #include #include #include #include #include -#include #include #include #include @@ -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 { using os::linux::XcbReplyGuard; using os::linux::XorgDisplayGuard; @@ -64,24 +29,19 @@ namespace { if (!conn) if (const i32 err = xcb_connection_has_error(conn.get()); !conn || err != 0) - 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"; - case XCB_CONN_CLOSED_EXT_NOTSUPPORTED: return "Closed: Extension Not Supported"; - case XCB_CONN_CLOSED_MEM_INSUFFICIENT: return "Closed: Insufficient Memory"; - case XCB_CONN_CLOSED_REQ_LEN_EXCEED: return "Closed: Request Length Exceeded"; - case XCB_CONN_CLOSED_PARSE_ERR: return "Closed: Display String Parse Error"; - case XCB_CONN_CLOSED_INVALID_SCREEN: return "Closed: Invalid Screen"; - case XCB_CONN_CLOSED_FDPASSING_FAILED: return "Closed: FD Passing Failed"; - default: return std::format("Unknown Error Code ({})", err); - } - }(), + 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"; + case XCB_CONN_CLOSED_EXT_NOTSUPPORTED: return "Closed: Extension Not Supported"; + case XCB_CONN_CLOSED_MEM_INSUFFICIENT: return "Closed: Insufficient Memory"; + case XCB_CONN_CLOSED_REQ_LEN_EXCEED: return "Closed: Request Length Exceeded"; + case XCB_CONN_CLOSED_PARSE_ERR: return "Closed: Display String Parse Error"; + case XCB_CONN_CLOSED_INVALID_SCREEN: return "Closed: Invalid Screen"; + 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 { const XcbReplyGuard 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 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_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(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 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 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 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 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 { - OsErrorCode::ParseError, - std::format( - "Inner metadata variant is not the expected type, expected dict/a{{sv}} but got '{}'", - metadataVariant.signature().str() - ), - } - ); + 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 metadata = metadataVariant.to_map(); // 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 { constexpr CStr path = "/etc/os-release"; @@ -321,7 +277,7 @@ fn os::GetOSVersion() -> Result { 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 { 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 { 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::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 { 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 playerBusName = GetMprisPlayers(connection); @@ -458,30 +414,26 @@ fn os::GetHost() -> Result { 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 { return readFirstLine(fallbackPath).or_else([&](const OsError& fallbackError) -> Result { - return Err( - OsError { - OsErrorCode::InternalError, - std::format( - "Failed to get host identifier. Primary ('{}'): {}. Fallback ('{}'): {}", - primaryPath, - primaryError.message, - fallbackPath, - fallbackError.message - ), - } - ); + return Err(OsError( + OsErrorCode::InternalError, + std::format( + "Failed to get host identifier. Primary ('{}'): {}. Fallback ('{}'): {}", + primaryPath, + primaryError.message, + fallbackPath, + fallbackError.message + ) + )); }); }); } @@ -490,10 +442,10 @@ fn os::GetKernelVersion() -> Result { 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 { 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 { }; } -#endif +#endif // __linux__ diff --git a/src/util/macros.h b/src/util/macros.h index f56ec8f..c5ad961 100644 --- a/src/util/macros.h +++ b/src/util/macros.h @@ -1,10 +1,9 @@ -// ReSharper disable CppDFAConstantParameter #pragma once // Fixes conflict in Windows with #ifdef _WIN32 -#undef ERROR -#endif + #undef ERROR +#endif // _WIN32 #include #include @@ -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)...); } -} +} // namespace term /** * @enum LogLevel @@ -201,11 +202,12 @@ template fn LogImpl(const LogLevel level, const std::source_location& loc, std::format_string 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 + fn LogAppError(const LogLevel level, const ErrorType& error_obj) { + using DecayedErrorType = std::decay_t; + + std::source_location log_location = std::source_location::current(); + String error_message_part; + LogLevel final_log_level = level; + + if constexpr (std::is_same_v) { + log_location = error_obj.location; + error_message_part = error_obj.message; + + } else if constexpr (std::is_same_v) { + if (std::holds_alternative(error_obj)) { + const OsError& osErr = std::get(error_obj); + log_location = osErr.location; + error_message_part = osErr.message; + } else if (std::holds_alternative(error_obj)) { + const NowPlayingCode npCode = std::get(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) + 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(0) + #define DEBUG_LOG(...) static_cast(0) + #define DEBUG_LOG_LOC(...) static_cast(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 + /** + * @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__) + /** + * @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(...) \ - do { \ - ERROR_LOG(__VA_ARGS__); \ - return None; \ +#define ERROR_LOG_LOC(error_obj) \ + do { \ + [&](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__ diff --git a/src/util/types.h b/src/util/types.h index 970a500..40b4da9 100644 --- a/src/util/types.h +++ b/src/util/types.h @@ -1,20 +1,23 @@ #pragma once -#include // std::array alias (Array) -#include // std::getenv, std::free -#include // std::expected alias (Result) -#include // std::format -#include // std::map alias (Map) -#include // std::shared_ptr and std::unique_ptr aliases (SharedPointer, UniquePointer) -#include // std::optional alias (Option) -#include // std::string and std::string_view aliases (String, StringView) -#include // std::error_code and std::system_error -#include // std::pair alias (Pair) -#include // std::variant alias (NowPlayingError) -#include // std::vector alias (Vec) +#include // std::array alias (Array) +#include // std::getenv, std::free +#include // std::expected alias (Result) +#include // std::format +#include // std::map alias (Map) +#include // std::shared_ptr and std::unique_ptr aliases (SharedPointer, UniquePointer) +#include // std::optional alias (Option) +#include // std::source_location +#include // std::string and std::string_view aliases (String, StringView) +#include // std::error_code and std::system_error +#include // std::pair alias (Pair) +#include // std::variant alias (NowPlayingError) +#include // std::vector alias (Vec) #ifdef _WIN32 -#include // winrt::hresult_error (WindowsError) + #include // winrt::hresult_error +#elifdef __linux__ + #include // 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; } + + return OsError { code, fullMsg, loc }; } -#ifdef __linux__ - static auto fromDBus(const DBus::Error& err) -> OsError { - String name = err.name(); + #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.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()); + } - 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()) }; + return OsError { codeHint, message, loc }; } -#endif // __linux__ -#endif // _WIN32 + #endif +#endif }; /** @@ -297,8 +319,7 @@ struct MediaInfo { MediaInfo() = default; - MediaInfo(Option title, Option artist) - : title(std::move(title)), artist(std::move(artist)) {} + MediaInfo(Option title, Option artist) : title(std::move(title)), artist(std::move(artist)) {} MediaInfo(Option title, Option artist, Option album, Option 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 { +[[nodiscard]] inline auto GetEnv(CStr name) -> Result { #ifdef _WIN32 char* rawPtr = nullptr; usize bufferSize = 0;