From 34e6bf52fdd611b2f5f934f2b8dc2b41db6f67de Mon Sep 17 00:00:00 2001 From: Mars Date: Fri, 2 May 2025 15:17:17 -0400 Subject: [PATCH] update windows + fixes --- src/config/config.cpp | 7 ++-- src/core/package.hpp | 2 -- src/core/system_data.cpp | 21 ++++++----- src/core/system_data.hpp | 4 +-- src/main.cpp | 6 ++-- src/os/shared.cpp | 19 ++++++---- src/os/windows.cpp | 76 +++++++++++++++++----------------------- src/util/error.hpp | 12 +++---- src/util/helpers.hpp | 4 +-- src/util/logging.hpp | 3 +- 10 files changed, 75 insertions(+), 79 deletions(-) diff --git a/src/config/config.cpp b/src/config/config.cpp index fdce910..2b63e4f 100644 --- a/src/config/config.cpp +++ b/src/config/config.cpp @@ -3,12 +3,15 @@ #include // std::filesystem::{path, operator/, exists, create_directories} #include // std::{format, format_error} #include // std::{ifstream, ofstream, operator<<} -#include // passwd, getpwuid #include // std::error_code #include // toml::node_view #include // toml::{parse_file, parse_result} #include // toml::table -#include // getuid + +#ifndef _WIN32 + #include // passwd, getpwuid + #include // getuid +#endif #include "src/util/defs.hpp" #include "src/util/helpers.hpp" diff --git a/src/core/package.hpp b/src/core/package.hpp index 88caf00..2d810fc 100644 --- a/src/core/package.hpp +++ b/src/core/package.hpp @@ -4,14 +4,12 @@ #include // std::future #include // glz::object #include // glz::detail::Object -#include // std::vector #include "src/util/defs.hpp" #include "src/util/error.hpp" #include "src/util/types.hpp" namespace packages { - namespace fs = std::filesystem; using util::error::DracError; using util::types::Result, util::types::u64, util::types::i64, util::types::String, util::types::Vec, diff --git a/src/core/system_data.cpp b/src/core/system_data.cpp index 971961d..70adeb7 100644 --- a/src/core/system_data.cpp +++ b/src/core/system_data.cpp @@ -17,7 +17,7 @@ using util::error::DracError, util::error::DracErrorCode; namespace { using util::types::i32, util::types::CStr; - fn getOrdinalSuffix(i32 day) -> CStr { + fn getOrdinalSuffix(const i32 day) -> CStr { if (day >= 11 && day <= 13) return "th"; @@ -45,10 +45,9 @@ namespace { #endif i32 day = nowTm.tm_mday; - String monthBuffer(32, '\0'); - const usize monthLen = std::strftime(monthBuffer.data(), monthBuffer.size(), "%B", &nowTm); + String monthBuffer(32, '\0'); - if (monthLen > 0) { + if (const usize monthLen = std::strftime(monthBuffer.data(), monthBuffer.size(), "%B", &nowTm); monthLen > 0) { monthBuffer.resize(monthLen); CStr suffix = getOrdinalSuffix(day); @@ -56,10 +55,12 @@ namespace { try { return std::format("{} {}{}", monthBuffer, day, suffix); } catch (const std::format_error& e) { return Err(DracError(DracErrorCode::ParseError, e.what())); } - } else - return Err(DracError(DracErrorCode::ParseError, "Failed to format date")); - } else - return Err(DracError(DracErrorCode::ParseError, "Failed to get local time")); + } + + return Err(DracError(DracErrorCode::ParseError, "Failed to format date")); + } + + return Err(DracError(DracErrorCode::ParseError, "Failed to get local time")); } } // namespace @@ -81,9 +82,7 @@ namespace os { Future> npFut = std::async(config.nowPlaying.enabled ? async : deferred, GetNowPlaying); Future> wthrFut = - std::async(config.weather.enabled ? async : deferred, [&config] -> Result { - return config.weather.getWeatherInfo(); - }); + std::async(config.weather.enabled ? async : deferred, [&config] { return config.weather.getWeatherInfo(); }); this->date = getDate(); this->host = hostFut.get(); diff --git a/src/core/system_data.hpp b/src/core/system_data.hpp index 37194c6..9577036 100644 --- a/src/core/system_data.hpp +++ b/src/core/system_data.hpp @@ -2,8 +2,8 @@ #include // std::{formatter, format_to} -#include "src/config/config.hpp" // Config -#include "src/config/weather.hpp" // weather::Output +#include "src/config/config.hpp" +#include "src/config/weather.hpp" #include "src/util/defs.hpp" #include "src/util/types.hpp" diff --git a/src/main.cpp b/src/main.cpp index 49a7544..3eeca8a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -244,8 +244,8 @@ namespace { usize requiredWidthSystemW = iconActualWidth + maxLabelWidthSystem; usize requiredWidthEnvW = iconActualWidth + maxLabelWidthEnv; - fn calculateRowVisualWidth = [&](const RowInfo& row, usize requiredLabelVisualWidth) -> usize { - return requiredLabelVisualWidth + get_visual_width(row.value) + get_visual_width_sv(" "); // Use visual width + fn calculateRowVisualWidth = [&](const RowInfo& row, const usize requiredLabelVisualWidth) -> usize { + return requiredLabelVisualWidth + get_visual_width(row.value) + get_visual_width_sv(" "); }; for (const RowInfo& row : initialRows) @@ -278,7 +278,7 @@ namespace { paragraphLimit = std::max(1, availableForParagraph); } - fn createStandardRow = [&](const RowInfo& row, usize sectionRequiredVisualWidth) { + fn createStandardRow = [&](const RowInfo& row, const usize sectionRequiredVisualWidth) { return hbox( { hbox( diff --git a/src/os/shared.cpp b/src/os/shared.cpp index e435bf1..7a913b9 100644 --- a/src/os/shared.cpp +++ b/src/os/shared.cpp @@ -1,15 +1,16 @@ -#include // SQLite::{Database, OPEN_READONLY} -#include // SQLite::Exception -#include // SQLite::Statement +#ifndef _WIN32 + #include // SQLite::{Database, OPEN_READONLY} + #include // SQLite::Exception + #include // SQLite::Statement +#endif + #include // std::chrono #include // std::filesystem #include // std::format #include // std::{ifstream, ofstream} -#include // glz::read_beve #include // glz::write_beve #include // glz::object #include // glz::detail::Object -#include // std::ios::{binary, trunc}, std::ios_base #include // std::istreambuf_iterator #include // std::error_code @@ -32,11 +33,13 @@ namespace { using namespace std::chrono; using namespace util::cache; +#ifndef _WIN32 struct PackageManagerInfo { String id; fs::path dbPath; String countQuery; }; +#endif struct PkgCountCacheData { u64 count {}; @@ -52,6 +55,7 @@ namespace { // NOLINTEND(readability-identifier-naming) }; +#ifndef _WIN32 fn GetPackageCountInternalDb(const PackageManagerInfo& pmInfo) -> Result { const auto& [pmId, dbPath, countQuery] = pmInfo; @@ -113,6 +117,7 @@ namespace { return count; } +#endif #ifndef _WIN32 fn GetNixPackageCount() -> Result { @@ -142,9 +147,9 @@ namespace { fs::path cargoPath {}; - if (Result cargoHome = GetEnv("CARGO_HOME")) + if (const Result cargoHome = GetEnv("CARGO_HOME")) cargoPath = fs::path(*cargoHome) / "bin"; - else if (Result homeDir = GetEnv("HOME")) + else if (const Result homeDir = GetEnv("HOME")) cargoPath = fs::path(*homeDir) / ".cargo" / "bin"; if (cargoPath.empty() || !fs::exists(cargoPath)) diff --git a/src/os/windows.cpp b/src/os/windows.cpp index ca2c202..3b718f0 100644 --- a/src/os/windows.cpp +++ b/src/os/windows.cpp @@ -27,7 +27,7 @@ using RtlGetVersionPtr = NTSTATUS(WINAPI*)(PRTL_OSVERSIONINFOW); namespace { - using util::error::DraconisError, util::error::DraconisErrorCode; + using util::error::DracError, util::error::DracErrorCode; using namespace util::types; struct ProcessData { @@ -165,7 +165,7 @@ namespace { } // namespace namespace os { - fn GetMemInfo() -> Result { + fn GetMemInfo() -> Result { MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); @@ -173,12 +173,12 @@ namespace os { return memInfo.ullTotalPhys; DWORD lastError = GetLastError(); - return Err(DraconisError( - DraconisErrorCode::PlatformSpecific, std::format("GlobalMemoryStatusEx failed with error code {}", lastError) + return Err(DracError( + DracErrorCode::PlatformSpecific, std::format("GlobalMemoryStatusEx failed with error code {}", lastError) )); } - fn GetNowPlaying() -> Result { + fn GetNowPlaying() -> Result { using namespace winrt::Windows::Media::Control; using namespace winrt::Windows::Foundation; @@ -193,16 +193,14 @@ namespace os { if (const Session currentSession = sessionManager.GetCurrentSession()) { const MediaProperties mediaProperties = currentSession.TryGetMediaPropertiesAsync().get(); - return MediaInfo( - winrt::to_string(mediaProperties.Title()), winrt::to_string(mediaProperties.Artist()), None, None - ); + return MediaInfo(winrt::to_string(mediaProperties.Title()), winrt::to_string(mediaProperties.Artist())); } - return Err(DraconisError(DraconisErrorCode::NotFound, "No media session found")); - } catch (const winrt::hresult_error& e) { return Err(DraconisError(e)); } + return Err(DracError(DracErrorCode::NotFound, "No media session found")); + } catch (const winrt::hresult_error& e) { return Err(DracError(e)); } } - fn GetOSVersion() -> Result { + fn GetOSVersion() -> Result { try { const String regSubKey = R"(SOFTWARE\Microsoft\Windows NT\CurrentVersion)"; @@ -210,7 +208,7 @@ namespace os { const String displayVersion = GetRegistryValue(HKEY_LOCAL_MACHINE, regSubKey, "DisplayVersion"); if (productName.empty()) - return Err(DraconisError(DraconisErrorCode::NotFound, "ProductName not found in registry")); + return Err(DracError(DracErrorCode::NotFound, "ProductName not found in registry")); if (const Option buildNumberOpt = GetBuildNumber()) { if (const u64 buildNumber = *buildNumberOpt; buildNumber >= 22000) { @@ -229,14 +227,14 @@ namespace os { } return displayVersion.empty() ? productName : productName + " " + displayVersion; - } catch (const std::exception& e) { return Err(DraconisError(e)); } + } catch (const std::exception& e) { return Err(DracError(e)); } } - fn GetHost() -> Result { + fn GetHost() -> Result { return GetRegistryValue(HKEY_LOCAL_MACHINE, R"(SYSTEM\HardwareConfig\Current)", "SystemFamily"); } - fn GetKernelVersion() -> Result { + fn GetKernelVersion() -> Result { if (const HMODULE ntdllHandle = GetModuleHandleW(L"ntdll.dll")) { if (const auto rtlGetVersion = std::bit_cast(GetProcAddress(ntdllHandle, "RtlGetVersion"))) { RTL_OSVERSIONINFOW osInfo = {}; @@ -249,28 +247,24 @@ namespace os { } } - return Err(DraconisError(DraconisErrorCode::NotFound, "Could not determine kernel version using RtlGetVersion")); + return Err(DracError(DracErrorCode::NotFound, "Could not determine kernel version using RtlGetVersion")); } - fn GetWindowManager() -> Option { + fn GetWindowManager() -> Result { BOOL compositionEnabled = FALSE; - if (SUCCEEDED(DwmIsCompositionEnabled(&compositionEnabled))) { + + if (SUCCEEDED(DwmIsCompositionEnabled(&compositionEnabled))) return compositionEnabled ? "DWM" : "Windows Manager (Basic)"; - } - error_log("GetWindowManager: DwmIsCompositionEnabled failed"); - - return None; + return Err(DracError(DracErrorCode::NotFound, "Failed to get window manager (DwmIsCompositionEnabled failed")); } - fn GetDesktopEnvironment() -> Option { + fn GetDesktopEnvironment() -> Result { const String buildStr = GetRegistryValue(HKEY_LOCAL_MACHINE, R"(SOFTWARE\Microsoft\Windows NT\CurrentVersion)", "CurrentBuildNumber"); - if (buildStr.empty()) { - debug_log("Failed to get CurrentBuildNumber from registry"); - return None; - } + if (buildStr.empty()) + return Err(DracError(DracErrorCode::InternalError, "Failed to get CurrentBuildNumber from registry")); try { const i32 build = stoi(buildStr); @@ -304,22 +298,18 @@ namespace os { // Pre-Win7 return "Classic"; - } catch (...) { - debug_log("Failed to parse CurrentBuildNumber"); - return None; - } + } catch (...) { return Err(DracError(DracErrorCode::ParseError, "Failed to parse CurrentBuildNumber")); } } - fn GetShell() -> Option { + fn GetShell() -> Result { using util::helpers::GetEnv; - if (const Result msystemResult = GetEnv("MSYSTEM"); - msystemResult && !msystemResult->empty()) { + if (const Result msystemResult = GetEnv("MSYSTEM"); msystemResult && !msystemResult->empty()) { String shellPath; - if (const Result shellResult = GetEnv("SHELL"); shellResult && !shellResult->empty()) { + if (const Result shellResult = GetEnv("SHELL"); shellResult && !shellResult->empty()) { shellPath = *shellResult; - } else if (const Result loginShellResult = GetEnv("LOGINSHELL"); + } else if (const Result loginShellResult = GetEnv("LOGINSHELL"); loginShellResult && !loginShellResult->empty()) { shellPath = *loginShellResult; } @@ -339,31 +329,31 @@ namespace os { const DWORD currentPid = GetCurrentProcessId(); if (const Option msysShell = FindShellInProcessTree(currentPid, msysShellMap)) - return msysShell; + return *msysShell; return "MSYS2 Environment"; } const DWORD currentPid = GetCurrentProcessId(); if (const Option windowsShell = FindShellInProcessTree(currentPid, windowsShellMap)) - return windowsShell; + return *windowsShell; - return None; + return Err(DracError(DracErrorCode::NotFound, "Shell not found")); } - fn GetDiskUsage() -> Result { + fn GetDiskUsage() -> Result { ULARGE_INTEGER freeBytes, totalBytes; if (GetDiskFreeSpaceExW(L"C:\\", nullptr, &totalBytes, &freeBytes)) return DiskSpace { .used_bytes = totalBytes.QuadPart - freeBytes.QuadPart, .total_bytes = totalBytes.QuadPart }; - return Err(DraconisError(util::error::DraconisErrorCode::NotFound, "Failed to get disk usage")); + return Err(DracError(util::error::DracErrorCode::NotFound, "Failed to get disk usage")); } - fn GetPackageCount() -> Result { + fn GetPackageCount() -> Result { try { return std::ranges::distance(winrt::Windows::Management::Deployment::PackageManager().FindPackagesForUser(L"")); - } catch (const winrt::hresult_error& e) { return Err(DraconisError(e)); } + } catch (const winrt::hresult_error& e) { return Err(DracError(e)); } } } // namespace os diff --git a/src/util/error.hpp b/src/util/error.hpp index ed82589..b1ea4db 100644 --- a/src/util/error.hpp +++ b/src/util/error.hpp @@ -71,16 +71,16 @@ namespace util::error { } } #ifdef _WIN32 - explicit DraconisError(const winrt::hresult_error& e) : message(winrt::to_string(e.message())) { + explicit DracError(const winrt::hresult_error& e) : message(winrt::to_string(e.message())) { switch (e.code()) { - case E_ACCESSDENIED: code = DraconisErrorCode::PermissionDenied; break; + case E_ACCESSDENIED: code = DracErrorCode::PermissionDenied; break; case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND): case HRESULT_FROM_WIN32(ERROR_PATH_NOT_FOUND): - case HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_FOUND): code = DraconisErrorCode::NotFound; break; + case HRESULT_FROM_WIN32(ERROR_SERVICE_NOT_FOUND): code = DracErrorCode::NotFound; break; case HRESULT_FROM_WIN32(ERROR_TIMEOUT): - case HRESULT_FROM_WIN32(ERROR_SEM_TIMEOUT): code = DraconisErrorCode::Timeout; break; - case HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED): code = DraconisErrorCode::NotSupported; break; - default: code = DraconisErrorCode::PlatformSpecific; break; + case HRESULT_FROM_WIN32(ERROR_SEM_TIMEOUT): code = DracErrorCode::Timeout; break; + case HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED): code = DracErrorCode::NotSupported; break; + default: code = DracErrorCode::PlatformSpecific; break; } } #else diff --git a/src/util/helpers.hpp b/src/util/helpers.hpp index d7c939a..4414d7f 100644 --- a/src/util/helpers.hpp +++ b/src/util/helpers.hpp @@ -27,10 +27,10 @@ namespace util::helpers { const UniquePointer ptrManager(rawPtr, free); if (err != 0) - return Err(DraconisError(DraconisErrorCode::PermissionDenied, "Failed to retrieve environment variable")); + return Err(DracError(DracErrorCode::PermissionDenied, "Failed to retrieve environment variable")); if (!ptrManager) - return Err(DraconisError(DraconisErrorCode::NotFound, "Environment variable not found")); + return Err(DracError(DracErrorCode::NotFound, "Environment variable not found")); return ptrManager.get(); #else diff --git a/src/util/logging.hpp b/src/util/logging.hpp index b85962f..b2bacf2 100644 --- a/src/util/logging.hpp +++ b/src/util/logging.hpp @@ -156,6 +156,7 @@ namespace util::logging { fn LogImpl( const LogLevel level, #ifndef NDEBUG + // ReSharper disable once CppDoxygenUndocumentedParameter const std::source_location& loc, #endif std::format_string fmt, @@ -173,7 +174,7 @@ namespace util::logging { String timestamp; #ifdef _WIN32 - if (localtime_s(&local_tm, &now_tt) == 0) { + if (localtime_s(&localTm, &nowTt) == 0) { #else if (localtime_r(&nowTt, &localTm) != nullptr) { #endif