diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c82064a..7adcc71 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -114,10 +114,19 @@ jobs: call scripts\build-windows.cmd release if errorlevel 1 exit /b 1 build\windows\procyon-cli.exe 1 300 + - name: Render a screen offscreen + # The app's own --screenshot mode (as in the Linux job): draws the Overview after a few + # samples into a PNG and exits, which exercises Direct2D, DirectWrite, the fonts and the sampler. + shell: pwsh + run: | + $p = Start-Process dist\windows\Procyon.exe -ArgumentList '--screenshot', 'dist\windows\overview.png', '--page', 'overview' -Wait -PassThru + if ($p.ExitCode -ne 0 -or -not (Test-Path dist\windows\overview.png)) { exit 1 } - uses: actions/upload-artifact@v7 with: name: Procyon-windows-${{ github.sha }} - path: dist\windows\Procyon.exe + path: | + dist\windows\Procyon.exe + dist\windows\overview.png retention-days: 7 windows-performance: @@ -181,3 +190,36 @@ jobs: dist/linux/procyon dist/linux/overview.png retention-days: 7 + + linux-performance: + name: Linux · Performance (${{ matrix.shard }}/${{ strategy.job-total }}) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3] + steps: + - uses: actions/checkout@v7 + - name: Install build tools and GTK 4 + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends build-essential cmake ninja-build pkg-config \ + libgtk-4-dev xvfb + - name: Build the app and the CLI + run: scripts/build-linux.sh release --no-tests + - name: Performance targets + # The Linux counterpart of the macOS and Windows jobs: its screens plus the background only + # state, measured from /proc on a virtual X display. Fails the build on a missed target. + # Xvfb has no GPU: GTK's GL renderer would run on Mesa's llvmpipe, whose buffers count as the + # app's private memory (3-4x its own), so the Cairo renderer measures Procyon itself. + run: >- + xvfb-run -a scripts/bench-linux.py --attempts 3 --renderer cairo + --shard ${{ matrix.shard }}/${{ strategy.job-total }} --output dist/bench-linux-${{ matrix.shard }}.json + - uses: actions/upload-artifact@v7 + if: always() + with: + name: bench-linux-${{ matrix.shard }}-${{ github.sha }} + path: dist/bench-linux-${{ matrix.shard }}.json + if-no-files-found: ignore + retention-days: 30 diff --git a/Makefile b/Makefile index 1bc12fa..702de07 100644 --- a/Makefile +++ b/Makefile @@ -33,8 +33,8 @@ run: app ## Build and open the app bench: ## Measure the app against the spec's performance targets (python: make tools fetches one) powershell -NoProfile -ExecutionPolicy Bypass -Command ". scripts\dev-env-windows.ps1; & (Find-Python) scripts\bench-windows.py; exit $$LASTEXITCODE" -screenshots: ## Retake the README screenshots (macOS only for now) - @echo screenshots is macOS only for now (scripts/screenshots.swift) +screenshots: app ## Render the main screens, light and dark, into dist\windows\screenshots + $(PS) scripts\screenshots-windows.ps1 format: ## Format C/C++ sources in place (and regenerate tokens when python is available) $(PS) scripts\format-windows.ps1 @@ -85,8 +85,8 @@ app: ## Release dist/linux/procyon (GTK 4, fonts embedded) run: app ## Build and open the app dist/linux/procyon -bench: ## (macOS and Windows) measure the app against the spec's targets - @echo "bench is not ported to Linux yet; procyon-cli prints the core's own overhead: build/linux/procyon-cli 10 1000" +bench: ## Measure the app against the spec's performance targets (needs a display; xvfb-run on CI) + scripts/bench-linux.py screenshots: app ## Render the main screens, light and dark, into dist/linux/screenshots @mkdir -p dist/linux/screenshots diff --git a/README.md b/README.md index 83cd97b..cc1cccd 100644 --- a/README.md +++ b/README.md @@ -171,10 +171,10 @@ Pick a screen in the sidebar, or use the keyboard: | `⇧⌘P` | Pause or resume updates | | `⌘,` | Settings | -On Windows, `Ctrl` stands in for `⌘`: `Ctrl+1`…`Ctrl+9` for the screens, `Ctrl+K` for the palette, `Ctrl+F` -to find, `Ctrl+I` for Get Info, `Delete` or `Ctrl+Backspace` for End Task, `Shift+Delete` or -`Ctrl+Alt+Backspace` for Force Quit, `Ctrl+Shift+Alt+Backspace` for End Process Tree, `Ctrl+Shift+P` to pause -and `Ctrl+,` for Settings. +On Windows and Linux, `Ctrl` stands in for `⌘`: `Ctrl+1`…`Ctrl+9` for the screens, `Ctrl+K` for the palette, +`Ctrl+F` to find, `Ctrl+I` for Get Info, `Delete` or `Ctrl+Backspace` for End Task, `Shift+Delete` or +`Ctrl+Alt+Backspace` for Force Quit, `Ctrl+Shift+Alt+Backspace` for End Process Tree, `Ctrl+Shift+P` to pause, +`Ctrl+,` for Settings and `Ctrl+Q` to quit. ### Ending a process diff --git a/apps/linux/src/platform_linux.cpp b/apps/linux/src/platform_linux.cpp index 213ccbd..0c738b1 100644 --- a/apps/linux/src/platform_linux.cpp +++ b/apps/linux/src/platform_linux.cpp @@ -2,12 +2,17 @@ // colour scheme, XDG folders for data and settings, the GDK clipboard. #include #include +#include #include +#include #include #include #include +#include +#include #include +#include #include "platform.hpp" #include "platform_linux.hpp" @@ -15,11 +20,41 @@ namespace procyon::ui::platform { namespace { +// The user this copy works for: the one who unlocked full access when pkexec started it as root +// (PKEXEC_UID), so the root copy keeps their settings and history; else the real user. +const passwd *pkexec_caller() { + static passwd entry{}; + static char buffer[4096]; + static const passwd *caller = []() -> const passwd * { + if (::geteuid() != 0) return nullptr; + const char *value = std::getenv("PKEXEC_UID"); + if (!value || !*value) return nullptr; + char *end = nullptr; + const unsigned long uid = std::strtoul(value, &end, 10); + if (!end || *end != '\0' || uid == 0) return nullptr; + passwd *result = nullptr; + return ::getpwuid_r(static_cast(uid), &entry, buffer, sizeof(buffer), &result) == 0 ? result : nullptr; + }(); + return caller; +} + +std::string home_folder() { + if (const passwd *caller = pkexec_caller(); caller && caller->pw_dir) return caller->pw_dir; + const char *home = std::getenv("HOME"); + return home ? home : "/tmp"; +} + std::string xdg_dir(const char *variable, const char *fallback) { + // pkexec passes the caller's XDG_CONFIG_HOME/XDG_DATA_HOME through when they set them. const char *value = std::getenv(variable); if (value && *value == '/') return value; - const char *home = std::getenv("HOME"); - return std::string(home ? home : "/tmp") + "/" + fallback; + return home_folder() + "/" + fallback; +} + +void give_back(const std::string &path) { + // Best effort: a file the user can't own stays root's and is rewritten next time as a new file. + const passwd *caller = pkexec_caller(); + if (caller && ::lchown(path.c_str(), caller->pw_uid, caller->pw_gid) != 0) return; } std::string settings_path() { return xdg_dir("XDG_CONFIG_HOME", ".config") + "/procyon/settings.ini"; } @@ -46,6 +81,17 @@ std::string lower(std::string s) { return s; } +// Programs that run many different apps' code: their name alone says nothing about which app a +// process is, so it never picks an icon (a desktop entry running "python3 tool.py" would otherwise +// give every Python process its icon). +bool interpreter(const std::string &name) { + if (name.rfind("python", 0) == 0) return true; + for (const char *i : {"sh", "bash", "dash", "zsh", "env", "perl", "ruby", "node", "java", "electron", "flatpak", + "snap", "gjs", "wine", "mono", "dotnet"}) + if (name == i) return true; + return false; +} + const AppIcons &app_icons() { static const AppIcons icons = [] { AppIcons result; @@ -71,11 +117,13 @@ const AppIcons &app_icons() { } } char *base = g_path_get_basename(program.c_str()); - add(lower(base)); + if (!interpreter(lower(base))) add(lower(base)); g_free(base); if (const char *wm = g_desktop_app_info_get_startup_wm_class(G_DESKTOP_APP_INFO(info))) add(lower(wm)); if (char *found = g_find_program_in_path(program.c_str())) { if (char *resolved = realpath(found, nullptr)) { + if (!interpreter(lower(program.substr(program.find_last_of('/') + 1)))) + add(std::string("path:") + resolved); char *dir = g_path_get_dirname(resolved); const std::string d = dir; if (d != "/usr/bin" && d != "/bin" && d != "/usr/local/bin" && d != "/usr/sbin" && d != "/snap/bin") @@ -123,14 +171,19 @@ std::shared_ptr app_icon(std::wstring_view path, int pixels) { if (path.empty() || pixels <= 0) return nullptr; const std::string file = fmt::to_utf8(path); const auto &icons = app_icons().by_key; - char *base = g_path_get_basename(file.c_str()); - auto it = icons.find(lower(base)); - g_free(base); + // The executable itself first, then the folder an app is installed in, then its name. + auto it = icons.find("path:" + file); if (it == icons.end()) { char *dir = g_path_get_dirname(file.c_str()); it = icons.find(std::string("dir:") + dir); g_free(dir); } + if (it == icons.end()) { + char *base = g_path_get_basename(file.c_str()); + const std::string name = lower(base); + g_free(base); + if (!interpreter(name)) it = icons.find(name); + } if (it == icons.end()) return nullptr; GdkDisplay *display = gdk_display_get_default(); if (!display) return nullptr; @@ -154,8 +207,10 @@ std::shared_ptr app_icon(std::wstring_view path, int pixels) { return image; } -bool system_prefers_dark() { - // GNOME (and the desktops that follow its setting): org.gnome.desktop.interface color-scheme. +namespace { + +// org.gnome.desktop.interface, where it has the color-scheme key (GNOME and the desktops that follow it). +GSettings *interface_settings() { static GSettings *interface = []() -> GSettings * { GSettingsSchemaSource *source = g_settings_schema_source_get_default(); GSettingsSchema *schema = @@ -165,7 +220,45 @@ bool system_prefers_dark() { g_settings_schema_unref(schema); return has_key ? g_settings_new("org.gnome.desktop.interface") : nullptr; }(); - if (interface) { + return interface; +} + +// GTK's dark preference as the desktop set it, before set_gtk_dark changed it for Procyon's windows. +std::optional desktop_prefers_dark_gtk; + +bool gtk_prefers_dark(GtkSettings *settings) { + if (desktop_prefers_dark_gtk) return *desktop_prefers_dark_gtk; + gboolean prefer_dark = FALSE; + g_object_get(settings, "gtk-application-prefer-dark-theme", &prefer_dark, nullptr); + return prefer_dark; +} + +} // namespace + +void set_gtk_dark(bool dark) { + GtkSettings *settings = gtk_settings_get_default(); + if (!settings) return; + if (!desktop_prefers_dark_gtk) desktop_prefers_dark_gtk = gtk_prefers_dark(settings); + gboolean current = FALSE; + g_object_get(settings, "gtk-application-prefer-dark-theme", ¤t, nullptr); + if (static_cast(current) != dark) + g_object_set(settings, "gtk-application-prefer-dark-theme", dark ? TRUE : FALSE, nullptr); +} + +void watch_color_scheme(std::function changed) { + static std::function callback; + callback = std::move(changed); + const auto notify = +[](gpointer, gpointer, gpointer) { + if (callback) callback(); + }; + if (GSettings *interface = interface_settings()) + g_signal_connect(interface, "changed::color-scheme", G_CALLBACK(notify), nullptr); + if (GtkSettings *settings = gtk_settings_get_default()) + g_signal_connect(settings, "notify::gtk-theme-name", G_CALLBACK(notify), nullptr); +} + +bool system_prefers_dark() { + if (GSettings *interface = interface_settings()) { gchar *scheme = g_settings_get_string(interface, "color-scheme"); const bool dark = scheme && g_strcmp0(scheme, "prefer-dark") == 0; const bool light = scheme && g_strcmp0(scheme, "prefer-light") == 0; @@ -174,10 +267,9 @@ bool system_prefers_dark() { } // Elsewhere: GTK's own preference, or a theme named "…-dark". if (GtkSettings *settings = gtk_settings_get_default()) { - gboolean prefer_dark = FALSE; gchar *theme = nullptr; - g_object_get(settings, "gtk-application-prefer-dark-theme", &prefer_dark, "gtk-theme-name", &theme, nullptr); - const bool dark = prefer_dark || (theme && g_str_has_suffix(theme, "-dark")); + g_object_get(settings, "gtk-theme-name", &theme, nullptr); + const bool dark = gtk_prefers_dark(settings) || (theme && g_str_has_suffix(theme, "-dark")); g_free(theme); return dark; } @@ -190,10 +282,21 @@ std::wstring data_file(std::wstring_view name) { void create_parent_directories(std::wstring_view path) { char *dir = g_path_get_dirname(fmt::to_utf8(path).c_str()); + // The folders this call creates, outermost last, to hand back to the pkexec caller. + std::vector created; + for (std::string d = dir; !d.empty() && d != "/" && !g_file_test(d.c_str(), G_FILE_TEST_EXISTS);) { + created.push_back(d); + char *parent = g_path_get_dirname(d.c_str()); + d = parent; + g_free(parent); + } g_mkdir_with_parents(dir, 0700); + for (const std::string &d : created) give_back(d); g_free(dir); } +void file_written(std::wstring_view path) { give_back(fmt::to_utf8(path)); } + std::wstring clipboard_text() { GdkDisplay *display = gdk_display_get_default(); if (!display) return {}; @@ -250,7 +353,7 @@ void write_setting(std::wstring_view group, std::wstring_view name, int64_t valu g_key_file_set_int64(file, g.c_str(), key.c_str(), value); const std::string path = settings_path(); create_parent_directories(fmt::from_utf8(path)); - g_key_file_save_to_file(file, path.c_str(), nullptr); + if (g_key_file_save_to_file(file, path.c_str(), nullptr)) give_back(path); } } // namespace procyon::ui::platform diff --git a/apps/linux/src/platform_linux.hpp b/apps/linux/src/platform_linux.hpp index eb04fbf..1035e30 100644 --- a/apps/linux/src/platform_linux.hpp +++ b/apps/linux/src/platform_linux.hpp @@ -1,8 +1,18 @@ // Linux-only additions to platform.hpp, for the pieces of the app that feed it. #pragma once +#include + namespace procyon::ui::platform { +// Makes GTK's own widgets (the window frame and its controls, menus, dialogs) light or dark with +// Procyon's appearance, also when Settings forces one against the desktop's. +void set_gtk_dark(bool dark); + +// Calls `changed` on the main loop when the desktop's colour scheme or GTK theme changes, so a +// "System" appearance follows it at once rather than at the next repaint. +void watch_color_scheme(std::function changed); + // Set by the tray as a StatusNotifierWatcher comes and goes; read through tray_available(). void set_tray_available(bool available); diff --git a/apps/linux/src/tray_linux.cpp b/apps/linux/src/tray_linux.cpp index 89b438a..d56636e 100644 --- a/apps/linux/src/tray_linux.cpp +++ b/apps/linux/src/tray_linux.cpp @@ -99,7 +99,7 @@ constexpr const char *kMenuXml = R"xml( )xml"; -enum MenuId { MenuRoot = 0, MenuOpen = 1, MenuPause = 2, MenuSeparator = 3, MenuQuit = 4 }; +enum MenuId { MenuRoot = 0, MenuOpen = 1, MenuPause = 2, MenuSeparator = 3, MenuQuit = 4, MenuSettings = 5 }; const GDBusInterfaceVTable kVTable = {&Tray::on_method, &Tray::on_property, nullptr, {}}; @@ -269,6 +269,7 @@ GVariant *Tray::layout() const { g_variant_builder_add( &children, "v", menu_item(MenuPause, {{"label", g_variant_new_string(paused_ ? "Resume updates" : "Pause updates")}})); + g_variant_builder_add(&children, "v", menu_item(MenuSettings, {{"label", g_variant_new_string("Settings…")}})); g_variant_builder_add(&children, "v", menu_item(MenuSeparator, {{"type", g_variant_new_string("separator")}})); g_variant_builder_add(&children, "v", menu_item(MenuQuit, {{"label", g_variant_new_string("Quit")}})); GVariantBuilder props; @@ -333,6 +334,13 @@ GVariant *Tray::menu_property(const char *property) { return nullptr; } +void Tray::clicked(int id) { + if (id == MenuOpen && callbacks_.activate) callbacks_.activate(); + if (id == MenuPause && callbacks_.toggle_pause) callbacks_.toggle_pause(); + if (id == MenuSettings && callbacks_.settings) callbacks_.settings(); + if (id == MenuQuit && callbacks_.quit) callbacks_.quit(); +} + void Tray::menu_method(const char *method, GVariant *parameters, GDBusMethodInvocation *invocation) { if (g_str_equal(method, "GetLayout")) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(u@(ia{sv}av))", revision_, layout())); @@ -343,9 +351,7 @@ void Tray::menu_method(const char *method, GVariant *parameters, GDBusMethodInvo g_dbus_method_invocation_return_value(invocation, nullptr); if (g_str_equal(event, "clicked")) { // After replying: Quit tears the object down. - if (id == MenuOpen && callbacks_.activate) callbacks_.activate(); - if (id == MenuPause && callbacks_.toggle_pause) callbacks_.toggle_pause(); - if (id == MenuQuit && callbacks_.quit) callbacks_.quit(); + clicked(id); } } else if (g_str_equal(method, "EventGroup")) { GVariantIter *events = nullptr; @@ -358,11 +364,7 @@ void Tray::menu_method(const char *method, GVariant *parameters, GDBusMethodInvo g_variant_iter_free(events); g_dbus_method_invocation_return_value( invocation, g_variant_new("(@ai)", g_variant_new_array(G_VARIANT_TYPE_INT32, nullptr, 0))); - for (int c : clicked) { - if (c == MenuOpen && callbacks_.activate) callbacks_.activate(); - if (c == MenuPause && callbacks_.toggle_pause) callbacks_.toggle_pause(); - if (c == MenuQuit && callbacks_.quit) callbacks_.quit(); - } + for (int c : clicked) this->clicked(c); } else if (g_str_equal(method, "AboutToShow")) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(b)", FALSE)); } else if (g_str_equal(method, "AboutToShowGroup")) { diff --git a/apps/linux/src/tray_linux.hpp b/apps/linux/src/tray_linux.hpp index 8272afe..787f723 100644 --- a/apps/linux/src/tray_linux.hpp +++ b/apps/linux/src/tray_linux.hpp @@ -14,6 +14,7 @@ class Tray { struct Callbacks { std::function activate; // left click: open or hide the window std::function toggle_pause; + std::function settings; // Settings…: the window on its Settings page std::function quit; }; @@ -40,6 +41,7 @@ class Tray { const char *property, GError **, gpointer self); private: + void clicked(int id); // a menu item, by its MenuId void item_method(const char *method, GVariant *parameters, GDBusMethodInvocation *invocation); void menu_method(const char *method, GVariant *parameters, GDBusMethodInvocation *invocation); GVariant *item_property(const char *property); diff --git a/apps/linux/src/window.cpp b/apps/linux/src/window.cpp index 29f6b9e..33b61b5 100644 --- a/apps/linux/src/window.cpp +++ b/apps/linux/src/window.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -88,8 +89,13 @@ class MainWindow : public Host { int width = 1280, height = 800; }; - MainWindow(GtkApplication *app, std::optional initial, bool persist, std::optional screenshot) - : app_(app), initial_page_(initial), persist_(persist), screenshot_(std::move(screenshot)) {} + MainWindow(GtkApplication *app, std::optional initial, bool persist, std::optional screenshot, + bool background = false) + : app_(app), + initial_page_(initial), + persist_(persist), + screenshot_(std::move(screenshot)), + start_in_background_(background) {} ~MainWindow() override { *alive_ = false; } @@ -183,32 +189,54 @@ class MainWindow : public Host { return true; }); navigate(initial_page_.value_or(PageId::Overview)); - if (!screenshot_) { - tray_ = std::make_unique( - Tray::Callbacks{[this] { hidden_ ? present() : gtk_window_present(GTK_WINDOW(window_)); }, - [this] { set_paused(!store_.paused()); }, [this] { quit(); }}); - } + if (!screenshot_) make_tray(); + // A "System" appearance follows the desktop at once, also while paused and idle. + if (!screenshot_) platform::watch_color_scheme([this] { repaint(); }); if (screenshot_) { settings_.theme = screenshot_->theme; g_application_hold(G_APPLICATION(app_)); held_ = true; return; } + // --background: running without a window from the start, as when it was closed (the macOS app's + // -launchInMenuBar); measured by scripts/bench-linux.py. + if (start_in_background_) { + hide_window(); + return; + } gtk_window_present(GTK_WINDOW(window_)); gtk_widget_grab_focus(area_); } - // A second launch while Procyon runs in the background brings the window back. + void make_tray() { + tray_ = std::make_unique( + Tray::Callbacks{[this] { hidden_ ? present() : gtk_window_present(GTK_WINDOW(window_)); }, + [this] { set_paused(!store_.paused()); }, + [this] { + present(); + navigate(PageId::Settings); + }, + [this] { quit(); }}); + if (store_.paused()) tray_->set_paused(true); + } + + bool failed() const { return failed_; } + + // A second launch while Procyon runs in the background brings the window back. While the root + // copy runs in this one's place, that copy's window is the one to use: this one stays hidden. void present() { + if (handed_over_) return; if (hidden_) show_again(); gtk_window_present(GTK_WINDOW(window_)); } void shutdown() { if (!window_) return; - save_settings(); + // After the root copy took over, its settings and history are the current ones: this copy + // writes neither. + if (!handed_over_) save_settings(); store_.stop(); - store_.flush_history(); // the minute in progress would otherwise go with the process + if (!handed_over_) store_.flush_history(); // the minute in progress would otherwise go with the process if (held_) g_application_release(G_APPLICATION(app_)); held_ = false; tray_.reset(); @@ -245,6 +273,11 @@ class MainWindow : public Host { float mouse_y() override { return overlays_.empty() ? mouse_y_ : -1; } void navigate(PageId id) override { + // A screen this machine doesn't have (a shortcut, --page): stay, or start on Overview. + if (!page_available(store_, id)) { + if (current_) return; + id = PageId::Overview; + } for (auto &page : pages_) { if (page->id() != id) continue; current_ = page.get(); @@ -345,7 +378,10 @@ class MainWindow : public Host { if (n <= 0) return; exe[n] = '\0'; std::vector args{"pkexec", "env"}; - for (const char *name : {"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "XDG_CURRENT_DESKTOP"}) + // The display, and the user's own config and data folders: the root copy reads the same + // settings and keeps the same history (pkexec resets HOME; PKEXEC_UID names the user). + for (const char *name : {"DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "XDG_RUNTIME_DIR", "XDG_CURRENT_DESKTOP", + "XDG_CONFIG_HOME", "XDG_DATA_HOME"}) if (const char *value = g_getenv(name)) args.push_back(std::string(name) + "=" + value); args.emplace_back(exe); args.emplace_back("--page"); @@ -354,6 +390,7 @@ class MainWindow : public Host { for (auto &a : args) argv.push_back(a.data()); argv.push_back(nullptr); save_settings(); + store_.flush_history(); GPid child = 0; GError *error = nullptr; if (!g_spawn_async(nullptr, argv.data(), nullptr, @@ -363,17 +400,30 @@ class MainWindow : public Host { if (error) g_error_free(error); return; } + // Hand over to the root copy: one tray icon, one sampler, one writer of the settings and the + // history. This copy waits hidden, without updates, until the root copy ends. + handed_over_ = true; + paused_before_handover_ = store_.paused(); + store_.set_paused(true); + store_.set_records_history(false); + tray_.reset(); hide_window(); + handover_started_ = g_get_monotonic_time(); g_child_watch_add( child, [](GPid pid, gint status, gpointer self) { g_spawn_close_pid(pid); auto *w = static_cast(self); - // 126: the authorization dialog was dismissed; 127: not authorized. + // 126: the authorization dialog was dismissed; 127: not authorized. A root copy that + // fails within seconds of starting didn't get to show a window either. const int code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; - if (code == 126 || code == 127) { - w->show_again(); - gtk_window_present(GTK_WINDOW(w->window_)); + const bool early = g_get_monotonic_time() - w->handover_started_ < 5 * G_USEC_PER_SEC; + if (code == 126 || code == 127 || (code != 0 && early)) { + w->take_back(); + if (code != 126 && code != 127) + w->alert(L"Couldn't run Procyon as root", L"The root copy stopped as it started (exit status " + + std::to_wstring(code) + + L"). Procyon keeps running as your user."); } else { w->quit(); } @@ -536,9 +586,9 @@ class MainWindow : public Host { GtkEventController *keys = gtk_event_controller_key_new(); g_signal_connect(keys, "key-pressed", - G_CALLBACK(+[](GtkEventControllerKey *, guint keyval, guint, GdkModifierType state, + G_CALLBACK(+[](GtkEventControllerKey *, guint keyval, guint keycode, GdkModifierType state, gpointer self) -> gboolean { - return static_cast(self)->on_key(keyval, state); + return static_cast(self)->on_key(keyval, keycode, state); }), this); gtk_widget_add_controller(area_, keys); @@ -648,14 +698,19 @@ class MainWindow : public Host { } // The accelerator table of the Windows app (res/Procyon.rc), plus Ctrl+Q. - int shortcut(guint keyval, bool ctrl, bool shift, bool alt) const { + int shortcut(guint keyval, guint keycode, bool ctrl, bool shift, bool alt) const { const guint key = gdk_keyval_to_lower(keyval); if (ctrl && !alt && !shift) { - if (key >= GDK_KEY_1 && key <= GDK_KEY_9) { + // Ctrl+1…9 by the key's place on the number row, like the Windows app's virtual keys: on + // layouts whose digits need Shift (AZERTY) the unshifted keyval is "&", "é", …. + // XKB keycodes 10-18 are the row's 1-9 keys whatever the layout. + guint digit = key >= GDK_KEY_1 && key <= GDK_KEY_9 ? key - GDK_KEY_1 : 9; + if (digit == 9 && keycode >= 10 && keycode <= 18) digit = keycode - 10; + if (digit < 9) { static const int pages[] = {IDM_PAGE_OVERVIEW, IDM_PAGE_PROCESSES, IDM_PAGE_CPU, IDM_PAGE_MEMORY, IDM_PAGE_GPU, IDM_PAGE_DISK, IDM_PAGE_NETWORK, IDM_PAGE_STARTUP, IDM_PAGE_SERVICES}; - return pages[key - GDK_KEY_1]; + return pages[digit]; } switch (key) { case GDK_KEY_k: return IDM_PALETTE; @@ -675,7 +730,7 @@ class MainWindow : public Host { return 0; } - gboolean on_key(guint keyval, GdkModifierType state) { + gboolean on_key(guint keyval, guint keycode, GdkModifierType state) { const bool ctrl = (state & GDK_CONTROL_MASK) != 0, shift = (state & GDK_SHIFT_MASK) != 0, alt = (state & GDK_ALT_MASK) != 0; KeyEvent e; @@ -687,11 +742,12 @@ class MainWindow : public Host { e.shift = shift; e.alt = alt; - // A search field keeps Delete, Backspace and Return for itself. + // A search field keeps Delete, Backspace and Return for itself, also with Ctrl (Ctrl+Backspace + // deletes a word there), as the macOS app turns End Task off while its search field has focus. const bool text_input = !overlays_.empty() || (current_ && current_->search_focused()); const bool editing_key = e.key == Key::Delete || e.key == Key::Back || e.key == Key::Return; - if (!(text_input && editing_key && !ctrl)) { - if (const int command = shortcut(keyval, ctrl, shift, alt)) { + if (!(text_input && editing_key)) { + if (const int command = shortcut(keyval, keycode, ctrl, shift, alt)) { on_command(command); repaint(); return TRUE; @@ -768,15 +824,11 @@ class MainWindow : public Host { case IDM_PAGE_PROCESSES: navigate(PageId::Processes); break; case IDM_PAGE_CPU: navigate(PageId::Cpu); break; case IDM_PAGE_MEMORY: navigate(PageId::Memory); break; - case IDM_PAGE_GPU: - if (store_.has(PC_CAP_GPU)) navigate(PageId::Gpu); - break; + case IDM_PAGE_GPU: navigate(PageId::Gpu); break; case IDM_PAGE_DISK: navigate(PageId::Disk); break; case IDM_PAGE_NETWORK: navigate(PageId::Network); break; case IDM_PAGE_STARTUP: navigate(PageId::Startup); break; - case IDM_PAGE_SERVICES: - if (store_.has(PC_CAP_SERVICES)) navigate(PageId::Services); - break; + case IDM_PAGE_SERVICES: navigate(PageId::Services); break; case IDM_PAGE_HISTORY: navigate(PageId::History); break; case IDM_PAGE_INSPECT: navigate(PageId::Inspect); break; case IDM_PAGE_SYSTEM: navigate(PageId::System); break; @@ -809,22 +861,37 @@ class MainWindow : public Host { } void open_palette() { + // Ctrl+K again closes it, as ⌘K toggles the macOS palette. + bool was_open = false; + for (auto &overlay : overlays_) + if (overlay->is_palette() && !overlay->closed()) { + overlay->close(); + was_open = true; + } + if (was_open) { + overlays_.erase( + std::remove_if(overlays_.begin(), overlays_.end(), [](const auto &o) { return o->closed(); }), + overlays_.end()); + repaint(); + return; + } std::vector items; auto screen = [&](PageId id, const wchar_t *title, const wchar_t *shortcut) { + if (!page_available(store_, id)) return; items.push_back({PaletteItem::Kind::Screen, title, L"", shortcut, [this, id] { navigate(id); }}); }; screen(PageId::Overview, L"Overview", L"Ctrl+1"); screen(PageId::Processes, L"Processes", L"Ctrl+2"); screen(PageId::Cpu, L"CPU", L"Ctrl+3"); screen(PageId::Memory, L"Memory", L"Ctrl+4"); - if (store_.has(PC_CAP_GPU)) screen(PageId::Gpu, L"GPU", L"Ctrl+5"); + screen(PageId::Gpu, L"GPU", L"Ctrl+5"); screen(PageId::Disk, L"Disk", L"Ctrl+6"); screen(PageId::Network, L"Network", L"Ctrl+7"); screen(PageId::Startup, L"Startup", L"Ctrl+8"); - if (store_.has(PC_CAP_SERVICES)) screen(PageId::Services, L"Services", L"Ctrl+9"); + screen(PageId::Services, L"Services", L"Ctrl+9"); screen(PageId::History, L"History", L""); screen(PageId::Inspect, L"Files & Ports", L""); - if (store_.has(PC_CAP_BATTERY)) screen(PageId::Battery, L"Battery", L""); + screen(PageId::Battery, L"Battery", L""); screen(PageId::System, L"System", L""); screen(PageId::Settings, L"Settings", L"Ctrl+,"); items.push_back({PaletteItem::Kind::Command, store_.paused() ? L"Resume updates" : L"Pause updates", L"", @@ -859,9 +926,10 @@ class MainWindow : public Host { : L""; const int32_t pid = row.is_group() ? row.group_pid : p ? p->pid : 0; if (name.empty() || pid <= 0) continue; + // Opens the app's actions, the macOS palette's second level. PaletteItem item{PaletteItem::Kind::App, name, - L"CPU " + fmt::cpu(row.cpu_percent) + L" · " + fmt::bytes(row.memory_bytes), L"", - [this, pid] { show_info(pid); }}; + L"CPU " + fmt::cpu(row.cpu_percent) + L" · " + fmt::bytes(row.memory_bytes), L"", nullptr}; + item.children = app_palette_actions(*this, row, p, name, [this](int id) { on_command(id); }); item.icon_path = app_icon_path(row, p, s); item.icon_system = p && (p->flags & PC_PROC_SYSTEM) != 0; items.push_back(std::move(item)); @@ -901,19 +969,19 @@ class MainWindow : public Host { section(L"Performance"); metric(PageId::Cpu, L"CPU", MetricKind::Cpu); metric(PageId::Memory, L"Memory", MetricKind::Memory); - if (store_.has(PC_CAP_GPU)) metric(PageId::Gpu, L"GPU", MetricKind::Gpu); + if (page_available(store_, PageId::Gpu)) metric(PageId::Gpu, L"GPU", MetricKind::Gpu); metric(PageId::Disk, L"Disk", MetricKind::Disk); metric(PageId::Network, L"Network", MetricKind::Network); - if (store_.has(PC_CAP_STARTUP) || store_.has(PC_CAP_SERVICES)) { + if (page_available(store_, PageId::Startup) || page_available(store_, PageId::Services)) { section(L"Manage"); - if (store_.has(PC_CAP_STARTUP)) page(PageId::Startup, L"Startup", Renderer::Symbol::Power); - if (store_.has(PC_CAP_SERVICES)) page(PageId::Services, L"Services", Renderer::Symbol::Gears); + if (page_available(store_, PageId::Startup)) page(PageId::Startup, L"Startup", Renderer::Symbol::Power); + if (page_available(store_, PageId::Services)) page(PageId::Services, L"Services", Renderer::Symbol::Gears); } section(L"Analyze"); page(PageId::History, L"History", Renderer::Symbol::Clock); - if (store_.has(PC_CAP_CONNECTIONS)) page(PageId::Inspect, L"Files & Ports", Renderer::Symbol::Ports); + if (page_available(store_, PageId::Inspect)) page(PageId::Inspect, L"Files & Ports", Renderer::Symbol::Ports); section(L"Machine"); - if (store_.has(PC_CAP_BATTERY)) page(PageId::Battery, L"Battery", Renderer::Symbol::Gauge); + if (page_available(store_, PageId::Battery)) page(PageId::Battery, L"Battery", Renderer::Symbol::Gauge); page(PageId::System, L"System", Renderer::Symbol::Info); } @@ -924,19 +992,17 @@ class MainWindow : public Host { case PageId::Overview: return display_model(info); case PageId::Processes: return store_.has_snapshot() ? fmt::count(s.process_count) + L" running" : L" "; case PageId::Startup: return L"Apps that start at login"; - case PageId::Services: return L"systemd services"; + case PageId::Services: return L"Background services"; case PageId::History: return store_.records_history() ? L"The last 24 hours" : L"Off"; case PageId::Inspect: return L"Who uses a port or a file"; case PageId::Battery: { - if (auto b = store_.battery()) - return fmt::percent(b->level) + L" · " + - (b->charging ? L"Charging" - : b->on_ac_power ? L"On AC power" - : L"On battery"); + if (auto b = store_.battery()) return fmt::percent(b->level) + L" · " + battery_state(*b); return L""; } case PageId::System: return fmt::from_utf8(info.os_name) + L" " + fmt::from_utf8(info.os_version); - case PageId::Settings: return L"Updates, alerts, appearance"; + case PageId::Settings: + return platform::tray_available() ? L"Updates, tray, alerts, appearance" + : L"Updates, alerts, appearance"; default: return L""; } } @@ -944,6 +1010,15 @@ class MainWindow : public Host { void paint(cairo_t *cr, int width, int height, float scale = 0) { const bool dark = settings_.theme == 2 || (settings_.theme == 0 && platform::system_prefers_dark()); theme_.dark = dark; + if (!screenshot_) platform::set_gtk_dark(dark); + // PROCYON_BENCH: tell the benchmark when the first frame is drawn (its startup measurement). + if (!first_frame_reported_ && !screenshot_) { + first_frame_reported_ = true; + if (g_getenv("PROCYON_BENCH")) { + std::fputs("procyon: first frame\n", stderr); + std::fflush(stderr); + } + } renderer_.set_theme(theme_); if (scale <= 0) { scale = 1; @@ -1105,14 +1180,14 @@ class MainWindow : public Host { options.end_dot = false; options.halo = false; options.line_width = 1.25f; - r.sparkline(Rect{spark.x, spark.cy() - 11, spark.w, 22}, series->data(), series->size(), kHistoryWindow, - max, item.metric, options); + r.sparkline(Rect{spark.x, spark.cy() - 11, spark.w, 22}, series->data(), series->size(), + history_window(), max, item.metric, options); if (secondary && secondary->size() > 1) { options.area = false; Color end = rgba(metric_style(item.metric).end); options.color_override = &end; r.sparkline(Rect{spark.x, spark.cy() - 11, spark.w, 22}, secondary->data(), secondary->size(), - kHistoryWindow, max, item.metric, options); + history_window(), max, item.metric, options); } } } @@ -1149,7 +1224,10 @@ class MainWindow : public Host { cairo_destroy(cr); const cairo_status_t status = cairo_surface_write_to_png(surface, shot.path.c_str()); cairo_surface_destroy(surface); - if (status != CAIRO_STATUS_SUCCESS) g_printerr("procyon: couldn't write %s\n", shot.path.c_str()); + if (status != CAIRO_STATUS_SUCCESS) { + g_printerr("procyon: couldn't write %s\n", shot.path.c_str()); + failed_ = true; // a non-zero exit status, so CI notices + } quit(); } @@ -1184,14 +1262,12 @@ class MainWindow : public Host { tip += (tip.empty() ? L"" : L" · ") + long_form; }; const int modules = settings_.tray_modules; - if (store_.paused()) { - tip = L"Paused"; - } else if (store_.has_snapshot()) { + // Paused, the last figures stay (as the macOS menu bar keeps them) and the tooltip says so. + if (store_.has_snapshot()) { if (modules & 1) add(L"CPU " + fmt::percent(s.cpu_usage), L"CPU 100%", L"CPU " + fmt::percent(s.cpu_usage)); if (modules & 2) { const double used = s.memory_total ? static_cast(s.memory_used) / s.memory_total : 0; - add(L"MEM " + fmt::percent(used), L"MEM 100%", - L"Memory " + fmt::bytes(static_cast(s.memory_used))); + add(L"MEM " + fmt::percent(used), L"MEM 100%", L"Memory " + fmt::percent(used)); } if (modules & 4) add(L"↓" + compact_rate(s.net_rx_bps) + L" ↑" + compact_rate(s.net_tx_bps), L"↓888M ↑888M", @@ -1207,6 +1283,7 @@ class MainWindow : public Host { if (auto b = store_.battery(); b && b->present) add(L"BAT " + fmt::percent(b->level), L"BAT 100%", L"Battery " + fmt::percent(b->level)); } + if (store_.paused()) tip = tip.empty() ? L"Paused" : L"Paused · " + tip; tray_->set_label(fmt::to_utf8(label), fmt::to_utf8(guide)); tray_->set_tooltip(fmt::to_utf8(tip)); } @@ -1216,7 +1293,11 @@ class MainWindow : public Host { GNotification *notification = g_notification_new(fmt::to_utf8(event.title).c_str()); g_notification_set_body(notification, fmt::to_utf8(event.message).c_str()); g_notification_set_priority(notification, G_NOTIFICATION_PRIORITY_HIGH); - g_application_send_notification(G_APPLICATION(app_), "procyon-alert", notification); + // One notification per rule (and app): different alerts stand side by side, as on macOS and + // Windows, while a rule that fires again after its cooldown replaces its own older one. + const std::string id = "alert-" + std::to_string(static_cast(event.kind)) + + (event.app_id.empty() ? std::string() : "-" + event.app_id); + g_application_send_notification(G_APPLICATION(app_), id.c_str(), notification); g_object_unref(notification); repaint(); } @@ -1260,6 +1341,17 @@ class MainWindow : public Host { shutdown(); } + // The root copy didn't take over (authorization dismissed, or it failed to start): this copy + // resumes as it was. + void take_back() { + handed_over_ = false; + store_.set_records_history(settings_.records_history); + store_.set_paused(paused_before_handover_); + if (!screenshot_) make_tray(); + show_again(); + gtk_window_present(GTK_WINDOW(window_)); + } + static bool can_elevate() { static const bool found = [] { char *path = g_find_program_in_path("pkexec"); @@ -1322,7 +1414,13 @@ class MainWindow : public Host { bool persist_ = true; std::optional screenshot_; int screenshot_samples_ = 0; + bool failed_ = false; + bool start_in_background_ = false; + bool first_frame_reported_ = false; std::unique_ptr tray_; + bool handed_over_ = false; // a root copy runs in this one's place + bool paused_before_handover_ = false; + gint64 handover_started_ = 0; std::shared_ptr alive_ = std::make_shared(true); GtkWidget *window_ = nullptr; GtkWidget *area_ = nullptr; @@ -1352,6 +1450,7 @@ class MainWindow : public Host { struct App { std::optional initial; bool persist = true; + bool background = false; std::optional screenshot; std::unique_ptr window; }; @@ -1367,6 +1466,8 @@ int run_app(int argc, char **argv) { app.initial = page_from_name(argv[++i]); else if (arg == "--no-settings") app.persist = false; + else if (arg == "--background") + app.background = true; else if (arg == "--screenshot" && i + 1 < argc) { if (!app.screenshot) app.screenshot.emplace(); app.screenshot->path = argv[++i]; @@ -1381,8 +1482,9 @@ int run_app(int argc, char **argv) { } g_set_prgname(kAppId); g_set_application_name("Procyon"); - // One instance per user session; the root copy (Full access) and screenshots run beside it. - const bool separate = ::geteuid() == 0 || (app.screenshot && !app.screenshot->path.empty()); + // One instance per user session; the root copy (Full access), screenshots and measurements + // (--no-settings) run beside it. + const bool separate = ::geteuid() == 0 || (app.screenshot && !app.screenshot->path.empty()) || !app.persist; GtkApplication *gtk_app = gtk_application_new(kAppId, separate ? G_APPLICATION_NON_UNIQUE : G_APPLICATION_DEFAULT_FLAGS); g_signal_connect(gtk_app, "activate", G_CALLBACK(+[](GtkApplication *a, gpointer data) { @@ -1391,13 +1493,14 @@ int run_app(int argc, char **argv) { state->window->present(); return; } - state->window = - std::make_unique(a, state->initial, state->persist, state->screenshot); + state->window = std::make_unique(a, state->initial, state->persist, + state->screenshot, state->background); state->window->create(); }), &app); char *gtk_argv[] = {argv[0], nullptr}; - const int status = g_application_run(G_APPLICATION(gtk_app), 1, gtk_argv); + int status = g_application_run(G_APPLICATION(gtk_app), 1, gtk_argv); + if (app.window && app.window->failed() && status == 0) status = 1; if (app.window) app.window->shutdown(); app.window.reset(); g_object_unref(gtk_app); diff --git a/apps/ui/src/alerts.hpp b/apps/ui/src/alerts.hpp index 64cfe55..34d62bb 100644 --- a/apps/ui/src/alerts.hpp +++ b/apps/ui/src/alerts.hpp @@ -45,7 +45,8 @@ struct AlertRule { bool operator!=(const AlertRule &o) const { return !(*this == o); } }; -// Every rule, persisted under HKCU\Software\Procyon\Alerts. +// Every rule, persisted in the settings' "Alerts" group (HKCU\Software\Procyon\Alerts on Windows, +// [Alerts] in ~/.config/procyon/settings.ini on Linux). struct AlertSettings { static constexpr double kDurations[] = {10, 30, 60, 300, 900}; diff --git a/apps/ui/src/format.cpp b/apps/ui/src/format.cpp index 85b7b0a..ec75e65 100644 --- a/apps/ui/src/format.cpp +++ b/apps/ui/src/format.cpp @@ -59,6 +59,11 @@ std::wstring bytes(int64_t value) { return bytes(static_cast(value)); } +std::wstring endpoint(std::wstring_view address, int port) { + const std::wstring a(address); + return (a.find(L':') != std::wstring::npos ? L"[" + a + L"]" : a) + L":" + std::to_wstring(port); +} + std::wstring rate(double value) { if (!std::isfinite(value) || value < 0) return unavailable; if (value < 1024) return fixed(std::floor(value), 0) + L" B/s"; diff --git a/apps/ui/src/history.cpp b/apps/ui/src/history.cpp index 28eb39c..04db4c5 100644 --- a/apps/ui/src/history.cpp +++ b/apps/ui/src/history.cpp @@ -290,6 +290,8 @@ bool HistoryDatabase::append(const MinuteRecord &record) { const auto length = static_cast(w.bytes.size()); file.write(reinterpret_cast(&length), sizeof(length)); file.write(w.bytes.data(), static_cast(w.bytes.size())); + file.close(); + if (fresh) platform::file_written(path_); return static_cast(file); } @@ -315,6 +317,7 @@ void HistoryDatabase::rewrite() { } std::error_code error; std::filesystem::rename(std::filesystem::path(temp), std::filesystem::path(path_), error); // replaces + if (!error) platform::file_written(path_); } void HistoryDatabase::write(const MinuteRecord &record) { diff --git a/apps/ui/src/history.hpp b/apps/ui/src/history.hpp index 2cc87e4..fbc1187 100644 --- a/apps/ui/src/history.hpp +++ b/apps/ui/src/history.hpp @@ -92,8 +92,8 @@ class HistoryRecorder { enum class AppOrder { Cpu, Memory, Disk, Network, Gpu }; // The history on disk: one record per minute with the busy apps of that minute, appended to a -// file under %LOCALAPPDATA%\Procyon and compacted now and then. Everything is also kept in memory -// (a day is 1,440 minutes), so queries don't touch the disk. +// file in the data folder (%LOCALAPPDATA%\Procyon, ~/.local/share/procyon) and compacted now and then. Everything is +// also kept in memory (a day is 1,440 minutes), so queries don't touch the disk. class HistoryDatabase { public: static constexpr int64_t kRetention = 24 * 3600; // how far back the history goes, seconds diff --git a/apps/ui/src/os.hpp b/apps/ui/src/os.hpp index f961a6e..697b94f 100644 --- a/apps/ui/src/os.hpp +++ b/apps/ui/src/os.hpp @@ -10,21 +10,51 @@ inline constexpr const wchar_t *name = L"Windows"; inline constexpr const wchar_t *admin = L"administrator"; inline constexpr const wchar_t *elevation = L"Procyon restarts once, with a UAC prompt."; inline constexpr const wchar_t *file_manager = L"Explorer"; +// How paths are spelt: the separator, and whether two spellings differing in case are one file. +inline constexpr wchar_t path_separator = L'\\'; +inline constexpr bool paths_ignore_case = true; // Machine-wide services and startup entries only change from an elevated Procyon. inline constexpr bool system_services_need_elevation = true; inline constexpr bool machine_startup_needs_elevation = true; // What the per-app network figures leave out, shown under them; null when they count everything. inline constexpr const wchar_t *process_network_note = nullptr; +// Per-app network needs Procyon elevated (an ETW session takes administrator rights). +inline constexpr bool process_network_needs_elevation = true; +// The CPU temperature's source: Windows has no user-mode way to the die sensor, so the hottest ACPI +// zone stands in, and a zone that never moves is the board's fixed reading (said so on the CPU screen). +inline constexpr bool cpu_sensor_is_firmware_zone = true; +inline constexpr const wchar_t *cpu_sensor_label = L"Hottest ACPI zone"; +inline constexpr const wchar_t *cpu_sensor_detail = L"Hottest ACPI zone"; +// Memory composition and swap in the words of the OS's own tools (Task Manager here). +inline constexpr const wchar_t *memory_wired = L"Kernel"; +inline constexpr const wchar_t *memory_wired_detail = L"Kernel (non-paged)"; +inline constexpr const wchar_t *memory_cached = L"Standby"; +inline constexpr const wchar_t *memory_cached_detail = L"Standby (cached)"; +inline constexpr const wchar_t *swap_name = L"Page file"; +// What Full Access changes, after "Full access runs Procyon as ." in Settings. +inline constexpr const wchar_t *full_access_caption = + L"It lets Processes read and manage system processes, Files & Ports list every process's files and " + L"connections, Startup and Services switch machine-wide entries, and shows which apps keep the PC awake and " + L"how much network each process uses. Without it, those rows show a lock."; // Where the chosen figures show, and whether the tray icon is there while the window is open too. +// The icon stays while the window is open too: alerts are shown as its notifications. inline constexpr const wchar_t *tray_figures = - L"Closing the window moves Procyon to the notification area, with the chosen figures in the icon's tooltip " - L"and the busiest apps one click away. Opening the window brings it back."; -inline constexpr bool tray_while_open = false; + L"The chosen figures show in the notification-area icon's tooltip. Closing the window keeps Procyon " + L"there; click the icon to open it again."; +inline constexpr bool tray_while_open = true; +// Whether a process's nice value is its own (Linux) or stands for a priority class (Windows). +inline constexpr bool nice_is_exact = false; +// The name of a pid that owns sockets without being in the process list (the kernel's own). +inline constexpr const wchar_t *unlisted_process_name(int pid) { + return pid == 4 ? L"System" : pid == 0 ? L"System Idle Process" : nullptr; +} #else inline constexpr const wchar_t *name = L"Linux"; inline constexpr const wchar_t *admin = L"root"; inline constexpr const wchar_t *elevation = L"Procyon restarts once as root, after a password prompt."; inline constexpr const wchar_t *file_manager = L"Files"; +inline constexpr wchar_t path_separator = L'/'; +inline constexpr bool paths_ignore_case = false; // systemctl asks polkit (the desktop's password dialog) for each system-service change, and a // machine-wide autostart entry is switched by a per-user override: neither needs Procyon as root. inline constexpr bool system_services_need_elevation = false; @@ -32,10 +62,28 @@ inline constexpr bool machine_startup_needs_elevation = false; inline constexpr const wchar_t *process_network_note = L"Per-app figures count TCP only: QUIC and other UDP traffic (much of a browser's video) isn't attributed to " L"apps, and other users' apps need full access."; +inline constexpr bool process_network_needs_elevation = false; +inline constexpr bool cpu_sensor_is_firmware_zone = false; +inline constexpr const wchar_t *cpu_sensor_label = L"CPU (hottest sensor)"; +inline constexpr const wchar_t *cpu_sensor_detail = L"Hottest die sensor"; +// Unreclaimable kernel memory and the page cache, in macOS's words. +inline constexpr const wchar_t *memory_wired = L"Wired"; +inline constexpr const wchar_t *memory_wired_detail = L"Wired"; +inline constexpr const wchar_t *memory_cached = L"Cached files"; +inline constexpr const wchar_t *memory_cached_detail = L"Cached files"; +inline constexpr const wchar_t *swap_name = L"Swap"; +// Services ask polkit per action, autostart entries are per-user overrides, and per-app network and +// sleep inhibitors are readable by every user: root only opens up other users' processes. +inline constexpr const wchar_t *full_access_caption = + L"It lets Processes end and reprioritize other users' processes and read their command lines and disk use, " + L"raise any process's priority, and lets Files & Ports list every process's files and connections. Without " + L"it, those rows show a lock."; inline constexpr const wchar_t *tray_figures = L"The chosen figures show next to the tray icon (in its tooltip where the panel shows no text, as on KDE). " L"Closing the window keeps Procyon there; the icon's menu opens it again."; inline constexpr bool tray_while_open = true; +inline constexpr bool nice_is_exact = true; +inline constexpr const wchar_t *unlisted_process_name(int) { return nullptr; } #endif } // namespace procyon::ui::os diff --git a/apps/ui/src/overlays.cpp b/apps/ui/src/overlays.cpp index 25c2587..6914c31 100644 --- a/apps/ui/src/overlays.cpp +++ b/apps/ui/src/overlays.cpp @@ -4,7 +4,9 @@ #include #include +#include +#include "commands.hpp" #include "widgets.hpp" namespace procyon::ui { @@ -36,7 +38,7 @@ void floating_panel(Renderer &r, const Rect &panel) { class CommandPalette : public Overlay { public: explicit CommandPalette(std::vector items) : items_(std::move(items)) { - field_.placeholder = L"Jump to a screen, run a command, or find an app"; + field_.placeholder = kPlaceholder; field_.keycap = L""; field_.focused = true; filter(); @@ -123,7 +125,18 @@ class CommandPalette : public Overlay { bool key(Host &host, const KeyEvent &e) override { switch (e.key) { - case Key::Escape: close(); return true; + case Key::Escape: + if (!levels_.empty()) + back(); + else + close(); + return true; + case Key::Back: + if (field_.text.empty() && !levels_.empty()) { + back(); + return true; + } + break; case Key::Down: selected_ = std::min(static_cast(std::min(matches_.size(), 9)) - 1, selected_ + 1); return true; @@ -144,15 +157,32 @@ class CommandPalette : public Overlay { return false; } + bool is_palette() const override { return true; } + private: + static constexpr const wchar_t *kPlaceholder = L"Jump to a screen, run a command, or find an app"; + + // Every word of the query appears in the title or subtitle, in any order ("chrome end"). + static bool matches(const PaletteItem &item, const std::vector &words) { + const std::wstring text = lower(item.title) + L" " + lower(item.subtitle); + for (const std::wstring &word : words) + if (text.find(word) == std::wstring::npos) return false; + return true; + } + void filter() { matches_.clear(); const std::wstring needle = lower(field_.text); + std::vector words; + for (size_t start = 0; start < needle.size();) { + const size_t end = std::min(needle.find(L' ', start), needle.size()); + if (end > start) words.push_back(needle.substr(start, end - start)); + start = end + 1; + } for (size_t i = 0; i < items_.size(); ++i) { - if (needle.empty() && items_[i].kind == PaletteItem::Kind::App) continue; // apps only on demand - if (needle.empty() || lower(items_[i].title).find(needle) != std::wstring::npos || - lower(items_[i].subtitle).find(needle) != std::wstring::npos) - matches_.push_back(i); + // At the top level apps appear only on demand. + if (needle.empty() && levels_.empty() && items_[i].kind == PaletteItem::Kind::App) continue; + if (words.empty() || matches(items_[i], words)) matches_.push_back(i); } // Screens, then commands, then apps; apps with more CPU first stay in their given order. std::stable_sort(matches_.begin(), matches_.end(), [&](size_t a, size_t b) { @@ -166,11 +196,32 @@ class CommandPalette : public Overlay { void run(Host &, int index) { if (index < 0 || index >= static_cast(matches_.size())) return; - const PaletteItem item = items_[matches_[static_cast(index)]]; + PaletteItem item = items_[matches_[static_cast(index)]]; + if (!item.children.empty()) { + levels_.push_back({std::move(items_), field_.placeholder}); + items_ = std::move(item.children); + field_.placeholder = item.title; + field_.text.clear(); + filter(); + return; + } close(); if (item.run) item.run(); } + void back() { + items_ = std::move(levels_.back().items); + field_.placeholder = levels_.back().placeholder; + levels_.pop_back(); + field_.text.clear(); + filter(); + } + + struct Level { + std::vector items; + std::wstring placeholder; + }; + std::vector levels_; // the levels above this one std::vector items_; std::vector matches_; TextField field_; @@ -239,7 +290,7 @@ class InfoSheet : public Overlay { r.push_clip(content_); float y = content_.y - scroll_.offset; switch (tab_) { - case 0: y = paint_info(r, content_, y); break; + case 0: y = paint_info(r, content_, y, host.elevated()); break; case 1: y = paint_threads(r, content_, y); break; case 2: y = paint_files(r, content_, y); break; case 3: y = paint_network(r, content_, y); break; @@ -352,7 +403,7 @@ class InfoSheet : public Overlay { return y + height + tokens::space::sm; } - float paint_info(Renderer &r, const Rect &area, float y) { + float paint_info(Renderer &r, const Rect &area, float y, bool elevated) { const Theme &theme = r.theme(); const pc_process &p = process_; y = row(r, area, y, L"Name", name_); @@ -366,12 +417,11 @@ class InfoSheet : public Overlay { : p.state == PC_STATE_ZOMBIE ? L"Exited" : p.state == PC_STATE_SLEEPING ? L"Waiting" : L"Unknown"); + // The Processes menu's steps; a nice value between them is shown as well (Linux). + const PriorityStep &step = priority_step(p.nice); y = row(r, area, y, L"Priority", - p.nice <= -15 ? L"High" - : p.nice < 0 ? L"Above normal" - : p.nice == 0 ? L"Normal" - : p.nice <= 8 ? L"Below normal" - : L"Low"); + std::wstring(step.title) + + (os::nice_is_exact && step.nice != p.nice ? L" (nice " + std::to_wstring(p.nice) + L")" : L"")); y = row(r, area, y, L"CPU", fmt::cpu(p.cpu_percent)); y = row(r, area, y, L"Memory", fmt::bytes(p.memory_bytes)); y = row(r, area, y, L"Disk", @@ -391,7 +441,10 @@ class InfoSheet : public Overlay { y = row(r, area, y, L"Command line", command, true); else y = row(r, area, y, L"Command line", std::wstring(L"Not readable without ") + os::admin + L" rights"); - if (!details_->environment.empty()) { + // Every process has some environment: none read means it is another user's. + if (details_->environment.empty() && !elevated) + y = row(r, area, y, L"Environment", std::wstring(L"Not readable without ") + os::admin + L" rights"); + else if (!details_->environment.empty()) { r.panel_caption(Rect{area.x, y + 4, area.w, 20}, L"Environment"); y += 28; TextStyle mono; @@ -406,10 +459,16 @@ class InfoSheet : public Overlay { return y; } + static std::wstring need_rights() { + std::wstring text = std::wstring(os::admin) + L" rights are needed for this process."; + text[0] = static_cast(towupper(text[0])); + return text; + } + float paint_threads(Renderer &r, const Rect &area, float y) { const Theme &theme = r.theme(); if (!details_ || !details_->info.threads_known) { - empty_state(r, area, L"Threads not readable", L"Administrator rights are needed for this process."); + empty_state(r, area, L"Threads not readable", need_rights()); return y; } Rect head{area.x, y, area.w, 22}; @@ -460,7 +519,7 @@ class InfoSheet : public Overlay { if (!handles_loaded_) return y; if (files_.empty()) { empty_state(r, area, files_complete_ ? L"No files open" : L"Not readable", - files_complete_ ? L"" : L"Administrator rights are needed for this process."); + files_complete_ ? std::wstring() : need_rights()); return y; } if (!files_complete_) { @@ -502,9 +561,9 @@ class InfoSheet : public Overlay { const std::wstring proto = c.protocol == PC_PROTOCOL_TCP ? (c.family == 6 ? L"TCP6" : L"TCP") : (c.family == 6 ? L"UDP6" : L"UDP"); r.text(proto, Rect{area.x, y, 56, 22}, b, theme.text_secondary()); - r.text(fmt::from_utf8(c.local_address) + L":" + std::to_wstring(c.local_port), - Rect{area.x + 56, y, 190, 22}, b, theme.text()); - r.text(c.remote_address[0] ? fmt::from_utf8(c.remote_address) + L":" + std::to_wstring(c.remote_port) + r.text(fmt::endpoint(fmt::from_utf8(c.local_address), c.local_port), Rect{area.x + 56, y, 190, 22}, b, + theme.text()); + r.text(c.remote_address[0] ? fmt::endpoint(fmt::from_utf8(c.remote_address), c.remote_port) : std::wstring(fmt::unavailable), Rect{area.x + 250, y, area.w - 350, 22}, b, c.remote_address[0] ? theme.text() : theme.text_tertiary()); @@ -512,7 +571,7 @@ class InfoSheet : public Overlay { : c.state == PC_TCP_ESTABLISHED ? L"Established" : c.state == PC_TCP_TIME_WAIT ? L"Time wait" : c.state == PC_TCP_CLOSE_WAIT ? L"Close wait" - : c.state == PC_TCP_NONE ? L"" + : c.state == PC_TCP_NONE ? (c.remote_address[0] ? L"" : L"Listening") : L"Closing"; b.halign = HAlign::Right; r.text(state, Rect{area.right() - 100, y, 100, 22}, b, theme.text_secondary()); @@ -553,6 +612,78 @@ std::unique_ptr make_command_palette(std::vector items) { return std::make_unique(std::move(items)); } +std::vector app_palette_actions(Host &host, const Row &row, const pc_process *process, + const std::wstring &name, std::function command) { + using Kind = PaletteItem::Kind; + const int32_t pid = row.is_group() ? row.group_pid : process ? process->pid : 0; + const std::string app_id = row.is_group() ? row.group_id : process ? std::string(process->app_id) : std::string(); + const bool locked = process && (process->flags & PC_PROC_PROTECTED); + const bool system = process && (process->flags & PC_PROC_SYSTEM); + const std::wstring path = process ? fmt::from_utf8(process->path) : std::wstring(); + Store &store = host.store(); + std::vector items; + auto add = [&items](std::wstring title, std::wstring subtitle, std::function run) { + items.push_back({Kind::Command, std::move(title), std::move(subtitle), L"", std::move(run)}); + }; + // Ending goes through the Processes screen with the app selected: the same confirmations and + // the same protection as its End Task button. + if (!locked) { + const std::wstring members = + row.process_count > 1 ? L"End " + std::to_wstring(row.process_count) + L" Processes" : L"End Task"; + add(members, name, [&host, app_id, pid, command] { + host.show_in_processes(app_id, pid); + command(IDM_END_TASK); + }); + add(L"Force Quit", name, [&host, app_id, pid, command] { + host.show_in_processes(app_id, pid); + command(IDM_FORCE_QUIT); + }); + } + if (!locked && store.has(PC_CAP_SUSPEND) && pid > 0) { + if (process && process->state == PC_STATE_STOPPED) + add(L"Resume", name, [&host, pid] { + if (const pc_result result = host.store().resume(pid); result != PC_OK) + host.report(result, L"resume the process"); + host.store().refresh_now(); + }); + else + add(L"Suspend", name, [&host, pid, name] { + if (!host.confirm(L"Suspend " + name + L"?", + L"The process stops running until you resume it. Apps may become unresponsive.", + L"Suspend", false)) + return; + if (const pc_result result = host.store().suspend(pid); result != PC_OK) + host.report(result, L"suspend the process"); + host.store().refresh_now(); + }); + } + if (!locked && store.has(PC_CAP_PRIORITY) && pid > 0) { + PaletteItem priority{Kind::Command, L"Set Priority", name, L"", nullptr}; + for (const PriorityStep &step : priority_steps()) + priority.children.push_back( + {Kind::Command, step.title, L"", L"", [&host, pid, name, system, nice = step.nice, title = step.title] { + if (system && !host.confirm(L"Change the priority of “" + name + L"”?", + std::wstring(L"This is a ") + os::name + + L" system process. Changing its priority can make " + os::name + + L" slower or less responsive.", + std::wstring(L"Set to ") + title, false)) + return; + if (const pc_result result = host.store().set_priority(pid, nice); result != PC_OK) + host.report(result, L"change the priority"); + host.store().refresh_now(); + }}); + items.push_back(std::move(priority)); + } + if (pid > 0) add(L"Get Info", name, [&host, pid] { host.show_info(pid); }); + add(L"Show in Processes", name, [&host, app_id, pid] { host.show_in_processes(app_id, pid); }); + if (!path.empty()) { + add(L"Open File Location", path, [&host, path] { host.open_in_explorer(path); }); + add(L"Copy Path", path, [&host, path] { host.copy_to_clipboard(path); }); + } + if (pid > 0) add(L"Copy PID", std::to_wstring(pid), [&host, pid] { host.copy_to_clipboard(std::to_wstring(pid)); }); + return items; +} + std::unique_ptr make_info_sheet(int32_t pid) { return std::make_unique(pid); } } // namespace procyon::ui diff --git a/apps/ui/src/overlays.hpp b/apps/ui/src/overlays.hpp index e9498be..2366ad4 100644 --- a/apps/ui/src/overlays.hpp +++ b/apps/ui/src/overlays.hpp @@ -20,6 +20,7 @@ class Overlay { virtual bool key(Host &, const KeyEvent &) { return false; } virtual bool character(Host &, wchar_t) { return false; } virtual void tick(Host &) {} + virtual bool is_palette() const { return false; } bool closed() const { return closed_; } void close() { closed_ = true; } @@ -36,9 +37,17 @@ struct PaletteItem { std::function run; std::wstring icon_path; // App rows: the app's icon (see Renderer::app_icon) bool icon_system = false; + // A row with children opens them as the palette's next level (an app's actions, the priority + // steps) instead of running; Escape or Backspace in an empty field goes back. + std::vector children; }; std::unique_ptr make_command_palette(std::vector items); +// The macOS palette's second level for an app: End Task, Force Quit, Suspend/Resume, Priority, Get Info, +// Show in Processes, Open File Location, Copy Path, Copy PID. `command` runs a window command +// (IDM_END_TASK, IDM_FORCE_QUIT) on the Processes screen once the app is selected there. +std::vector app_palette_actions(Host &host, const Row &row, const pc_process *process, + const std::wstring &name, std::function command); std::unique_ptr make_info_sheet(int32_t pid); } // namespace procyon::ui diff --git a/apps/ui/src/page_history.cpp b/apps/ui/src/page_history.cpp index 69755cc..64826d2 100644 --- a/apps/ui/src/page_history.cpp +++ b/apps/ui/src/page_history.cpp @@ -556,7 +556,8 @@ class HistoryPage : public Page { Rect row{inner.x, y, inner.w, kAppRow}; Rect line = row.inset(0, tokens::space::xs); const Rect icon = line.take_left(22 + tokens::space::sm + 2); - r.app_icon(app_icon_path(app.app_id), Rect{icon.x, icon.y + 1, 22, 22}, app.app_id.rfind("exe:", 0) == 0); + r.app_icon(app_icon_path(app.app_id), Rect{icon.x, icon.y + 1, 22, 22}, + app_is_system(host.store().snapshot(), app.app_id, 0)); Rect head = line; head.h = 20; TextStyle headline; diff --git a/apps/ui/src/page_inspect.cpp b/apps/ui/src/page_inspect.cpp index 622e401..82e668c 100644 --- a/apps/ui/src/page_inspect.cpp +++ b/apps/ui/src/page_inspect.cpp @@ -33,6 +33,9 @@ std::wstring lower(std::wstring s) { return s; } +// A path as the file system compares it: folded on Windows, as spelt on Linux. +std::wstring path_key(const std::wstring &path) { return os::paths_ignore_case ? lower(path) : path; } + // Case-insensitive ordering, like _wcsicmp. int wcscasecmp_(const wchar_t *a, const wchar_t *b) { for (;; ++a, ++b) { @@ -116,8 +119,8 @@ class InspectPage : public Page { if (!target_.empty()) { float x = browse_button_.right() + tokens::space::md; std::wstring name = target_; - while (!name.empty() && name.back() == L'\\') name.pop_back(); - if (const size_t slash = name.find_last_of(L'\\'); + while (name.size() > 1 && name.back() == os::path_separator) name.pop_back(); + if (const size_t slash = name.find_last_of(os::path_separator); slash != std::wstring::npos && slash + 1 < name.size()) name = name.substr(slash + 1); x += r.badge(x, toolbar.cy() - 8.5f, name, Renderer::Tone::Accent) + tokens::space::xs; @@ -239,6 +242,7 @@ class InspectPage : public Page { int32_t pid; std::wstring process; std::wstring a, b, c, d; // tab-specific columns + std::wstring copy; // Copy Address on the Ports and Connections tabs int32_t state = 0; int sort_key = 0; bool local_only = false; @@ -279,7 +283,8 @@ class InspectPage : public Page { if (!host_) return L""; const pc_process *p = host_->store().snapshot().find(pid); if (p) return process_display_name(*p); - return pid == 4 ? L"System" : pid == 0 ? L"System Idle Process" : L"PID " + std::to_wstring(pid); + if (const wchar_t *name = os::unlisted_process_name(pid)) return name; + return L"PID " + std::to_wstring(pid); } void reload() { @@ -293,7 +298,9 @@ class InspectPage : public Page { const std::vector connections = host_->store().connections(-1, complete); complete_ = complete; for (const pc_connection &c : connections) { - const bool listen = c.protocol == PC_PROTOCOL_UDP || c.state == PC_TCP_LISTEN; + // As on macOS: TCP listening, or UDP bound without a peer. A connected UDP socket (a QUIC + // or DNS client) is a connection. + const bool listen = c.state == PC_TCP_LISTEN || (c.protocol == PC_PROTOCOL_UDP && !c.remote_address[0]); if (tab_ == TabPorts && !listen) continue; if (tab_ == TabConnections && listen) continue; RowData row; @@ -306,13 +313,16 @@ class InspectPage : public Page { if (tab_ == TabPorts) { row.b = std::to_wstring(c.local_port); row.c = local == L"*" ? L"All addresses" : local; + // What Copy Address gives: an address a program accepts, the wildcard spelt out. + row.copy = fmt::endpoint(local == L"*" ? (c.family == 6 ? L"::" : L"0.0.0.0") : local, c.local_port); row.d = row.local_only ? L"This PC" : L"Network"; row.state = row.local_only ? 0 : 1; row.sort_key = c.local_port; } else { - row.b = local + L":" + std::to_wstring(c.local_port); - row.c = c.remote_address[0] ? fmt::from_utf8(c.remote_address) + L":" + std::to_wstring(c.remote_port) + row.b = fmt::endpoint(local, c.local_port); + row.c = c.remote_address[0] ? fmt::endpoint(fmt::from_utf8(c.remote_address), c.remote_port) : std::wstring(fmt::unavailable); + row.copy = row.c; row.d = state_name(c.state); row.state = c.state; row.sort_key = c.local_port; @@ -346,15 +356,16 @@ class InspectPage : public Page { void sort() { rows_.clear(); const std::wstring needle = lower(search_.text); - std::wstring prefix = lower(target_); - while (!prefix.empty() && prefix.back() == L'\\') prefix.pop_back(); + std::wstring prefix = path_key(target_); + // "C:\" or "/" stand for everything under them: the separator itself ends the prefix. + while (!prefix.empty() && prefix.back() == os::path_separator) prefix.pop_back(); int exposed = 0; for (const RowData &row : all_) { if (tab_ != TabFiles && hide_loopback_ && row.local_only) continue; if (tab_ == TabFiles && !prefix.empty()) { - const std::wstring path = lower(row.b); + const std::wstring path = path_key(row.b); if (path.rfind(prefix, 0) != 0) continue; - if (path.size() > prefix.size() && path[prefix.size()] != L'\\') continue; + if (path.size() > prefix.size() && path[prefix.size()] != os::path_separator) continue; } if (!needle.empty() && lower(row.process).find(needle) == std::wstring::npos && lower(row.b).find(needle) == std::wstring::npos && lower(row.c).find(needle) == std::wstring::npos && @@ -443,9 +454,7 @@ class InspectPage : public Page { if (tab_ == TabFiles) items.push_back({MenuOpen, std::wstring(L"Show in ") + os::file_manager}); switch (host_->popup_menu(items, x, y)) { case MenuInfo: host_->show_info(d.pid); break; - case MenuCopy: - host_->copy_to_clipboard(tab_ == TabFiles ? d.b : tab_ == TabPorts ? d.c + L":" + d.b : d.c); - break; + case MenuCopy: host_->copy_to_clipboard(tab_ == TabFiles ? d.b : d.copy); break; case MenuOpen: host_->open_in_explorer(d.b); break; default: break; } diff --git a/apps/ui/src/page_overview.cpp b/apps/ui/src/page_overview.cpp index c54f30e..a1cbd01 100644 --- a/apps/ui/src/page_overview.cpp +++ b/apps/ui/src/page_overview.cpp @@ -276,7 +276,7 @@ class OverviewPage : public Page { Renderer::SparklineOptions options; options.end_dot = true; options.halo = true; - r.sparkline(spark.inset(0, 4), spec.series->data(), spec.series->size(), kHistoryWindow, spec.series_max, + r.sparkline(spark.inset(0, 4), spec.series->data(), spec.series->size(), history_window(), spec.series_max, spec.kind, options); } if (spec.secondary && spec.secondary->size() > 1) { @@ -285,7 +285,7 @@ class OverviewPage : public Page { options.halo = false; Color end = rgba(metric_style(spec.kind).end); options.color_override = &end; - r.sparkline(spark.inset(0, 4), spec.secondary->data(), spec.secondary->size(), kHistoryWindow, + r.sparkline(spark.inset(0, 4), spec.secondary->data(), spec.secondary->size(), history_window(), spec.series_max, spec.kind, options); } r.pop_clip(); diff --git a/apps/ui/src/page_performance.cpp b/apps/ui/src/page_performance.cpp index 6d6edf5..ba5e558 100644 --- a/apps/ui/src/page_performance.cpp +++ b/apps/ui/src/page_performance.cpp @@ -73,6 +73,7 @@ class PerformancePage : public Page { void paint(Host &host, const Rect &bounds) override { app_rows_.clear(); + unlock_button_ = {}; switch (id_) { case PageId::Cpu: paint_cpu(host, bounds); break; case PageId::Memory: paint_memory(host, bounds); break; @@ -87,6 +88,10 @@ class PerformancePage : public Page { void wheel(Host &, const MouseEvent &e) override { scroll_.wheel(e.wheel); } void mouse_down(Host &host, const MouseEvent &e, bool right) override { if (right) return; + if (!unlock_button_.empty() && unlock_button_.contains(e.x, e.y)) { + host.relaunch_elevated(); + return; + } for (const TopAppRow &row : app_rows_) if (row.rect.contains(e.x, e.y)) host.show_in_processes(row.app_id, row.pid); } @@ -97,7 +102,7 @@ class PerformancePage : public Page { static bool fixed_temperature(const Series &series) { if (series.size() < 20) return false; const float *values = series.data(); - const size_t start = series.size() > kHistoryWindow ? series.size() - kHistoryWindow : 0; + const size_t start = series.size() > history_window() ? series.size() - history_window() : 0; for (size_t i = start + 1; i < series.size(); ++i) if (values[i] != values[start]) return false; return true; @@ -112,9 +117,12 @@ class PerformancePage : public Page { void top_apps(Host &host, Stack &stack, const wchar_t *title, Renderer::Symbol symbol, MetricKind kind, int32_t column, const std::function &value, - const std::function &fraction) { + const std::function &fraction, + const std::function &rank = {}, + std::wstring_view empty = L"No app is busy right now.") { const Rect card = stack.next(top_apps_height(8)); - for (const TopAppRow &row : top_apps_panel(host, card, title, symbol, kind, column, true, 8, value, fraction)) + for (const TopAppRow &row : + top_apps_panel(host, card, title, symbol, kind, column, true, 8, value, fraction, rank, empty)) app_rows_.push_back(row); } @@ -155,10 +163,11 @@ class PerformancePage : public Page { {&h.cpu_system, L"System", fmt::percent(s.cpu_system), true}}, 1, MetricKind::Cpu, percent_axis); - // Windows has no user-mode way to the die sensor: the hottest ACPI zone stands in. A zone that - // has never moved over the last minute is the board's fixed reading, and says so. - const bool fixed_zone = fixed_temperature(h.cpu_temperature); - const wchar_t *zone_label = fixed_zone ? L"Board zone (fixed reading)" : L"Hottest ACPI zone"; + // Where only a firmware zone stands in for the die sensor (Windows), a zone that has never moved + // over the last minute is the board's fixed reading, and says so. A die sensor of an idle machine + // may sit still too: it is never called fixed. + const bool fixed_zone = os::cpu_sensor_is_firmware_zone && fixed_temperature(h.cpu_temperature); + const wchar_t *zone_label = fixed_zone ? L"Board zone (fixed reading)" : os::cpu_sensor_label; if (store.has(PC_CAP_TEMPERATURE) && s.cpu_temperature >= 0) { inner = panel(r, stack.next(kPanelChrome + 160), L"Temperature", Renderer::Symbol::Thermo); Color warning = theme.warning(); @@ -184,9 +193,15 @@ class PerformancePage : public Page { }; if (info.cpu_frequency_hz) stats.push_back({L"Base speed", fmt::number(info.cpu_frequency_hz / 1e9, 2) + L" GHz", L""}); + // Where the OS keeps one (Linux; not Windows, whose figures stay 0), as the macOS CPU screen shows. + if (s.load_average[0] > 0 || s.load_average[1] > 0 || s.load_average[2] > 0) + stats.push_back({L"Load average", + fmt::number(s.load_average[0], 2) + L" " + fmt::number(s.load_average[1], 2) + L" " + + fmt::number(s.load_average[2], 2), + L"1, 5 and 15 minutes"}); if (store.has(PC_CAP_TEMPERATURE) && s.cpu_temperature >= 0) stats.push_back({L"Temperature", fmt::temperature(s.cpu_temperature, host.settings().fahrenheit), - fixed_zone ? L"Board's ACPI zone, not the CPU die" : L"Hottest ACPI zone"}); + fixed_zone ? L"Board's ACPI zone, not the CPU die" : os::cpu_sensor_detail}); const float content_w = stack.area.w - tokens::space::lg * 2; inner = panel(r, stack.next(kPanelChrome + stat_grid_height(content_w, stats.size())), L"Details", Renderer::Symbol::Bullets); @@ -266,7 +281,7 @@ class PerformancePage : public Page { Color color = rgba(s.core_usage[static_cast(i)] > 0.85 ? style.end : style.start); options.color_override = &color; r.sparkline(spark, h.cores[static_cast(i)].data(), h.cores[static_cast(i)].size(), - kHistoryWindow, 1, MetricKind::Cpu, options); + history_window(), 1, MetricKind::Cpu, options); } r.usage_bar(Rect{tile.x + tokens::space::sm, tile.bottom() - 2, tile.w - tokens::space::sm * 2, 2}, static_cast(s.core_usage[static_cast(i)]), MetricKind::Cpu); @@ -325,9 +340,9 @@ class PerformancePage : public Page { }; const std::vector parts = { {L"App", s.memory_app, rgba(style.start)}, - {L"Kernel", s.memory_wired, rgba(style.end)}, + {os::memory_wired, s.memory_wired, rgba(style.end)}, {L"Compressed", s.memory_compressed, rgba(tokens::metric::cpu.start)}, - {L"Standby", s.memory_cached, with_alpha(theme.text_tertiary(), 0.6f)}, + {os::memory_cached, s.memory_cached, with_alpha(theme.text_tertiary(), 0.6f)}, {L"Free", s.memory_free, theme.track()}, }; const float content_w = stack.area.w - tokens::space::lg * 2; @@ -358,7 +373,7 @@ class PerformancePage : public Page { value, theme.text()); } - // Details and the page file, side by side. + // Details and the page file (swap), side by side. std::vector stats = { {L"Pressure", pressure, L"", s.memory_pressure == PC_PRESSURE_CRITICAL ? theme.danger() @@ -367,9 +382,9 @@ class PerformancePage : public Page { {L"Used", fmt::bytes(static_cast(s.memory_used)), fmt::percent(s.memory_total ? static_cast(s.memory_used) / s.memory_total : 0)}, {L"App memory", fmt::bytes(static_cast(s.memory_app)), L""}, - {L"Kernel (non-paged)", fmt::bytes(static_cast(s.memory_wired)), L""}, + {os::memory_wired_detail, fmt::bytes(static_cast(s.memory_wired)), L""}, {L"Compressed", fmt::bytes(static_cast(s.memory_compressed)), L""}, - {L"Standby (cached)", fmt::bytes(static_cast(s.memory_cached)), L""}, + {os::memory_cached_detail, fmt::bytes(static_cast(s.memory_cached)), L""}, }; const bool wide = stack.area.w >= 720; const float swap_w = wide ? std::min(360.0f, stack.area.w * 0.35f) : stack.area.w; @@ -381,7 +396,7 @@ class PerformancePage : public Page { inner = panel(r, Rect{row.x, row.y, details_w, row_h}, L"Details", Renderer::Symbol::Bullets); stat_grid(r, inner, stats, 140, 3); const Rect swap_card = wide ? Rect{row.right() - swap_w, row.y, swap_w, row_h} : stack.next(kPanelChrome + 120); - inner = panel(r, swap_card, L"Page file", Renderer::Symbol::Drive); + inner = panel(r, swap_card, os::swap_name, Renderer::Symbol::Drive); const auto swap = fmt::split_unit(fmt::bytes(static_cast(s.swap_used))); const float vw = value_text(r, inner.take_top(32), swap.first, swap.second, Font::Metric, theme.text()); TextStyle of_label; @@ -398,7 +413,7 @@ class PerformancePage : public Page { options.halo = false; Color end = rgba(style.end); options.color_override = &end; - r.sparkline(inner, h.swap_used.data(), h.swap_used.size(), kHistoryWindow, + r.sparkline(inner, h.swap_used.data(), h.swap_used.size(), history_window(), nice_max(std::max(1.0f, h.swap_used.max_recent())), MetricKind::Memory, options); } @@ -507,7 +522,9 @@ class PerformancePage : public Page { return row.disk_read_bps < 0 ? 0.0f : static_cast((row.disk_read_bps + std::max(0.0, row.disk_write_bps)) / peak); - }); + }, + [](const Row &row) { return std::max(0.0, row.disk_read_bps) + std::max(0.0, row.disk_write_bps); }, + L"No app is reading or writing right now."); finish(r, bounds, stack.y); } @@ -557,14 +574,21 @@ class PerformancePage : public Page { return row.net_rx_bps < 0 ? 0.0f : static_cast((row.net_rx_bps + std::max(0.0, row.net_tx_bps)) / peak); - }); + }, + [](const Row &row) { return std::max(0.0, row.net_rx_bps) + std::max(0.0, row.net_tx_bps); }, + L"No app is using the network right now."); if (os::process_network_note) info_banner(r, stack.next(44), os::process_network_note, L"", Renderer::Tone::Neutral); + } else if (os::process_network_needs_elevation && !host.elevated()) { + const Banner b = action_banner( + r, stack.next(kActionBannerHeight), L"Per-app network needs full access", + std::wstring(L"Counting each app's traffic needs ") + os::admin + L" access. " + os::elevation, + L"Unlock Full Access", Renderer::Tone::Accent, unlock_button_.contains(host.mouse_x(), host.mouse_y())); + unlock_button_ = b.button; } else { info_banner(r, stack.next(44), - std::wstring(L"Procyon can't read per-app network usage on ") + os::name + - L" yet, so it hides it instead of showing " - L"estimates.", + std::wstring(L"Procyon can't read per-app network usage on this machine, so it hides it " + L"instead of showing estimates."), L"", Renderer::Tone::Neutral); } finish(r, bounds, stack.y); @@ -658,6 +682,8 @@ class PerformancePage : public Page { finish(r, bounds, stack.y); } + // Laid out like the macOS BatteryView: Charge and Health side by side, then the apps keeping the + // machine awake, always shown. void paint_battery(Host &host, const Rect &bounds) { Renderer &r = host.renderer(); const Theme &theme = r.theme(); @@ -666,79 +692,166 @@ class PerformancePage : public Page { Rect area; Stack stack = begin(r, bounds, area); Rect trailing; - stack.area = page_header(r, area, L"Battery", - b ? (b->charging ? L"Charging" - : b->on_ac_power ? L"On AC power" - : L"On battery") - : L"No battery", - MetricKind::Battery, &trailing); + stack.area = + page_header(r, area, L"Battery", b ? battery_state(*b) : L"No battery", MetricKind::Battery, &trailing); stack.y = stack.area.y; if (!b) { - empty_state(r, stack.next(200), L"No battery", L"This PC runs on mains power."); + empty_state(r, stack.next(200), L"No battery", L"This PC runs on external power."); finish(r, bounds, stack.y); return; } value_text(r, Rect{trailing.x, trailing.y + 6, trailing.w, 40}, fmt::number(b->level * 100, 0), L"%", Font::Display, theme.text(), HAlign::Right); - std::vector stats = { - {L"Charge", fmt::percent(b->level), - b->charging ? L"Charging" - : b->on_ac_power ? L"On AC power" - : L"On battery", - rgba(tokens::metric::battery.start)}, - {L"Time remaining", - b->on_ac_power ? (b->minutes_to_full > 0 ? fmt::duration(b->minutes_to_full * 60.0) + L" to full" - : b->fully_charged ? L"Fully charged" - : std::wstring(fmt::unavailable)) - : b->minutes_to_empty > 0 ? fmt::duration(b->minutes_to_empty * 60.0) - : std::wstring(fmt::unavailable), - L""}, - {L"Power", b->power_watts != 0 ? fmt::watts(std::fabs(b->power_watts)) : std::wstring(fmt::unavailable), - b->power_watts < 0 ? L"discharging" - : b->power_watts > 0 ? L"charging" - : L""}, - {L"Health", b->health >= 0 ? fmt::percent(b->health) : std::wstring(fmt::unavailable), - fmt::from_utf8(b->condition)}, - {L"Cycles", b->cycle_count >= 0 ? fmt::count(b->cycle_count) : std::wstring(fmt::unavailable), L""}, - {L"Capacity", - b->max_capacity_mah > 0 ? fmt::count(b->max_capacity_mah) + L" mAh" : std::wstring(fmt::unavailable), - b->design_capacity_mah > 0 ? L"design " + fmt::count(b->design_capacity_mah) + L" mAh" : L""}, - {L"Temperature", fmt::temperature(b->temperature, host.settings().fahrenheit), L""}, - }; - const float content_w = stack.area.w - tokens::space::lg * 2 - 110; - Rect inner = panel(r, stack.next(kPanelChrome + std::max(110.0f, stat_grid_height(content_w, stats.size()))), - L"Details", Renderer::Symbol::Bullets, MetricKind::Battery); - const Rect gauge = inner.take_left(110); - r.ring_gauge(gauge.x + 43, gauge.y + 43, 38, static_cast(b->level), MetricKind::Battery, 9); + + // Charge: the state (with the adapter under it), the time left, the power drawn or charged at. + std::vector charge = {{L"State", battery_state(*b), fmt::from_utf8(b->adapter), std::nullopt}}; + if (b->charging) + charge.push_back({L"Until full", + b->minutes_to_full > 0 ? fmt::duration(b->minutes_to_full * 60.0) : L"Calculating…", L"", + std::nullopt}); + else if (!b->on_ac_power) + charge.push_back({L"Remaining", + b->minutes_to_empty > 0 ? fmt::duration(b->minutes_to_empty * 60.0) : L"Calculating…", + L"", std::nullopt}); + if (b->power_watts != 0) + charge.push_back({b->power_watts < 0 ? L"Drawing" : L"Charging at", fmt::watts(std::fabs(b->power_watts)), + L"", std::nullopt}); + // Health: maximum capacity (amber below 80%), condition, cycles, full charge, temperature. + std::vector health; + if (b->health >= 0) + health.push_back({L"Maximum capacity", fmt::percent(b->health), L"", + b->health >= 0.8 ? theme.success() : theme.warning()}); + if (b->condition[0]) health.push_back({L"Condition", fmt::from_utf8(b->condition), L"", std::nullopt}); + if (b->cycle_count > 0) health.push_back({L"Cycle count", fmt::count(b->cycle_count), L"", std::nullopt}); + if (b->max_capacity_mah > 0) + health.push_back( + {L"Full charge", fmt::count(b->max_capacity_mah) + L" mAh", + b->design_capacity_mah > 0 ? L"Design " + fmt::count(b->design_capacity_mah) + L" mAh" : L"", + std::nullopt}); + if (b->temperature >= 0) + health.push_back( + {L"Temperature", fmt::temperature(b->temperature, host.settings().fahrenheit), L"", std::nullopt}); + + const bool wide = stack.area.w >= 760; + const float gap = tokens::space::lg; + const float charge_w = wide ? (stack.area.w - gap) * 0.55f : stack.area.w; + const float health_w = wide ? stack.area.w - gap - charge_w : stack.area.w; + const float charge_h = kPanelChrome + std::max(110.0f, stat_grid_height(charge_w - tokens::space::lg * 2 - 120, + charge.size(), 140, 2)); + const float health_h = kPanelChrome + stat_grid_height(health_w - tokens::space::lg * 2, health.size(), 140, 2); + Rect charge_card, health_card; + if (wide) { + const Rect row = stack.next(std::max(charge_h, health_h)); + charge_card = Rect{row.x, row.y, charge_w, row.h}; + health_card = Rect{row.x + charge_w + gap, row.y, health_w, row.h}; + } else { + charge_card = stack.next(charge_h); + health_card = stack.next(health_h); + } + Rect inner = panel(r, charge_card, L"Charge", Renderer::Symbol::Gauge, MetricKind::Battery); + const Rect gauge = inner.take_left(120); + r.ring_gauge(gauge.x + 48, gauge.y + 48, 42, static_cast(b->level), MetricKind::Battery, 10); TextStyle v; v.font = Font::Stat; v.halign = HAlign::Center; - r.text(fmt::percent(b->level), Rect{gauge.x, gauge.y + 31, 86, 24}, v, theme.text()); - stat_grid(r, inner, stats); - if (!assertions_.empty()) { - inner = panel(r, stack.next(kPanelChrome + assertions_.size() * 24), L"Preventing sleep", - Renderer::Symbol::Clock); - for (const pc_power_assertion &pa : assertions_) { - Rect row = inner.take_top(24); - TextStyle name; - name.font = Font::Body; - // A driver holds no process: its device description stands in for the name. - const std::wstring who = pa.process_name[0] ? fmt::from_utf8(pa.process_name) - : pa.pid > 0 ? L"PID " + std::to_wstring(pa.pid) - : L"Driver"; - const float nw = r.text(who, row, name, theme.text()); - TextStyle kind; - kind.font = Font::Caption; - r.text((pa.kind & PC_ASSERT_DISPLAY_SLEEP) ? L"display" : L"sleep", - Rect{row.x + nw + tokens::space::sm, row.y, 60, row.h}, kind, theme.text_tertiary()); - TextStyle reason; - reason.font = Font::Caption; - reason.halign = HAlign::Right; - r.text(fmt::from_utf8(pa.reason), Rect{row.x + nw + 70, row.y, row.w - nw - 70, row.h}, reason, - theme.text_secondary()); + r.text(fmt::percent(b->level), Rect{gauge.x, gauge.y + 36, 96, 24}, v, theme.text()); + stat_grid(r, inner, charge, 140, 2); + inner = panel(r, health_card, L"Health", Renderer::Symbol::Bullets); + if (health.empty()) + empty_state(r, inner, L"", L"This battery reports nothing about its health."); + else + stat_grid(r, inner, health, 140, 2); + + paint_sleep(host, stack); + finish(r, bounds, stack.y); + } + + // One row per app: what a daemon holds for an app (audio for a player) counts as the app's. + void paint_sleep(Host &host, Stack &stack) { + Renderer &r = host.renderer(); + const Theme &theme = r.theme(); + const Snapshot &s = host.store().snapshot(); + struct Group { + int32_t pid; + std::vector items; + }; + std::vector groups; + for (const pc_power_assertion &pa : assertions_) { + const int32_t pid = pa.on_behalf_of > 0 ? pa.on_behalf_of : pa.pid; + auto it = std::find_if(groups.begin(), groups.end(), [pid](const Group &g) { return g.pid == pid; }); + if (it == groups.end()) it = groups.insert(groups.end(), Group{pid, {}}); + it->items.push_back(&pa); + } + auto name_of = [&s](const Group &g) { + if (const pc_process *p = g.pid > 0 ? s.find(g.pid) : nullptr) return process_display_name(*p); + for (const pc_power_assertion *pa : g.items) + if (pa->pid == g.pid && pa->process_name[0]) return fmt::from_utf8(pa->process_name); + // A driver holds no process: its device description stands in for the name. + if (g.pid <= 0 && g.items.front()->process_name[0]) return fmt::from_utf8(g.items.front()->process_name); + return g.pid > 0 ? L"PID " + std::to_wstring(g.pid) : std::wstring(L"Driver"); + }; + std::sort(groups.begin(), groups.end(), + [&](const Group &a, const Group &b) { return name_of(a) < name_of(b); }); + + constexpr float kRow = 48; + Rect inner = panel(r, stack.next(kPanelChrome + std::max(60, groups.size() * kRow)), + L"Apps Preventing Sleep", Renderer::Symbol::Clock); + if (groups.empty()) { + TextStyle t; + t.font = Font::Body; + t.halign = HAlign::Center; + r.text(L"Nothing is keeping this PC awake.", inner, t, theme.text_tertiary()); + return; + } + for (const Group &g : groups) { + Rect row = inner.take_top(kRow).inset(0, tokens::space::xs); + const pc_process *p = g.pid > 0 ? s.find(g.pid) : nullptr; + const Rect icon = row.take_left(22 + tokens::space::sm + 2); + r.app_icon(p ? app_icon_path(p->app_id) : std::wstring(), Rect{icon.x, icon.y + 1, 22, 22}, + !p || (p->flags & PC_PROC_SYSTEM) != 0); + bool display = false; + std::vector via, reasons; + for (const pc_power_assertion *pa : g.items) { + display |= (pa->kind & PC_ASSERT_DISPLAY_SLEEP) != 0; + if (pa->on_behalf_of > 0 && pa->process_name[0]) { + const std::wstring holder = fmt::from_utf8(pa->process_name); + if (std::find(via.begin(), via.end(), holder) == via.end()) via.push_back(holder); + } + const std::wstring reason = fmt::from_utf8(pa->reason); + if (!reason.empty() && std::find(reasons.begin(), reasons.end(), reason) == reasons.end() && + reasons.size() < 3) + reasons.push_back(reason); + } + TextStyle pid_style; + pid_style.font = Font::Caption; + pid_style.tabular = true; + pid_style.halign = HAlign::Right; + pid_style.valign = VAlign::Top; + if (g.pid > 0) + r.text(L"PID " + std::to_wstring(g.pid), row.take_right(80), pid_style, theme.text_tertiary()); + TextStyle head; + head.font = Font::Headline; + head.valign = VAlign::Top; + float x = row.x + r.text(name_of(g), Rect{row.x, row.y, row.w * 0.5f, 18}, head, theme.text()) + + tokens::space::sm; + x += r.badge(x, row.y, display ? L"Keeps display on" : L"Prevents sleep", + display ? Renderer::Tone::Warning : Renderer::Tone::Accent) + + tokens::space::sm; + if (!via.empty()) { + std::wstring text = L"via "; + for (size_t i = 0; i < via.size(); ++i) text += (i ? L", " : L"") + via[i]; + TextStyle c; + c.font = Font::Caption; + c.valign = VAlign::Top; + r.text(text, Rect{x, row.y + 1, row.right() - x, 16}, c, theme.text_tertiary()); } + std::wstring why; + for (size_t i = 0; i < reasons.size(); ++i) why += (i ? L" · " : L"") + reasons[i]; + TextStyle label; + label.font = Font::Label; + label.valign = VAlign::Top; + r.text(why, Rect{row.x, row.y + 21, row.w, 16}, label, theme.text_secondary()); } - finish(r, bounds, stack.y); } PageId id_; @@ -746,6 +859,7 @@ class PerformancePage : public Page { std::vector volumes_; std::vector assertions_; std::vector app_rows_; + Rect unlock_button_; }; } // namespace diff --git a/apps/ui/src/page_processes.cpp b/apps/ui/src/page_processes.cpp index f3eed6a..ec0ab68 100644 --- a/apps/ui/src/page_processes.cpp +++ b/apps/ui/src/page_processes.cpp @@ -23,16 +23,10 @@ enum MenuIds { MenuCopyPath, MenuCopyPid, MenuPin, - MenuPriorityBase = 100, // + index into kPriorities + MenuPriorityBase = 100, // + index into priority_steps() + MenuSignalBase = 200, // + index into signal_choices() }; -struct Priority { - const wchar_t *label; - int32_t nice; -}; -const Priority kPriorities[] = { - {L"High", -15}, {L"Above normal", -8}, {L"Normal", 0}, {L"Below normal", 8}, {L"Low", 15}}; - // Column ids are pc_column values; the name column is PC_COLUMN_NAME. class ProcessesPage : public Page { public: @@ -145,7 +139,7 @@ class ProcessesPage : public Page { area.take_top(tokens::space::lg); banner_button_ = {}; - if (!host.elevated()) { + if (!host.elevated() && locked_processes(host.store().snapshot()) > 0) { const Banner b = action_banner(r, area.take_top(kActionBannerHeight), L"Processes of other users are locked", std::wstring(L"Their command lines, open files and End Task need ") + os::admin + @@ -464,7 +458,8 @@ class ProcessesPage : public Page { } c.icon = true; c.icon_path = app_icon_path(r, p, s); - c.icon_system = p ? (p->flags & PC_PROC_SYSTEM) != 0 : r.is_group() && r.group_id.rfind("exe:", 0) == 0; + c.icon_system = p ? (p->flags & PC_PROC_SYSTEM) != 0 + : app_is_system(host_->store().snapshot(), r.group_id, r.group_pid); c.pinned = pinned(r); break; case PC_COLUMN_PID: @@ -593,27 +588,64 @@ class ProcessesPage : public Page { store.refresh_now(); } + // Processes this Procyon can't fully read: restricted ones (macOS without the helper), and, where + // every process is listed, those whose user (Windows) or disk use (Linux) is hidden from it. The + // banner shows only when there are some, as macOS shows it only while restrictedCount > 0. + static int locked_processes(const Snapshot &s) { + if (s.restricted_count > 0) return s.restricted_count; + int locked = 0; + for (const pc_process &p : s.processes) + if ((p.flags & PC_PROC_RESTRICTED) || !p.user[0] || p.disk_read_bps < 0) ++locked; + return locked; + } + void context(int visible_index, float x, float y) { if (!host_) return; const Row r = row(visible_index); const pc_process *p = process_of(r); const bool prot = is_protected(r); std::vector items; - items.push_back({MenuEnd, L"End Task", !prot, false, false, true}); + // An app's End Task names how many processes it ends, as on macOS. + items.push_back({MenuEnd, + r.is_group() && r.process_count > 1 + ? L"End " + std::to_wstring(r.process_count) + L" Processes" + : std::wstring(L"End Task"), + !prot, false, false, true}); items.push_back({MenuForce, L"Force Quit", !prot, false, false, true}); - items.push_back({MenuTree, L"End Process Tree", !prot && !r.is_group(), false, false, true}); + // An app's End Process Tree ends each member's tree, as on macOS. + items.push_back({MenuTree, L"End Process Tree", !prot, false, false, true}); items.push_back({0, L"", true, false, true}); if (host_->store().has(PC_CAP_SUSPEND) && !r.is_group()) { const bool suspended = p && p->state == PC_STATE_STOPPED; items.push_back({suspended ? MenuResume : MenuSuspend, suspended ? L"Resume" : L"Suspend", !prot}); } if (host_->store().has(PC_CAP_PRIORITY) && !r.is_group()) { + // As on macOS: the step the process is at is checked; a nice value between steps is listed + // as it is. Windows' classes always sit on a step. Raising priority needs full access. MenuItem priority{0, L"Priority", !prot}; - for (size_t i = 0; i < std::size(kPriorities); ++i) - priority.children.push_back({static_cast(MenuPriorityBase + i), kPriorities[i].label, true, - p && p->nice == kPriorities[i].nice}); + const auto &steps = priority_steps(); + const PriorityStep *current = p ? &priority_step(p->nice) : nullptr; + const bool between = p && os::nice_is_exact && current->nice != p->nice; + for (size_t i = 0; i < steps.size(); ++i) { + std::wstring title = steps[i].title; + if (steps[i].nice < 0 && !host_->elevated()) title += L" (needs full access)"; + priority.children.push_back( + {static_cast(MenuPriorityBase + i), title, true, !between && current == &steps[i]}); + } + if (between) { + priority.children.push_back({0, L"", true, false, true}); + priority.children.push_back({0, L"Current: nice " + std::to_wstring(p->nice), false}); + } items.push_back(priority); } + if (host_->store().has(PC_CAP_SIGNALS) && !r.is_group() && !signal_choices().empty()) { + MenuItem signal{0, L"Send Signal", !prot}; + const auto &signals = signal_choices(); + for (size_t i = 0; i < signals.size(); ++i) + signal.children.push_back({static_cast(MenuSignalBase + i), + std::wstring(signals[i].name) + L" — " + signals[i].meaning}); + items.push_back(signal); + } items.push_back({0, L"", true, false, true}); items.push_back({MenuPin, app_of(r) == pinned_app_ ? L"Unpin" : L"Pin to Top", !app_of(r).empty()}); items.push_back({MenuInfo, L"Get Info"}); @@ -654,15 +686,39 @@ class ProcessesPage : public Page { if (p) host_->copy_to_clipboard(fmt::from_utf8(p->path)); break; case MenuCopyPid: host_->copy_to_clipboard(std::to_wstring(pid)); break; - default: - if (chosen >= MenuPriorityBase && - chosen < MenuPriorityBase + static_cast(std::size(kPriorities))) { - const pc_result result = - host_->store().set_priority(pid, kPriorities[chosen - MenuPriorityBase].nice); + default: { + const std::wstring name = p ? process_display_name(*p) : L"PID " + std::to_wstring(pid); + const bool system = p && (p->flags & PC_PROC_SYSTEM) != 0; + const auto &steps = priority_steps(); + if (chosen >= MenuPriorityBase && chosen < MenuPriorityBase + static_cast(steps.size())) { + const PriorityStep &step = steps[static_cast(chosen - MenuPriorityBase)]; + // A system process's priority is the OS's business: confirmed first, as on macOS. + if (system && !host_->confirm(L"Change the priority of “" + name + L"”?", + std::wstring(L"This is a ") + os::name + + L" system process. Changing its priority can make " + os::name + + L" slower or less responsive.", + std::wstring(L"Set to ") + step.title, false)) + break; + const pc_result result = host_->store().set_priority(pid, step.nice); if (result != PC_OK) host_->report(result, L"change the priority"); host_->store().refresh_now(); } + const auto &signals = signal_choices(); + if (chosen >= MenuSignalBase && chosen < MenuSignalBase + static_cast(signals.size())) { + const SignalChoice &signal = signals[static_cast(chosen - MenuSignalBase)]; + if ((signal.disruptive || system) && + !host_->confirm( + std::wstring(L"Send ") + signal.name + L" to “" + name + L"”?", + std::wstring(signal.meaning) + L"." + + (system ? std::wstring(L" This is a ") + os::name + L" system process." : L""), + std::wstring(L"Send ") + signal.name, signal.disruptive)) + break; + const pc_result result = host_->store().send_signal(pid, signal.number); + if (result != PC_OK) host_->report(result, L"send the signal"); + host_->store().refresh_now(); + } break; + } } } diff --git a/apps/ui/src/page_services.cpp b/apps/ui/src/page_services.cpp index 6cf0bcb..e69121a 100644 --- a/apps/ui/src/page_services.cpp +++ b/apps/ui/src/page_services.cpp @@ -1,5 +1,6 @@ -// Startup (Run keys and Startup folders) and Services (Service Control Manager), laid out like -// the macOS StartupView and ServicesView: header with controls, notice, table card, footnote. +// Startup (Run keys, Startup folders and logon tasks on Windows; XDG autostart on Linux) and Services +// (Service Control Manager; systemd units), laid out like the macOS StartupView and ServicesView: header with controls, +// notice, table card, footnote. #include #ifndef _WIN32 #include @@ -242,8 +243,7 @@ class StartupPage : public Page { } case ColEnabled: c.toggle = i.enabled; - c.toggle_enabled = - !i.managed_by_os && (host_ && (host_->elevated() || i.scope == PC_STARTUP_USER_AGENT)); + c.toggle_enabled = can_switch(i); break; default: break; } @@ -275,6 +275,14 @@ class StartupPage : public Page { table_.select(std::min(table_.selected, static_cast(filtered_.size()) - 1)); } + // Whether this Procyon can switch the item: the OS's own items never, machine-wide ones only + // where that needs no elevation (a per-user override on Linux) or Procyon is elevated. + bool can_switch(const pc_startup_item &i) const { + if (i.managed_by_os) return false; + if (i.scope == PC_STARTUP_USER_AGENT || !os::machine_startup_needs_elevation) return true; + return host_ && host_->elevated(); + } + void toggle(int row) { if (!host_ || row < 0 || row >= static_cast(filtered_.size())) return; const pc_startup_item i = item(row); @@ -296,7 +304,7 @@ class StartupPage : public Page { if (!host_) return; const pc_startup_item i = item(row); std::vector items; - items.push_back({i.enabled ? MenuDisable : MenuEnable, i.enabled ? L"Disable" : L"Enable", !i.managed_by_os}); + items.push_back({i.enabled ? MenuDisable : MenuEnable, i.enabled ? L"Disable" : L"Enable", can_switch(i)}); items.push_back({0, L"", true, false, true}); items.push_back( {MenuOpenLocation, std::wstring(L"Show in ") + os::file_manager, i.app_path[0] != 0 || i.program[0] != 0}); diff --git a/apps/ui/src/page_system.cpp b/apps/ui/src/page_system.cpp index ad176fc..03b5d49 100644 --- a/apps/ui/src/page_system.cpp +++ b/apps/ui/src/page_system.cpp @@ -254,12 +254,7 @@ class SettingsPage : public Page { r.badge(row.right() - bw, row.cy() - 8.5f, on ? L"On" : L"Off", on ? Renderer::Tone::Success : Renderer::Tone::Neutral); caption(inner, - std::wstring(L"Full access runs Procyon as ") + os::admin + - L". It lets Processes read and manage " - L"system processes, Files & Ports list every process's files and connections, Startup and " - L"Services switch machine-wide entries, and shows which apps keep the PC awake and how " - L"much network each process uses. Without it, those rows show a lock.", - 3); + std::wstring(L"Full access runs Procyon as ") + os::admin + L". " + os::full_access_caption, 3); inner.take_top(tokens::space::sm); row = inner.take_top(kRow); if (on) { diff --git a/apps/ui/src/pages.hpp b/apps/ui/src/pages.hpp index 66b1320..a89ba35 100644 --- a/apps/ui/src/pages.hpp +++ b/apps/ui/src/pages.hpp @@ -28,6 +28,38 @@ enum class PageId { Settings, }; +// Whether this machine has the screen at all (the sidebar lists it, its shortcut and palette entry +// open it), as the macOS app hides a screen whose capability is missing. +bool page_available(const Store &store, PageId id); + +// The battery's state in a few words, as the macOS app says it: Charging, Fully charged, On AC power, +// On battery (Battery screen header, sidebar). +std::wstring battery_state(const pc_battery &battery); + +// Whether an app (or process) gets the system tile (cog) where it has no icon: its main process's +// PC_PROC_SYSTEM flag, as macOS decides it; `pid` first, else any running process of the app. +// One rule for Processes, top apps and History. +bool app_is_system(const Snapshot &snapshot, const std::string &app_id, int32_t pid); + +// Scheduling priority in the steps the menus offer, as a nice value: the macOS app's table (High -10, +// Above normal -5, Normal 0, Below normal 5, Low 10, Lowest 20). Windows maps each to its class. +struct PriorityStep { + const wchar_t *title; + int32_t nice; +}; +const std::vector &priority_steps(); +// The step a nice value falls into (the nearest). +const PriorityStep &priority_step(int32_t nice); + +// POSIX signals offered by Send Signal (PC_CAP_SIGNALS), with this OS's numbers; empty on Windows. +struct SignalChoice { + const wchar_t *name; + const wchar_t *meaning; + int32_t number; + bool disruptive; // ends or freezes the process: confirmed first +}; +const std::vector &signal_choices(); + struct MenuItem { int id = 0; std::wstring label; @@ -213,7 +245,12 @@ struct TopAppRow { std::vector top_apps_panel(Host &host, const Rect &card, std::wstring_view title, Renderer::Symbol symbol, MetricKind kind, int32_t column, bool tint, size_t max_rows, const std::function &value, - const std::function &fraction); + const std::function &fraction, + // With `rank`, apps are ordered by it rather than by `column`, and + // the ones at or below 0 are left out (as the macOS app ranks disk + // and network by read + write and drops idle apps). + const std::function &rank = {}, + std::wstring_view empty = L"No app is busy right now."); constexpr float kTopAppRowHeight = 44; // headline + bar, with the row padding float top_apps_height(size_t rows); diff --git a/apps/ui/src/pages_common.cpp b/apps/ui/src/pages_common.cpp index e545cc2..a42911c 100644 --- a/apps/ui/src/pages_common.cpp +++ b/apps/ui/src/pages_common.cpp @@ -1,6 +1,8 @@ // Screen patterns shared by every page: header, panels, live chart, stat grids, banners, buttons. #include #include +#include +#include #include "pages.hpp" @@ -110,7 +112,7 @@ void live_chart(Renderer &r, const Rect &bounds, const std::vector Renderer::SparklineOptions grid_only; grid_only.grid = true; grid_only.line_width = lw; - r.sparkline(chart, nullptr, 0, kHistoryWindow, max, kind, grid_only); + r.sparkline(chart, nullptr, 0, history_window(), max, kind, grid_only); for (size_t i = 0; i < series.size(); ++i) { const ChartSeries &s = series[i]; if (!s.series) continue; // legend-only entry (a peak) @@ -121,7 +123,7 @@ void live_chart(Renderer &r, const Rect &bounds, const std::vector options.line_width = lw; Color color = s.color ? *s.color : rgba(s.secondary ? style.end : style.start); options.color_override = &color; - r.sparkline(chart, s.series->data(), s.series->size(), kHistoryWindow, max, kind, options); + r.sparkline(chart, s.series->data(), s.series->size(), history_window(), max, kind, options); } TextStyle foot; foot.font = Font::Caption; @@ -342,7 +344,8 @@ float top_apps_height(size_t rows) { return kPanelChrome + std::max(rows std::vector top_apps_panel(Host &host, const Rect &card, std::wstring_view title, Renderer::Symbol symbol, MetricKind kind, int32_t column, bool tint, size_t max_rows, const std::function &value, - const std::function &fraction) { + const std::function &fraction, + const std::function &rank, std::wstring_view empty) { Renderer &r = host.renderer(); const Theme &theme = r.theme(); std::vector hits; @@ -351,8 +354,13 @@ std::vector top_apps_panel(Host &host, const Rect &card, std::wstring query.mode = PC_VIEW_GROUPED; query.sort_column = column; query.descending = true; - query.limit = static_cast(max_rows); - const std::vector rows = host.store().build_view(query); + query.limit = rank ? 0 : static_cast(max_rows); + std::vector rows = host.store().build_view(query); + if (rank) { + std::erase_if(rows, [&rank](const Row &row) { return row.depth > 0 || !(rank(row) > 0); }); + std::stable_sort(rows.begin(), rows.end(), [&rank](const Row &a, const Row &b) { return rank(a) > rank(b); }); + if (rows.size() > max_rows) rows.resize(max_rows); + } const Snapshot &s = host.store().snapshot(); const float mx = host.mouse_x(), my = host.mouse_y(); float y = inner.y; @@ -372,7 +380,7 @@ std::vector top_apps_panel(Host &host, const Rect &card, std::wstring Rect line = rr.inset(tokens::space::sm, tokens::space::xs + 1); // App icon (ProcessIcon at 22). const Rect icon = line.take_left(22 + tokens::space::sm + 2); - r.app_icon(app_icon_path(row, p, s), Rect{icon.x, icon.y + 1, 22, 22}, p && (p->flags & PC_PROC_SYSTEM) != 0); + r.app_icon(app_icon_path(row, p, s), Rect{icon.x, icon.y + 1, 22, 22}, app_is_system(s, app_id, pid)); Rect top = line; top.h = 20; TextStyle headline; @@ -403,10 +411,68 @@ std::vector top_apps_panel(Host &host, const Rect &card, std::wstring TextStyle style; style.font = Font::Body; style.halign = HAlign::Center; - r.text(host.store().has_snapshot() ? L"No app is busy right now." : L"Collecting…", + r.text(host.store().has_snapshot() ? std::wstring(empty) : std::wstring(L"Collecting…"), Rect{inner.x, inner.y, inner.w, kTopAppRowHeight}, style, theme.text_tertiary()); } return hits; } +bool page_available(const Store &store, PageId id) { + switch (id) { + case PageId::Gpu: return store.has(PC_CAP_GPU); + case PageId::Battery: return store.has(PC_CAP_BATTERY); + case PageId::Startup: return store.has(PC_CAP_STARTUP); + case PageId::Services: return store.has(PC_CAP_SERVICES); + case PageId::Inspect: return store.has(PC_CAP_CONNECTIONS) || store.has(PC_CAP_OPEN_FILES); + default: return true; + } +} + +const std::vector &priority_steps() { + static const std::vector steps = {{L"High", -10}, {L"Above normal", -5}, {L"Normal", 0}, + {L"Below normal", 5}, {L"Low", 10}, {L"Lowest", 20}}; + return steps; +} + +const PriorityStep &priority_step(int32_t nice) { + const auto &steps = priority_steps(); + const PriorityStep *best = &steps.front(); + for (const PriorityStep &step : steps) + if (std::abs(step.nice - nice) < std::abs(best->nice - nice)) best = &step; + return *best; +} + +const std::vector &signal_choices() { +#if defined(_WIN32) + static const std::vector none; + return none; +#else + static const std::vector signals = { + {L"SIGHUP", L"Hang up / reload configuration", SIGHUP, false}, + {L"SIGINT", L"Interrupt (like Ctrl+C)", SIGINT, true}, + {L"SIGQUIT", L"Quit and dump core", SIGQUIT, true}, + {L"SIGKILL", L"Kill immediately", SIGKILL, true}, + {L"SIGUSR1", L"User-defined 1", SIGUSR1, false}, + {L"SIGUSR2", L"User-defined 2", SIGUSR2, false}, + {L"SIGTERM", L"Ask to terminate", SIGTERM, true}, + {L"SIGSTOP", L"Suspend", SIGSTOP, true}, + {L"SIGCONT", L"Resume", SIGCONT, false}, + }; + return signals; +#endif +} + +bool app_is_system(const Snapshot &snapshot, const std::string &app_id, int32_t pid) { + if (const pc_process *p = pid > 0 ? snapshot.find(pid) : nullptr) return (p->flags & PC_PROC_SYSTEM) != 0; + for (const pc_process &p : snapshot.processes) + if (p.app_id == app_id) return (p.flags & PC_PROC_SYSTEM) != 0; + return false; +} + +std::wstring battery_state(const pc_battery &battery) { + if (battery.charging) return L"Charging"; + if (battery.fully_charged) return L"Fully charged"; + return battery.on_ac_power ? L"On AC power" : L"On battery"; +} + } // namespace procyon::ui diff --git a/apps/ui/src/platform.hpp b/apps/ui/src/platform.hpp index 737e489..a199dc1 100644 --- a/apps/ui/src/platform.hpp +++ b/apps/ui/src/platform.hpp @@ -24,6 +24,10 @@ std::wstring data_file(std::wstring_view name); // Creates the folders a file path needs before it is written. void create_parent_directories(std::wstring_view path); +// Called after Procyon wrote `path` in its data or settings folder. The Linux root copy (pkexec) +// writes into the desktop user's folders and hands what it wrote back to them; elsewhere a no-op. +void file_written(std::wstring_view path); + // The clipboard's text, empty when it holds none. std::wstring clipboard_text(); diff --git a/apps/ui/src/render.cpp b/apps/ui/src/render.cpp index 38c92d5..ca7b069 100644 --- a/apps/ui/src/render.cpp +++ b/apps/ui/src/render.cpp @@ -1,5 +1,5 @@ // The component vocabulary of design/components.md, drawn with Canvas primitives. Platform -// independent: the Direct2D and (later) Cairo backends only implement Canvas. +// independent: the Direct2D (Windows) and Cairo (Linux) backends only implement Canvas. #include #include diff --git a/apps/ui/src/store.cpp b/apps/ui/src/store.cpp index ad0fa70..b90f8f9 100644 --- a/apps/ui/src/store.cpp +++ b/apps/ui/src/store.cpp @@ -1,6 +1,7 @@ #include "store.hpp" #include +#include #include #include #include @@ -51,8 +52,21 @@ void Store::stop() { if (thread_.joinable()) thread_.join(); } +namespace { +std::atomic history_samples{60}; +} // namespace + +size_t history_window() { return history_samples.load(std::memory_order_relaxed); } + +void set_history_interval(double seconds) { + const double samples = std::round(kHistorySeconds / std::clamp(seconds, 0.5, 5.0)); + history_samples.store(std::clamp(static_cast(samples), 2, kHistoryMaxSamples), + std::memory_order_relaxed); +} + void Store::set_interval(double seconds) { interval_ = std::clamp(seconds, 0.5, 5.0); + set_history_interval(interval_); wake_.notify_all(); } @@ -327,6 +341,11 @@ pc_result Store::end_tree(int32_t pid) { return pc_process_end_tree(monitor_, pid); } +pc_result Store::send_signal(int32_t pid, int32_t signal) { + std::lock_guard lock(monitor_mutex_); + return pc_process_signal(monitor_, pid, signal); +} + pc_result Store::suspend(int32_t pid) { std::lock_guard lock(monitor_mutex_); return pc_process_suspend(monitor_, pid); diff --git a/apps/ui/src/store.hpp b/apps/ui/src/store.hpp index ef298bd..1b23134 100644 --- a/apps/ui/src/store.hpp +++ b/apps/ui/src/store.hpp @@ -23,19 +23,26 @@ namespace procyon::ui { -// One sample a tick for every live chart: the last 60 seconds are visible. -constexpr size_t kHistoryWindow = 60; +// One sample a tick for every live chart; the charts show the last 60 seconds (as the macOS app's +// time-based window does), which is 60 samples at 1 s updates, 120 at 0.5 s and 12 at 5 s. +constexpr double kHistorySeconds = 60; +constexpr size_t kHistoryMaxSamples = 120; // 60 s at the fastest update speed, 0.5 s +// The samples that span kHistorySeconds at the current update speed (set by Store::set_interval). +size_t history_window(); +void set_history_interval(double seconds); class Series { public: void push(float value) { values_.push_back(value); - if (values_.size() > kHistoryWindow * 4) values_.erase(values_.begin(), values_.begin() + kHistoryWindow); + if (values_.size() > kHistoryMaxSamples * 4) + values_.erase(values_.begin(), values_.begin() + kHistoryMaxSamples); } const float *data() const { return values_.data(); } size_t size() const { return values_.size(); } float last() const { return values_.empty() ? 0 : values_.back(); } - float max_recent(size_t window = kHistoryWindow) const { + float max_recent(size_t window = 0) const { + if (window == 0) window = history_window(); float m = 0; const size_t start = values_.size() > window ? values_.size() - window : 0; for (size_t i = start; i < values_.size(); ++i) m = std::max(m, values_[i]); @@ -183,6 +190,7 @@ class Store { pc_result suspend(int32_t pid); pc_result resume(int32_t pid); pc_result set_priority(int32_t pid, int32_t nice); + pc_result send_signal(int32_t pid, int32_t signal); pc_result set_affinity(int32_t pid, uint64_t mask); std::optional details(int32_t pid); std::vector open_files(int32_t pid, bool &complete); diff --git a/apps/ui/src/ui.hpp b/apps/ui/src/ui.hpp index d5952a6..cdeb2cf 100644 --- a/apps/ui/src/ui.hpp +++ b/apps/ui/src/ui.hpp @@ -1,4 +1,4 @@ -// Shared UI foundation for the non-Apple Procyon apps (Windows today, Linux next): geometry, +// Shared UI foundation for the non-Apple Procyon apps (Windows and Linux): geometry, // colors, the theme (design tokens resolved for light or dark), formatting, the vector path and // Canvas interface each platform implements, and the Renderer that draws every component of // design/components.md on top of a Canvas. Nothing in here includes a platform header. @@ -118,6 +118,7 @@ std::wstring cpu(double percent); // std::wstring bytes(double value); // base 1024 std::wstring bytes(int64_t value); // -1 unknown std::wstring rate(double bytes_per_second); // "1.2 MB/s" +std::wstring endpoint(std::wstring_view address, int port); // "[::1]:443", "1.2.3.4:443" std::wstring count(int64_t value); // "1,234" std::wstring duration(double seconds); // "2h 15m" std::wstring temperature(double celsius, bool fahrenheit); // "61°C" diff --git a/apps/windows/CMakeLists.txt b/apps/windows/CMakeLists.txt index b165ddb..606866f 100644 --- a/apps/windows/CMakeLists.txt +++ b/apps/windows/CMakeLists.txt @@ -17,7 +17,7 @@ add_executable(Procyon WIN32 ) # `design` is on the include path for the fonts the .rc embeds (fonts/InterVariable.ttf). target_include_directories(Procyon PRIVATE src res "${CMAKE_CURRENT_SOURCE_DIR}/../../design") -target_link_libraries(Procyon PRIVATE procyon_ui d2d1 dwrite d3d11 dxgi dcomp dxguid dwmapi comctl32 shell32 ole32 uxtheme gdi32) +target_link_libraries(Procyon PRIVATE procyon_ui d2d1 dwrite d3d11 dxgi dcomp dxguid dwmapi comctl32 shell32 ole32 uxtheme gdi32 windowscodecs) target_compile_options(Procyon PRIVATE /W4 /utf-8 /permissive- /Zc:__cplusplus /wd4100) target_compile_definitions(Procyon PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _CRT_SECURE_NO_WARNINGS) set_target_properties(Procyon PROPERTIES OUTPUT_NAME "Procyon") diff --git a/apps/windows/res/Procyon.rc b/apps/windows/res/Procyon.rc index 5c54095..3297b13 100644 --- a/apps/windows/res/Procyon.rc +++ b/apps/windows/res/Procyon.rc @@ -29,6 +29,7 @@ BEGIN "P", IDM_PAUSE, VIRTKEY, CONTROL, SHIFT VK_OEM_COMMA, IDM_PAGE_SETTINGS, VIRTKEY, CONTROL VK_F5, IDM_REFRESH, VIRTKEY + "Q", IDM_QUIT, VIRTKEY, CONTROL END VS_VERSION_INFO VERSIONINFO diff --git a/apps/windows/src/canvas_d2d.cpp b/apps/windows/src/canvas_d2d.cpp index 849d8e0..5b1fb4c 100644 --- a/apps/windows/src/canvas_d2d.cpp +++ b/apps/windows/src/canvas_d2d.cpp @@ -2,6 +2,8 @@ // (the Shadow effect of a device context), clipping and text in the bundled Inter and Nunito. #include "canvas_d2d.hpp" +#include + #include #include #include @@ -12,6 +14,7 @@ #pragma comment(lib, "d2d1.lib") #pragma comment(lib, "dwrite.lib") +#pragma comment(lib, "windowscodecs.lib") namespace procyon::ui { @@ -262,6 +265,11 @@ bool D2DCanvas::end() { while (!transforms_.empty()) pop_transform(); prune_layouts(); HRESULT hr = target_->EndDraw(); + // Before Present: a flip-model swap chain's buffer 0 is the frame just drawn only until then. + if (SUCCEEDED(hr) && !capture_path_.empty()) { + captured_ = save_back_buffer(capture_path_); + capture_path_.clear(); + } if (SUCCEEDED(hr)) hr = swap_chain_->Present(1, 0); if (hr == D2DERR_RECREATE_TARGET || hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { release_device(); @@ -270,6 +278,54 @@ bool D2DCanvas::end() { return SUCCEEDED(hr); } +// Copies the back buffer into a CPU-readable texture and encodes it as a PNG with WIC. The buffer is +// premultiplied BGRA; the PNG gets straight alpha, which is opaque wherever the page drew. +bool D2DCanvas::save_back_buffer(const std::wstring &path) { + ComPtr buffer; + if (FAILED(swap_chain_->GetBuffer(0, IID_PPV_ARGS(&buffer)))) return false; + D3D11_TEXTURE2D_DESC desc{}; + buffer->GetDesc(&desc); + desc.Usage = D3D11_USAGE_STAGING; + desc.BindFlags = 0; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + desc.MiscFlags = 0; + ComPtr staging; + if (FAILED(d3d_->CreateTexture2D(&desc, nullptr, &staging))) return false; + ComPtr context; + d3d_->GetImmediateContext(&context); + context->CopyResource(staging.Get(), buffer.Get()); + D3D11_MAPPED_SUBRESOURCE mapped{}; + if (FAILED(context->Map(staging.Get(), 0, D3D11_MAP_READ, 0, &mapped))) return false; + const UINT stride = desc.Width * 4; + std::vector pixels(static_cast(stride) * desc.Height); + for (UINT y = 0; y < desc.Height; ++y) { + const BYTE *from = static_cast(mapped.pData) + static_cast(y) * mapped.RowPitch; + BYTE *to = pixels.data() + static_cast(y) * stride; + for (UINT x = 0; x < desc.Width; ++x, from += 4, to += 4) { + const BYTE a = from[3]; + for (int c = 0; c < 3; ++c) to[c] = a ? static_cast(std::min(255, from[c] * 255 / a)) : 0; + to[3] = a; + } + } + context->Unmap(staging.Get(), 0); + + ComPtr wic; + ComPtr stream; + ComPtr encoder; + ComPtr frame; + if (FAILED(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&wic))) || + FAILED(wic->CreateStream(&stream)) || FAILED(stream->InitializeFromFilename(path.c_str(), GENERIC_WRITE)) || + FAILED(wic->CreateEncoder(GUID_ContainerFormatPng, nullptr, &encoder)) || + FAILED(encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache)) || + FAILED(encoder->CreateNewFrame(&frame, nullptr)) || FAILED(frame->Initialize(nullptr)) || + FAILED(frame->SetSize(desc.Width, desc.Height))) + return false; + WICPixelFormatGUID format = GUID_WICPixelFormat32bppBGRA; + if (FAILED(frame->SetPixelFormat(&format)) || format != GUID_WICPixelFormat32bppBGRA) return false; + return SUCCEEDED(frame->WritePixels(desc.Height, stride, static_cast(pixels.size()), pixels.data())) && + SUCCEEDED(frame->Commit()) && SUCCEEDED(encoder->Commit()); +} + // --------------------------------------------------------------------------------------------- // Images // --------------------------------------------------------------------------------------------- diff --git a/apps/windows/src/canvas_d2d.hpp b/apps/windows/src/canvas_d2d.hpp index 77e9f5d..b1d4da6 100644 --- a/apps/windows/src/canvas_d2d.hpp +++ b/apps/windows/src/canvas_d2d.hpp @@ -41,6 +41,10 @@ class D2DCanvas : public Canvas { // when the device is lost (the window then repaints on the next frame). bool begin(Color background); bool end(); + // The next end() also writes the frame to a PNG at `path` (--screenshot), opaque, at the + // window's pixel size. captured() says whether that worked. + void capture_next_frame(std::wstring path) { capture_path_ = std::move(path); } + bool captured() const { return captured_; } // ---- Canvas ---- float dpi() const override { return dpi_; } @@ -76,6 +80,7 @@ class D2DCanvas : public Canvas { } }; + bool save_back_buffer(const std::wstring &path); bool create_device(); bool create_swap_chain(); bool bind_back_buffer(); @@ -136,6 +141,8 @@ class D2DCanvas : public Canvas { ComPtr tabular_; // tabular figures, shared by every layout std::unordered_map layouts_; uint32_t frame_ = 0; // counts begin(); stamps the layouts a frame used + std::wstring capture_path_; + bool captured_ = false; std::wstring ui_family_, display_family_, mono_family_; ComPtr dwrite6_; // variable-font text formats (Windows 10 1809+) ComPtr embedded_fonts_; // the bundled Inter and Nunito; null when they could not load diff --git a/apps/windows/src/platform_windows.cpp b/apps/windows/src/platform_windows.cpp index 68b315e..7d050c2 100644 --- a/apps/windows/src/platform_windows.cpp +++ b/apps/windows/src/platform_windows.cpp @@ -147,6 +147,9 @@ std::shared_ptr app_icon(std::wstring_view path, int pixels) { return image; } +// The elevated copy runs as the same user, so its files are already theirs. +void file_written(std::wstring_view) {} + std::wstring clipboard_text() { std::wstring out; if (!OpenClipboard(nullptr)) return out; diff --git a/apps/windows/src/window.cpp b/apps/windows/src/window.cpp index c7d6080..2b90893 100644 --- a/apps/windows/src/window.cpp +++ b/apps/windows/src/window.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include "canvas_d2d.hpp" @@ -42,6 +43,15 @@ constexpr float kSidebarOpacityDark = 0.62f; constexpr float kSidebarOpacityLight = 0.55f; const wchar_t *const kClassName = L"ProcyonMainWindow"; const wchar_t *const kSettingsKey = L"Software\\Procyon"; +// One Procyon per sign-in session: the first holds this mutex, a later launch brings its window up. +const wchar_t *const kInstanceMutex = L"Local\\Procyon.Instance"; + +// Posted by a second launch to the running window (registered: an elevated window lets it through +// User Interface Privilege Isolation with ChangeWindowMessageFilterEx). +UINT activate_message() { + static const UINT message = RegisterWindowMessageW(L"Procyon.Activate"); + return message; +} // A sidebar entry: a page row (symbol, title, detail), a metric row (icon, title, value, // sparkline) or a section label. @@ -85,11 +95,25 @@ std::optional page_from_name(const std::wstring &name) { class MainWindow : public Host { public: - MainWindow(HINSTANCE instance, std::optional initial, bool persist) - : instance_(instance), initial_page_(initial), persist_(persist) {} + // --screenshot: the window is never shown; after a few samples the page is drawn once into a PNG + // and Procyon exits (the counterpart of the Linux app's mode, for CI and the README). + struct Screenshot { + std::wstring path; + int theme = 1; // light; --dark: 2 + }; + + MainWindow(HINSTANCE instance, std::optional initial, bool persist, + std::optional screenshot = std::nullopt) + : instance_(instance), initial_page_(initial), persist_(persist), screenshot_(std::move(screenshot)) {} + + int exit_code() const { return exit_code_; } bool create(int show_command) { load_settings(); + if (screenshot_) { + settings_.theme = screenshot_->theme; + settings_.records_history = false; + } WNDCLASSEXW wc{}; wc.cbSize = sizeof(wc); wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; @@ -105,6 +129,18 @@ class MainWindow : public Host { hwnd_ = CreateWindowExW(WS_EX_NOREDIRECTIONBITMAP, kClassName, L"Procyon", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1280, 800, nullptr, nullptr, instance_, this); if (!hwnd_) return false; + if (screenshot_) { + // 1280×800 of client area at the monitor's scale, hidden. The frame is what WM_NCCALCSIZE + // left of it (the resize borders), measured rather than assumed. + RECT window{}, client{}; + GetWindowRect(hwnd_, &window); + GetClientRect(hwnd_, &client); + const int frame_w = (window.right - window.left) - client.right; + const int frame_h = (window.bottom - window.top) - client.bottom; + SetWindowPos(hwnd_, nullptr, 0, 0, to_px(1280) + frame_w, to_px(800) + frame_h, + SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); + return true; + } restore_placement(show_command); return true; } @@ -126,6 +162,11 @@ class MainWindow : public Host { float mouse_y() override { return overlays_.empty() ? mouse_y_ : -1; } void navigate(PageId id) override { + // A screen this machine doesn't have (a shortcut, --page): stay, or start on Overview. + if (!page_available(store_, id)) { + if (current_) return; + id = PageId::Overview; + } for (auto &page : pages_) { if (page->id() != id) continue; current_ = page.get(); @@ -214,7 +255,9 @@ class MainWindow : public Host { if (elevated()) return; wchar_t path[MAX_PATH]; GetModuleFileNameW(nullptr, path, MAX_PATH); - const std::wstring params = std::wstring(L"--page ") + (current_ ? page_name(current_->id()) : L"overview"); + // --relaunch: the new copy waits for this one to exit instead of handing over to it. + const std::wstring params = + std::wstring(L"--relaunch --page ") + (current_ ? page_name(current_->id()) : L"overview"); SHELLEXECUTEINFOW info{}; info.cbSize = sizeof(info); info.fMask = SEE_MASK_NOCLOSEPROCESS; @@ -312,7 +355,9 @@ class MainWindow : public Host { const MARGINS whole{-1, -1, -1, -1}; DwmExtendFrameIntoClientArea(hwnd_, &whole); const DWORD backdrop = kDwmSystemBackdropMainWindow; - mica_ = SUCCEEDED(DwmSetWindowAttribute(hwnd_, kDwmSystemBackdropType, &backdrop, sizeof(backdrop))); + // A screenshot has no desktop behind it: an opaque sidebar. + mica_ = !screenshot_ && + SUCCEEDED(DwmSetWindowAttribute(hwnd_, kDwmSystemBackdropType, &backdrop, sizeof(backdrop))); apply_theme(); pages_.push_back(make_overview_page()); pages_.push_back(make_processes_page()); @@ -333,7 +378,7 @@ class MainWindow : public Host { return PostMessageW(hwnd_, WM_APP_SNAPSHOT, 0, reinterpret_cast(snapshot)) != FALSE; }); navigate(initial_page_.value_or(PageId::Overview)); - add_tray(); + if (!screenshot_) add_tray(); } void build_nav() { @@ -365,19 +410,19 @@ class MainWindow : public Host { section(L"Performance"); metric(PageId::Cpu, L"CPU", MetricKind::Cpu); metric(PageId::Memory, L"Memory", MetricKind::Memory); - if (store_.has(PC_CAP_GPU)) metric(PageId::Gpu, L"GPU", MetricKind::Gpu); + if (page_available(store_, PageId::Gpu)) metric(PageId::Gpu, L"GPU", MetricKind::Gpu); metric(PageId::Disk, L"Disk", MetricKind::Disk); metric(PageId::Network, L"Network", MetricKind::Network); - if (store_.has(PC_CAP_STARTUP) || store_.has(PC_CAP_SERVICES)) { + if (page_available(store_, PageId::Startup) || page_available(store_, PageId::Services)) { section(L"Manage"); - if (store_.has(PC_CAP_STARTUP)) page(PageId::Startup, L"Startup", Renderer::Symbol::Power); - if (store_.has(PC_CAP_SERVICES)) page(PageId::Services, L"Services", Renderer::Symbol::Gears); + if (page_available(store_, PageId::Startup)) page(PageId::Startup, L"Startup", Renderer::Symbol::Power); + if (page_available(store_, PageId::Services)) page(PageId::Services, L"Services", Renderer::Symbol::Gears); } section(L"Analyze"); page(PageId::History, L"History", Renderer::Symbol::Clock); - if (store_.has(PC_CAP_CONNECTIONS)) page(PageId::Inspect, L"Files & Ports", Renderer::Symbol::Ports); + if (page_available(store_, PageId::Inspect)) page(PageId::Inspect, L"Files & Ports", Renderer::Symbol::Ports); section(L"Machine"); - if (store_.has(PC_CAP_BATTERY)) page(PageId::Battery, L"Battery", Renderer::Symbol::Gauge); + if (page_available(store_, PageId::Battery)) page(PageId::Battery, L"Battery", Renderer::Symbol::Gauge); page(PageId::System, L"System", Renderer::Symbol::Info); // info.circle.fill on macOS } @@ -442,6 +487,22 @@ class MainWindow : public Host { return Rect{0, 0, to_dip(rc.right), to_dip(rc.bottom)}; } + void take_screenshot() { + canvas_.capture_next_frame(screenshot_->path); + paint(); + if (!canvas_.captured()) { + exit_code_ = 1; + if (AttachConsole(ATTACH_PARENT_PROCESS)) { + const std::wstring message = L"Procyon: couldn't write " + screenshot_->path + L"\n"; + DWORD written = 0; + WriteConsoleW(GetStdHandle(STD_ERROR_HANDLE), message.c_str(), static_cast(message.size()), + &written, nullptr); + } + } + quit_ = true; + DestroyWindow(hwnd_); + } + void paint() { // The theme follows Settings, which may have changed since the last frame. const bool dark = settings_.theme == 2 || (settings_.theme == 0 && platform::system_prefers_dark()); @@ -545,7 +606,8 @@ class MainWindow : public Host { void caption_button_action(int button) { switch (button) { - case 0: ShowWindow(hwnd_, SW_MINIMIZE); break; + // Through WM_SYSCOMMAND, like Win+Down and the taskbar: minimizing to the tray applies too. + case 0: PostMessageW(hwnd_, WM_SYSCOMMAND, SC_MINIMIZE, 0); break; case 1: ShowWindow(hwnd_, IsZoomed(hwnd_) ? SW_RESTORE : SW_MAXIMIZE); break; case 2: PostMessageW(hwnd_, WM_CLOSE, 0, 0); break; default: break; @@ -564,11 +626,7 @@ class MainWindow : public Host { case PageId::History: return store_.records_history() ? L"The last 24 hours" : L"Off"; case PageId::Inspect: return L"Who uses a port or a file"; case PageId::Battery: { - if (auto b = store_.battery()) - return fmt::percent(b->level) + L" · " + - (b->charging ? L"Charging" - : b->on_ac_power ? L"On AC power" - : L"On battery"); + if (auto b = store_.battery()) return fmt::percent(b->level) + L" · " + battery_state(*b); return L""; } case PageId::System: return fmt::from_utf8(info.os_name) + L" " + fmt::from_utf8(info.os_version); @@ -724,14 +782,14 @@ class MainWindow : public Host { options.end_dot = false; options.halo = false; options.line_width = 1.25f; - r.sparkline(Rect{spark.x, spark.cy() - 11, spark.w, 22}, series->data(), series->size(), kHistoryWindow, - max, item.metric, options); + r.sparkline(Rect{spark.x, spark.cy() - 11, spark.w, 22}, series->data(), series->size(), + history_window(), max, item.metric, options); if (secondary && secondary->size() > 1) { options.area = false; Color end = rgba(metric_style(item.metric).end); options.color_override = &end; r.sparkline(Rect{spark.x, spark.cy() - 11, spark.w, 22}, secondary->data(), secondary->size(), - kHistoryWindow, max, item.metric, options); + history_window(), max, item.metric, options); } } } @@ -790,7 +848,10 @@ class MainWindow : public Host { case IDM_PAGE_INSPECT: navigate(PageId::Inspect); break; case IDM_PAGE_SYSTEM: navigate(PageId::System); break; case IDM_PAGE_BATTERY: navigate(PageId::Battery); break; - case IDM_PAGE_SETTINGS: navigate(PageId::Settings); break; + case IDM_PAGE_SETTINGS: + if (hidden_) show_from_tray(); // from the tray menu + navigate(PageId::Settings); + break; case IDM_PALETTE: open_palette(); break; case IDM_FIND: if (current_ && current_->id() != PageId::Processes && current_->id() != PageId::Services && @@ -823,22 +884,37 @@ class MainWindow : public Host { } void open_palette() { + // Ctrl+K again closes it, as ⌘K toggles the macOS palette. + bool was_open = false; + for (auto &overlay : overlays_) + if (overlay->is_palette() && !overlay->closed()) { + overlay->close(); + was_open = true; + } + if (was_open) { + overlays_.erase( + std::remove_if(overlays_.begin(), overlays_.end(), [](const auto &o) { return o->closed(); }), + overlays_.end()); + repaint(); + return; + } std::vector items; auto screen = [&](PageId id, const wchar_t *title, const wchar_t *shortcut) { + if (!page_available(store_, id)) return; items.push_back({PaletteItem::Kind::Screen, title, L"", shortcut, [this, id] { navigate(id); }}); }; screen(PageId::Overview, L"Overview", L"Ctrl+1"); screen(PageId::Processes, L"Processes", L"Ctrl+2"); screen(PageId::Cpu, L"CPU", L"Ctrl+3"); screen(PageId::Memory, L"Memory", L"Ctrl+4"); - if (store_.has(PC_CAP_GPU)) screen(PageId::Gpu, L"GPU", L"Ctrl+5"); + screen(PageId::Gpu, L"GPU", L"Ctrl+5"); screen(PageId::Disk, L"Disk", L"Ctrl+6"); screen(PageId::Network, L"Network", L"Ctrl+7"); screen(PageId::Startup, L"Startup", L"Ctrl+8"); screen(PageId::Services, L"Services", L"Ctrl+9"); screen(PageId::History, L"History", L""); screen(PageId::Inspect, L"Files & Ports", L""); - if (store_.has(PC_CAP_BATTERY)) screen(PageId::Battery, L"Battery", L""); + screen(PageId::Battery, L"Battery", L""); screen(PageId::System, L"System", L""); screen(PageId::Settings, L"Settings", L"Ctrl+,"); items.push_back({PaletteItem::Kind::Command, store_.paused() ? L"Resume updates" : L"Pause updates", L"", @@ -855,7 +931,8 @@ class MainWindow : public Host { items.push_back( {PaletteItem::Kind::Command, L"Get Info: " + name, L"", L"Ctrl+I", [this, pid] { show_info(pid); }}); } - items.push_back({PaletteItem::Kind::Command, L"Quit Procyon", L"", L"", [this] { on_command(IDM_QUIT); }}); + items.push_back( + {PaletteItem::Kind::Command, L"Quit Procyon", L"", L"Ctrl+Q", [this] { on_command(IDM_QUIT); }}); ViewQuery query; query.mode = PC_VIEW_GROUPED; query.sort_column = PC_COLUMN_CPU; @@ -872,9 +949,10 @@ class MainWindow : public Host { : L""; const int32_t pid = row.is_group() ? row.group_pid : p ? p->pid : 0; if (name.empty() || pid <= 0) continue; + // Opens the app's actions, the macOS palette's second level. PaletteItem item{PaletteItem::Kind::App, name, - L"CPU " + fmt::cpu(row.cpu_percent) + L" · " + fmt::bytes(row.memory_bytes), L"", - [this, pid] { show_info(pid); }}; + L"CPU " + fmt::cpu(row.cpu_percent) + L" · " + fmt::bytes(row.memory_bytes), L"", nullptr}; + item.children = app_palette_actions(*this, row, p, name, [this](int id) { on_command(id); }); item.icon_path = app_icon_path(row, p, s); item.icon_system = p && (p->flags & PC_PROC_SYSTEM) != 0; items.push_back(std::move(item)); @@ -904,19 +982,20 @@ class MainWindow : public Host { void update_tray() { if (!tray_added_) return; const Snapshot &s = store_.snapshot(); - std::wstring tip = L"Procyon"; - if (store_.paused()) { - tip += L" · paused"; - } else { - // Every module switched on in Settings, like the menu bar modules on macOS. + std::wstring tip = store_.paused() ? L"Procyon · paused" : L"Procyon"; + // Every module switched on in Settings, like the menu bar modules on macOS; paused, the last + // figures stay. Nothing before the first sample. + if (store_.has_snapshot()) { if (settings_.tray_modules & 1) tip += L" · CPU " + fmt::percent(s.cpu_usage); - if (settings_.tray_modules & 2) tip += L" · Memory " + fmt::bytes(static_cast(s.memory_used)); + if (settings_.tray_modules & 2) + tip += L" · Memory " + + fmt::percent(s.memory_total ? static_cast(s.memory_used) / s.memory_total : 0); if (settings_.tray_modules & 4) tip += L" · ↓ " + fmt::rate(s.net_rx_bps) + L" ↑ " + fmt::rate(s.net_tx_bps); - if ((settings_.tray_modules & 8) && !s.gpus.empty()) + if ((settings_.tray_modules & 8) && !s.gpus.empty() && s.gpus[0].utilization >= 0) tip += L" · GPU " + fmt::percent(s.gpus[0].utilization); if ((settings_.tray_modules & 16) && s.cpu_temperature >= 0) - tip += L" · " + fmt::temperature(s.cpu_temperature, settings_.fahrenheit); + tip += L" · CPU " + fmt::temperature(s.cpu_temperature, settings_.fahrenheit); if (settings_.tray_modules & 32) if (auto b = store_.battery(); b && b->present) tip += L" · Battery " + fmt::percent(b->level); } @@ -933,7 +1012,14 @@ class MainWindow : public Host { // An alert as a Windows notification (a balloon of the tray icon, which Windows 10 and 11 show // as a toast and keep in the notification center), also while Procyon is in front. void notify(const AlertEvent &event) { - if (!tray_added_) return; + if (!tray_added_) add_tray(); // the shell may not have been ready at start + if (!tray_added_) { + // No notification area to show it in: at least make a sound; the alert is still listed + // under Settings → Alerts. + MessageBeep(MB_ICONWARNING); + repaint(); + return; + } NOTIFYICONDATAW data = tray_; data.uFlags = NIF_INFO; data.dwInfoFlags = NIIF_WARNING | NIIF_RESPECT_QUIET_TIME; @@ -969,6 +1055,7 @@ class MainWindow : public Host { HMENU menu = CreatePopupMenu(); AppendMenuW(menu, MF_STRING, IDM_OPEN, L"Open Procyon"); AppendMenuW(menu, MF_STRING, IDM_PAUSE, store_.paused() ? L"Resume updates" : L"Pause updates"); + AppendMenuW(menu, MF_STRING, IDM_PAGE_SETTINGS, L"Settings…"); AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); AppendMenuW(menu, MF_STRING, IDM_QUIT, L"Quit"); SetMenuDefaultItem(menu, IDM_OPEN, FALSE); @@ -987,14 +1074,17 @@ class MainWindow : public Host { if (!persist_) return; // --no-settings: defaults, nothing read HKEY key = nullptr; if (RegOpenKeyExW(HKEY_CURRENT_USER, kSettingsKey, 0, KEY_READ, &key) != ERROR_SUCCESS) return; + // Only a DWORD of the expected size counts: anything else (a hand-edited string) is the default, + // as platform::read_setting and the Linux key file treat it. auto dword = [&](const wchar_t *name, DWORD fallback) { - DWORD value = fallback, size = sizeof(value); - if (RegQueryValueExW(key, name, nullptr, nullptr, reinterpret_cast(&value), &size) != ERROR_SUCCESS) + DWORD value = fallback, size = sizeof(value), type = 0; + if (RegQueryValueExW(key, name, nullptr, &type, reinterpret_cast(&value), &size) != ERROR_SUCCESS || + type != REG_DWORD || size != sizeof(value)) return fallback; return value; }; settings_.interval = std::clamp(dword(L"IntervalMs", 1000) / 1000.0, 0.5, 5.0); - settings_.theme = static_cast(dword(L"Theme", 0)); + settings_.theme = std::clamp(static_cast(dword(L"Theme", 0)), 0, 2); settings_.fahrenheit = dword(L"Fahrenheit", 0) != 0; settings_.minimize_to_tray = dword(L"MinimizeToTray", 1) != 0; settings_.tray_modules = static_cast(dword(L"TrayModules", 1 | 2)); @@ -1029,7 +1119,8 @@ class MainWindow : public Host { WINDOWPLACEMENT placement{}; placement.length = sizeof(placement); if (GetWindowPlacement(hwnd_, &placement)) { - if (placement.showCmd == SW_SHOWMINIMIZED) placement.showCmd = SW_SHOWNORMAL; + // Maximized or not, whatever the window's state now (hidden in the tray, minimized). + placement.showCmd = IsZoomed(hwnd_) ? SW_SHOWMAXIMIZED : SW_SHOWNORMAL; RegSetValueExW(key, L"Placement", 0, REG_BINARY, reinterpret_cast(&placement), sizeof(placement)); } @@ -1038,7 +1129,8 @@ class MainWindow : public Host { void restore_placement(int show_command) { if (has_placement_) { - placement_.showCmd = SW_SHOWNORMAL; + // Reopens maximized when it was closed maximized, never minimized. + if (placement_.showCmd != SW_SHOWMAXIMIZED) placement_.showCmd = SW_SHOWNORMAL; SetWindowPlacement(hwnd_, &placement_); } ShowWindow(hwnd_, has_placement_ ? SW_SHOW : show_command); @@ -1066,8 +1158,22 @@ class MainWindow : public Host { // ---- window procedure ---- LRESULT proc(UINT message, WPARAM wparam, LPARAM lparam) { + // Explorer restarted: the notification area is new and empty, so add the icon again (without + // it a Procyon hidden in the tray could not be opened any more). + static const UINT taskbar_created = RegisterWindowMessageW(L"TaskbarCreated"); + if (message == activate_message() && message != 0) { + show_from_tray(); + return 0; + } + if (taskbar_created && message == taskbar_created) { + add_tray(); + update_tray(); + return 0; + } switch (message) { case WM_CREATE: + // A second, unelevated launch may activate an elevated Procyon. + ChangeWindowMessageFilterEx(hwnd_, activate_message(), MSGFLT_ALLOW, nullptr); on_create(); // Re-run WM_NCCALCSIZE now that the window exists, so the caption goes away. SetWindowPos(hwnd_, nullptr, 0, 0, 0, 0, SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); @@ -1176,6 +1282,10 @@ class MainWindow : public Host { if (nav_.size() < 6) build_nav(); if (current_) current_->tick(*this); for (auto &overlay : overlays_) overlay->tick(*this); + if (screenshot_) { + if (++screenshot_samples_ == 6) take_screenshot(); + return 0; + } update_tray(); if (!hidden_) repaint(); return 0; @@ -1185,7 +1295,8 @@ class MainWindow : public Host { case NIN_SELECT: case NIN_KEYSELECT: case WM_LBUTTONUP: - case WM_LBUTTONDBLCLK: show_from_tray(); break; + case WM_LBUTTONDBLCLK: + case NIN_BALLOONUSERCLICK: show_from_tray(); break; // also a click on an alert case WM_CONTEXTMENU: case WM_RBUTTONUP: tray_menu(); break; default: break; @@ -1317,7 +1428,7 @@ class MainWindow : public Host { store_.stop(); store_.flush_history(); // the minute in progress would otherwise go with the process canvas_.shutdown(); - PostQuitMessage(0); + PostQuitMessage(exit_code_); return 0; default: break; } @@ -1349,6 +1460,9 @@ class MainWindow : public Host { bool tray_added_ = false; bool hidden_ = false; bool quit_ = false; + std::optional screenshot_; + int screenshot_samples_ = 0; + int exit_code_ = 0; WINDOWPLACEMENT placement_{}; bool has_placement_ = false; }; @@ -1369,8 +1483,75 @@ int run_app(HINSTANCE instance, const std::wstring &args, int show_command) { initial = page_from_name(name); } + // The value after `flag` ("--screenshot C:\\out.png"), quoted or not; empty when absent. + const auto value_of = [&args](const wchar_t *flag) -> std::wstring { + const size_t at = args.find(flag); + if (at == std::wstring::npos) return {}; + size_t start = args.find_first_not_of(L' ', at + wcslen(flag)); + if (start == std::wstring::npos) return {}; + if (args[start] == L'"') { + const size_t end = args.find(L'"', start + 1); + return args.substr(start + 1, end == std::wstring::npos ? std::wstring::npos : end - start - 1); + } + const size_t end = args.find(L' ', start); + return args.substr(start, end == std::wstring::npos ? std::wstring::npos : end - start); + }; + + // --version: printed to the console Procyon was started from (a GUI program has none of its own). + if (args.find(L"--version") != std::wstring::npos) { + const std::string text = std::string("Procyon ") + PROCYON_VERSION_STRING + "\n"; + HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); + if (!out || out == INVALID_HANDLE_VALUE) { + if (AttachConsole(ATTACH_PARENT_PROCESS)) out = GetStdHandle(STD_OUTPUT_HANDLE); + } + DWORD written = 0; + if (out && out != INVALID_HANDLE_VALUE) + WriteFile(out, text.data(), static_cast(text.size()), &written, nullptr); + CoUninitialize(); + return 0; + } + + std::optional screenshot; + if (const std::wstring path = value_of(L"--screenshot"); !path.empty()) { + screenshot.emplace(); + screenshot->path = path; + if (args.find(L"--dark") != std::wstring::npos) screenshot->theme = 2; + } + // --no-settings: the defaults (1 s refresh, close to tray) and no registry writes, for measurements. - MainWindow window(instance, initial, args.find(L"--no-settings") == std::wstring::npos); + // A screenshot reads and writes no settings either. + const bool measuring = args.find(L"--no-settings") != std::wstring::npos || screenshot.has_value(); + + // A second launch (Start menu, taskbar) while Procyon runs, maybe hidden in the tray, brings the + // running window up instead of starting another sampler and tray icon, as on macOS and Linux. + // Measurements run beside a running Procyon. An elevated copy's mutex can't be opened from an + // unelevated launch (access denied): that also means one is running. + HANDLE instance_mutex = nullptr; + if (!measuring) { + instance_mutex = CreateMutexW(nullptr, TRUE, kInstanceMutex); + const DWORD error = GetLastError(); + if (!instance_mutex || error == ERROR_ALREADY_EXISTS) { + bool owned = false; + // The copy Unlock Full Access starts: the unelevated one is on its way out. + if (instance_mutex && args.find(L"--relaunch") != std::wstring::npos) { + const DWORD wait = WaitForSingleObject(instance_mutex, 15000); + owned = wait == WAIT_OBJECT_0 || wait == WAIT_ABANDONED; + } + if (!owned) { + if (HWND running = FindWindowW(kClassName, nullptr)) { + DWORD pid = 0; + GetWindowThreadProcessId(running, &pid); + AllowSetForegroundWindow(pid); + PostMessageW(running, activate_message(), 0, 0); + } + if (instance_mutex) CloseHandle(instance_mutex); + CoUninitialize(); + return 0; + } + } + } + + MainWindow window(instance, initial, !measuring, screenshot); g_window = &window; if (!window.create(show_command)) return 1; HACCEL accelerators = LoadAcceleratorsW(instance, MAKEINTRESOURCEW(IDR_ACCELERATORS)); @@ -1378,17 +1559,22 @@ int run_app(HINSTANCE instance, const std::wstring &args, int show_command) { MSG msg; while (GetMessageW(&msg, nullptr, 0, 0) > 0) { bool use_accelerators = true; + // A search field keeps Delete, Backspace and Return for itself, also with Ctrl (Ctrl+Backspace + // deletes a word there), as the macOS app turns End Task off while its search field has focus. if (msg.message == WM_KEYDOWN && window.text_input_active() && - (msg.wParam == VK_DELETE || msg.wParam == VK_BACK || msg.wParam == VK_RETURN) && - !(GetKeyState(VK_CONTROL) & 0x8000)) + (msg.wParam == VK_DELETE || msg.wParam == VK_BACK || msg.wParam == VK_RETURN)) use_accelerators = false; if (use_accelerators && accelerators && TranslateAcceleratorW(window.hwnd(), accelerators, &msg)) continue; TranslateMessage(&msg); DispatchMessageW(&msg); } g_window = nullptr; + if (instance_mutex) { + ReleaseMutex(instance_mutex); + CloseHandle(instance_mutex); + } CoUninitialize(); - return static_cast(msg.wParam); + return static_cast(msg.wParam); // PostQuitMessage(exit_code_) } } // namespace procyon::ui diff --git a/core/include/procyon/procyon.h b/core/include/procyon/procyon.h index e726dbc..524c767 100644 --- a/core/include/procyon/procyon.h +++ b/core/include/procyon/procyon.h @@ -37,7 +37,8 @@ typedef enum { PC_CAP_SUSPEND = 1u << 9, /* pc_process_suspend / pc_process_resume */ PC_CAP_SIGNALS = 1u << 10, /* pc_process_signal with POSIX signal numbers */ PC_CAP_CPU_AFFINITY = 1u << 11, - PC_CAP_TEMPERATURE = 1u << 12, /* pc_snapshot.cpu_temperature, disk_temperature where a sensor exists */ + PC_CAP_TEMPERATURE = 1u << 12, /* a CPU sensor: pc_snapshot.cpu_temperature, and disk_temperature + where the drive has a sensor too */ PC_CAP_BATTERY = 1u << 13, /* pc_battery_get */ PC_CAP_SERVICES = 1u << 14, /* pc_monitor_services, pc_service_control */ PC_CAP_STARTUP = 1u << 15, /* pc_monitor_startup_items, pc_startup_set_enabled */ @@ -305,7 +306,10 @@ pc_result pc_process_end(pc_monitor *monitor, int32_t pid, bool force); /* Force-kills pid and all its descendants (children first). */ pc_result pc_process_end_tree(pc_monitor *monitor, int32_t pid); -/* Sends a POSIX signal number (PC_CAP_SIGNALS). Protected processes refuse every signal. */ +/* Sends a POSIX signal (PC_CAP_SIGNALS). The number is the running OS's own, from its : + * they differ between macOS and Linux (SIGSTOP is 17 on macOS, 19 on Linux; SIGUSR1 30 and 10), so a + * caller uses the SIG* constants of the platform it runs on, never hard-coded numbers. + * Protected processes refuse every signal. */ pc_result pc_process_signal(pc_monitor *monitor, int32_t pid, int32_t signal); /* Stops / continues every thread of the process (PC_CAP_SUSPEND). */ diff --git a/core/src/platform.hpp b/core/src/platform.hpp index a369b4b..658cb6b 100644 --- a/core/src/platform.hpp +++ b/core/src/platform.hpp @@ -187,6 +187,16 @@ struct DesktopEntry { bool session_phase = false; // X-GNOME-Autostart-Phase: a session component }; DesktopEntry parse_desktop_entry(const std::string &text); +// One temperature input of /sys/class/hwmon: its driver's name, its label and the input file. +struct HwmonInput { + std::string driver, label, input; +}; +// The inputs that measure the CPU, best first (exposed for tests). +std::vector cpu_sensor_inputs(const std::vector &inputs); +// Whether a systemd unit is part of the OS (pc_service.apple) (exposed for tests). +bool systemd_os_unit(const std::string &id, const std::string &fragment, const std::string &program); +// pc_battery.condition from sysfs `health` and the capacity health (-1 unknown) (exposed for tests). +std::string battery_condition(const std::string &sysfs_health, double health); #endif #if defined(_WIN32) // The parsing half of power_assertions() on Windows: `report` is the output of `powercfg /requests`. diff --git a/core/src/platform/linux.cpp b/core/src/platform/linux.cpp index aafd47a..ce7b0a7 100644 --- a/core/src/platform/linux.cpp +++ b/core/src/platform/linux.cpp @@ -291,6 +291,67 @@ bool read_stat(int32_t pid, ProcStat &out) { return read_file("/proc/" + std::to_string(pid) + "/stat", text) && parse_stat(text, out); } +bool is_interpreter(const std::string &name) { + if (starts_with(name, "python")) return true; // python3, python3.12 + for (const char *i : {"sh", "bash", "dash", "zsh", "env", "perl", "ruby", "node", "java", "electron", "flatpak", + "snap", "gjs", "wine", "mono", "dotnet"}) + if (name == i) return true; + return false; +} + +// uname's machine in the ABI's words (procyon.h: "arm64", "x86_64"), as macOS and Windows report it. +std::string arch_name(const std::string &machine) { + if (machine == "aarch64" || machine == "arm64") return "arm64"; + if (machine == "i386" || machine == "i486" || machine == "i586" || machine == "i686") return "x86"; + if (starts_with(machine, "armv")) return "arm"; + return machine; +} + +namespace { +passwd *session_entry(passwd &entry, char *buffer, size_t size) { + passwd *result = nullptr; + return ::getpwuid_r(session_uid(), &entry, buffer, size, &result) == 0 ? result : nullptr; +} +} // namespace + +uint32_t session_uid() { + if (::geteuid() == 0) + if (const char *caller = std::getenv("PKEXEC_UID"); caller && *caller) { + char *end = nullptr; + const unsigned long uid = std::strtoul(caller, &end, 10); + if (end && *end == '\0' && uid > 0 && uid < 0xFFFFFFFFul) return static_cast(uid); + } + return ::getuid(); +} + +bool acting_for_session_user() { return session_uid() != ::getuid(); } + +std::string session_user_name() { + passwd entry{}; + char buffer[4096]; + const passwd *pw = session_entry(entry, buffer, sizeof(buffer)); + return pw && pw->pw_name ? pw->pw_name : ""; +} + +std::string session_home() { + if (!acting_for_session_user()) { + const char *home = std::getenv("HOME"); + return home ? home : ""; + } + passwd entry{}; + char buffer[4096]; + const passwd *pw = session_entry(entry, buffer, sizeof(buffer)); + return pw && pw->pw_dir ? pw->pw_dir : ""; +} + +void give_to_session_user(const std::string &path) { + if (!acting_for_session_user()) return; + passwd entry{}; + char buffer[4096]; + if (const passwd *pw = session_entry(entry, buffer, sizeof(buffer))) + if (::lchown(path.c_str(), pw->pw_uid, pw->pw_gid) != 0) return; // best effort: stays root's +} + int32_t state_of(char state) { switch (state) { case 'R': return PC_STATE_RUNNING; @@ -416,9 +477,9 @@ uint32_t capabilities() { if (!gpus().empty()) caps |= PC_CAP_GPU; if (process_gpu_available()) caps |= PC_CAP_PROCESS_GPU; if (process_network_available()) caps |= PC_CAP_PROCESS_NETWORK; - double cpu = -1, disk = -1; - temperatures(cpu, disk); - if (cpu >= 0 || disk >= 0) caps |= PC_CAP_TEMPERATURE; + // As on macOS and Windows: a CPU sensor. The UI's temperature module, alert and History metric + // are the CPU's; the drive's reading comes along where the CPU's exists. + if (cpu_temperature() >= 0) caps |= PC_CAP_TEMPERATURE; pc_battery battery_info{}; if (battery(battery_info) && battery_info.present) caps |= PC_CAP_BATTERY; if (!find_program("systemctl").empty() && exists("/run/systemd/system")) caps |= PC_CAP_SERVICES; @@ -463,17 +524,18 @@ bool system_info(pc_system_info &out) { copy_string(out.os_name, sizeof(out.os_name), release.count("NAME") ? release["NAME"] : "Linux"); copy_string(out.os_version, sizeof(out.os_version), release.count("VERSION") ? release["VERSION"] : release["VERSION_ID"]); - copy_string(out.os_build, sizeof(out.os_build), - release.count("BUILD_ID") ? release["BUILD_ID"] : release["VERSION_CODENAME"]); + // The codename is already part of VERSION ("24.04 LTS (Noble Numbat)"): a build only when one exists. + copy_string(out.os_build, sizeof(out.os_build), release.count("BUILD_ID") ? release["BUILD_ID"] : ""); utsname uts{}; if (::uname(&uts) == 0) { copy_string(out.kernel, sizeof(out.kernel), std::string("Linux ") + uts.release); copy_string(out.hostname, sizeof(out.hostname), uts.nodename); - copy_string(out.arch, sizeof(out.arch), uts.machine); + copy_string(out.arch, sizeof(out.arch), arch_name(uts.machine)); } const std::string vendor = trim(read_line("/sys/class/dmi/id/sys_vendor")); const std::string product = trim(read_line("/sys/class/dmi/id/product_name")); const std::string version = trim(read_line("/sys/class/dmi/id/product_version")); + const std::string family = trim(read_line("/sys/class/dmi/id/product_family")); // Boards that ship without a filled-in DMI table say so in many ways. auto placeholder = [](std::string s) { std::transform(s.begin(), s.end(), s.begin(), ::tolower); @@ -481,9 +543,12 @@ bool system_info(pc_system_info &out) { s == "none" || s == "o.e.m."; }; copy_string(out.model_id, sizeof(out.model_id), placeholder(product) ? "" : product); - std::string model = placeholder(product) ? "" : product; + // The family ("ThinkPad X1 Carbon Gen 9", "XPS"), the field Windows shows, over the product name, + // which is often a SKU ("20XW004GUS"). + std::string model = !placeholder(family) ? family : placeholder(product) ? "" : product; + if (placeholder(family) && !model.empty() && !placeholder(version) && version.find("ThinkPad") != std::string::npos) + model = version; if (!model.empty() && !placeholder(vendor) && !starts_with(model, vendor)) model = vendor + " " + model; - if (!model.empty() && !placeholder(version) && version.find("ThinkPad") != std::string::npos) model = version; copy_string(out.model_name, sizeof(out.model_name), model); std::string cpuinfo; @@ -531,7 +596,12 @@ bool system_info(pc_system_info &out) { out.efficiency_cores = static_cast(e_cores.size()); } - const int64_t khz = read_int("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq", 0); + // The base (nominal) clock, as macOS and Windows report it; the maximum boost only where the + // driver publishes nothing else. + const std::string cpufreq = "/sys/devices/system/cpu/cpu0/cpufreq/"; + int64_t khz = read_int(cpufreq + "base_frequency", 0); // intel_pstate + if (khz <= 0) khz = read_int(cpufreq + "amd_pstate_nominal_freq", 0); // amd-pstate + if (khz <= 0) khz = read_int(cpufreq + "cpuinfo_max_freq", 0); out.cpu_frequency_hz = khz > 0 ? static_cast(khz) * 1000 : 0; std::string meminfo; if (read_file("/proc/meminfo", meminfo)) out.memory_total = parse_key_values(meminfo)["MemTotal"] * 1024; @@ -667,12 +737,12 @@ bool memory(Memory &out) { auto bytes = [&](const char *key) { return kb[key] * 1024; }; out.total = bytes("MemTotal"); const uint64_t available = kb.count("MemAvailable") ? bytes("MemAvailable") : bytes("MemFree") + bytes("Cached"); - out.free = bytes("MemFree"); - // Page cache the kernel can drop at once (tmpfs/shm pages can't be dropped: they are in use). - const uint64_t shmem = bytes("Shmem"); - const uint64_t cache = bytes("Cached") + bytes("Buffers") + bytes("SReclaimable"); - out.cached = cache > shmem ? cache - shmem : 0; out.used = out.total > available ? out.total - available : 0; + // The parts add up to the total, as on macOS and Windows: what isn't used is free, or page cache + // the kernel can drop at once (the reclaimable share of MemAvailable beyond MemFree). + const uint64_t unused = out.total - out.used; + out.free = std::min(bytes("MemFree"), unused); + out.cached = unused - out.free; // Kernel memory that can't be paged out, like macOS's "wired". out.wired = bytes("SUnreclaim") + bytes("KernelStack") + bytes("PageTables") + bytes("Unevictable"); // zswap's compressed pool sits in RAM (Zswap:), zram counts as a swap device instead. @@ -861,12 +931,13 @@ const std::unordered_map &desktop_apps() { static const std::unordered_map apps = [] { std::unordered_map map; std::vector dirs; - const char *home = std::getenv("HOME"); + // The desktop user's own entries, also in the root copy (pkexec resets HOME). + const std::string home = session_home(); const char *data_home = std::getenv("XDG_DATA_HOME"); - if (data_home && *data_home) + if (data_home && *data_home == '/') dirs.push_back(std::string(data_home) + "/applications"); - else if (home) - dirs.push_back(std::string(home) + "/.local/share/applications"); + else if (!home.empty()) + dirs.push_back(home + "/.local/share/applications"); const char *data_dirs = std::getenv("XDG_DATA_DIRS"); for (const auto &d : split(data_dirs && *data_dirs ? data_dirs : "/usr/local/share:/usr/share", ':')) if (!d.empty()) dirs.push_back(d + "/applications"); @@ -917,7 +988,7 @@ const std::unordered_map &desktop_apps() { const std::string dir = std::string(resolved).substr(0, std::string(resolved).find_last_of('/')); if (!generic_bin_dir(dir) && !map.count("dir:" + dir)) map["dir:" + dir] = {name}; } - for (const std::string &key : {program, wm_class}) { + for (const std::string &key : {is_interpreter(program) ? std::string() : program, wm_class}) { std::string lower = key; std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); if (!lower.empty() && !map.count(lower)) map[lower] = {name}; @@ -949,15 +1020,19 @@ AppIdentity app_identity(const RawProcess &process) { std::transform(name.begin(), name.end(), name.begin(), ::tolower); found = apps.find(name); } - if (found != apps.end() && !process.path.empty() && process.uid >= 1000) return {process.path, found->second.name}; + // Whoever runs it, as on macOS and Windows: an app started as root (Procyon after Unlock Full Access, + // a partition editor through pkexec) is still that app. + if (found != apps.end() && !process.path.empty()) return {process.path, found->second.name}; return {"exe:" + process.name, process.name}; } bool is_system_process(const RawProcess &process) { // root and the system accounts (below UID_MIN, 1000 on every major distribution), and nobody. if (process.uid < 1000 || process.uid == 65534) return true; + // The OS's own programs in the user's session, like /System, /usr/libexec and /usr/sbin on macOS. return starts_with(process.path, "/usr/libexec/") || starts_with(process.path, "/usr/lib/systemd/") || - starts_with(process.path, "/lib/systemd/"); + starts_with(process.path, "/lib/systemd/") || starts_with(process.path, "/usr/sbin/") || + starts_with(process.path, "/sbin/"); } int32_t self_pid() { return ::getpid(); } @@ -1005,7 +1080,8 @@ pc_result for_each_thread(int32_t pid, Apply apply) { } // namespace pc_result set_priority(int32_t pid, int32_t nice) { - if (nice < -20 || nice > 19) return PC_ERR_INVALID; + if (nice < -20 || nice > 20) return PC_ERR_INVALID; + nice = std::min(nice, 19); // the ABI's range is -20..20 (as on macOS); Linux stops at 19 return for_each_thread(pid, [&](int tid) { errno = 0; return ::setpriority(PRIO_PROCESS, static_cast(tid), nice) == 0; @@ -1051,9 +1127,9 @@ bool process_details(int32_t pid, Details &out) { if (end > start) out.environment.push_back(environ_text.substr(start, end - start)); start = end + 1; } - } else if (exists("/proc/" + std::to_string(pid))) { - out.arguments_known = false; // another user's process: its environment is private } + // Another user's environment is private, but its command line is public: like macOS and + // Windows, arguments_known speaks for the arguments alone, and the environment stays empty. const auto tids = list_dir(proc_path(pid, "task")); const double now = now_seconds(); diff --git a/core/src/platform/linux_gpu.cpp b/core/src/platform/linux_gpu.cpp index 97381d0..697085c 100644 --- a/core/src/platform/linux_gpu.cpp +++ b/core/src/platform/linux_gpu.cpp @@ -265,13 +265,19 @@ std::vector gpus() { if (busy >= 0 && busy <= 100) g.utilization = busy / 100.0; if (g.utilization < 0) g.utilization = intel_awake_share(card, index); ++index; + const int64_t used = read_int(card.device + "/mem_info_vram_used", -1); + const int64_t total = read_int(card.device + "/mem_info_vram_total", -1); if (!card.integrated) { - const int64_t used = read_int(card.device + "/mem_info_vram_used", -1); - const int64_t total = read_int(card.device + "/mem_info_vram_total", -1); if (used >= 0 && total > 0) { g.memory_used = used; g.memory_total = total; } + } else if (used >= 0) { + // An APU's carve-out plus what it maps from system memory (GTT): the memory it uses, as + // macOS and Windows report a unified GPU's. No total: it shares the system's. i915/xe + // publish no such figure. + const int64_t gtt = read_int(card.device + "/mem_info_gtt_used", 0); + g.memory_used = used + std::max(gtt, 0); } if (!card.hwmon.empty()) { const int64_t milli = read_int(card.hwmon + "/temp1_input", -1); diff --git a/core/src/platform/linux_internal.hpp b/core/src/platform/linux_internal.hpp index c4ab0da..7237582 100644 --- a/core/src/platform/linux_internal.hpp +++ b/core/src/platform/linux_internal.hpp @@ -36,6 +36,24 @@ void copy_string(char *dst, size_t capacity, const std::string &src); // Runs `argv` (no shell, LC_ALL=C) and returns its exit status, -1 when it couldn't start or was // killed after `timeout_ms`. Standard output goes to `out`, standard error to `err` when given. int run(const std::vector &argv, std::string &out, std::string *err = nullptr, int timeout_ms = 10000); +// uname's machine as procyon.h spells architectures ("aarch64" -> "arm64", "i686" -> "x86"). +std::string arch_name(const std::string &machine); + +// Programs that run many different apps' code (python3, sh, node, java): their name alone doesn't +// tell which app or startup entry a process is. +bool is_interpreter(const std::string &name); + +// The desktop user Procyon works for. A copy started as root through pkexec (Unlock Full Access) +// still serves the user who asked: pkexec names them in PKEXEC_UID. Otherwise the real user. +uint32_t session_uid(); +// Whether this is such a root copy acting for another (session) user. +bool acting_for_session_user(); +std::string session_user_name(); +// The session user's home folder ("" when unknown). +std::string session_home(); +// Hands a file or folder a root copy created in the session user's home back to that user, so +// the unprivileged copy can change it later. The link itself, never what it points to. No-op otherwise. +void give_to_session_user(const std::string &path); // Path of an executable found in PATH (or the standard system directories), "" when missing. std::string find_program(const std::string &name); diff --git a/core/src/platform/linux_network.cpp b/core/src/platform/linux_network.cpp index b28ae7a..ee7b0c0 100644 --- a/core/src/platform/linux_network.cpp +++ b/core/src/platform/linux_network.cpp @@ -35,13 +35,6 @@ struct SocketBytes { uint64_t rx = 0, tx = 0; }; -bool loopback(int family, const __be32 *address) { - if (family == AF_INET) return (ntohl(address[0]) >> 24) == 127; - // ::1, or an IPv4-mapped loopback (::ffff:127.x.x.x). - if (address[0] == 0 && address[1] == 0 && address[2] == 0 && ntohl(address[3]) == 1) return true; - return address[0] == 0 && address[1] == 0 && ntohl(address[2]) == 0xFFFF && (ntohl(address[3]) >> 24) == 127; -} - // A socket as the kernel identifies it: enough to ask for that one socket again. struct SocketId { uint8_t family = 0; @@ -84,7 +77,8 @@ Request make_request(uint8_t family, const inet_diag_sockid *id) { } // Reads replies until `expected` answers (data or error) arrived, or NLMSG_DONE for a dump. -// Sockets talking only to loopback are skipped, like the machine's own totals skip `lo`. +// Loopback sockets count, as on macOS and Windows: a local database client's traffic is the app's. +// (The machine's totals still skip `lo`, which isn't a physical interface.) bool read_replies(int fd, size_t expected, bool dump, std::unordered_map &out, std::unordered_map *ids) { alignas(nlmsghdr) char buffer[32768]; @@ -101,8 +95,6 @@ bool read_replies(int fd, size_t expected, bool dump, std::unordered_map(NLMSG_DATA(h)); - if (loopback(diag->idiag_family, diag->id.idiag_src) && loopback(diag->idiag_family, diag->id.idiag_dst)) - continue; int length = static_cast(h->nlmsg_len - NLMSG_LENGTH(sizeof(*diag))); for (auto *a = reinterpret_cast(diag + 1); RTA_OK(a, length); a = RTA_NEXT(a, length)) { if (a->rta_type != INET_DIAG_INFO) continue; diff --git a/core/src/platform/linux_power.cpp b/core/src/platform/linux_power.cpp index 4169af6..8bb1f4a 100644 --- a/core/src/platform/linux_power.cpp +++ b/core/src/platform/linux_power.cpp @@ -27,30 +27,21 @@ struct Sensors { const Sensors &sensors() { static const Sensors found = [] { Sensors s; - std::vector fallback; // ACPI thermal zones when no CPU driver is loaded + std::vector inputs; for (const auto &h : list_dir("/sys/class/hwmon")) { const std::string dir = "/sys/class/hwmon/" + h; const std::string name = read_line(dir + "/name"); for (const auto &file : list_dir(dir)) { - if (!starts_with(file, "temp") || file.size() < 12 || file.compare(file.size() - 6, 6, "_input") != 0) + // "temp1_input": at least "temp", a digit and "_input". + if (!starts_with(file, "temp") || file.size() < 11 || file.compare(file.size() - 6, 6, "_input") != 0) continue; - const std::string input = dir + "/" + file; const std::string label = read_line(dir + "/" + file.substr(0, file.size() - 6) + "_label"); - if (name == "coretemp") { - // "Package id 0" covers the whole die; per-core sensors only when it is missing. - if (starts_with(label, "Package")) s.cpu.insert(s.cpu.begin(), input); - } else if (name == "k10temp" || name == "zenpower") { - if (label == "Tctl" || label == "Tdie") s.cpu.push_back(input); - } else if (name == "cpu_thermal" || name == "soc_thermal") { - s.cpu.push_back(input); - } else if (name == "acpitz") { - fallback.push_back(input); - } else if (name == "nvme" || name == "drivetemp") { - if (label.empty() || label == "Composite") s.disk.push_back(input); - } + inputs.push_back({name, label, dir + "/" + file}); + if ((name == "nvme" || name == "drivetemp") && (label.empty() || label == "Composite")) + s.disk.push_back(dir + "/" + file); } } - if (s.cpu.empty()) s.cpu = fallback; + s.cpu = cpu_sensor_inputs(inputs); return s; }(); return found; @@ -150,7 +141,9 @@ bool battery(pc_battery &out) { out.level = capacity >= 0 ? std::min(capacity, 100) / 100.0 : full_wh > 0 && now_wh >= 0 ? now_wh / full_wh : 0; - if (full_wh > 0 && design_wh > 0) out.health = std::min(full_wh / design_wh, 1.5); + // Maximum capacity relative to new, capped at 100% like macOS and Windows (a fresh battery may + // report a little over its design capacity). + if (full_wh > 0 && design_wh > 0) out.health = std::min(full_wh / design_wh, 1.0); if (watts > 0) { const bool discharging = status == "Discharging"; out.power_watts = discharging ? -watts : watts; @@ -162,11 +155,49 @@ bool battery(pc_battery &out) { if (cycles > 0) out.cycle_count = static_cast(cycles); // 0 means "not reported" const int64_t temp = read_int(dir + "/temp", -1); // tenths of a degree, rarely present if (temp > 0 && temp < 1000) out.temperature = temp / 10.0; - const std::string health = read_line(dir + "/health"); - if (!health.empty() && health != "Unknown") copy_string(out.condition, sizeof(out.condition), health); + copy_string(out.condition, sizeof(out.condition), battery_condition(read_line(dir + "/health"), out.health)); return true; } +// The CPU die sensors among the hwmon inputs, best first: coretemp's package sensor (its per-core +// sensors only where the package one is missing), k10temp/zenpower's Tdie (Tctl only without it: +// on Zen and Zen+ Tctl carries a 10-20 °C control offset), ARM SoC zones; ACPI zones as the last resort. +std::vector cpu_sensor_inputs(const std::vector &inputs) { + std::vector package, cores, tdie, tctl, soc, acpi; + for (const HwmonInput &i : inputs) { + if (i.driver == "coretemp") { + if (starts_with(i.label, "Package")) + package.push_back(i.input); + else if (starts_with(i.label, "Core")) + cores.push_back(i.input); + } else if (i.driver == "k10temp" || i.driver == "zenpower") { + if (i.label == "Tdie") tdie.push_back(i.input); + if (i.label == "Tctl") tctl.push_back(i.input); + } else if (i.driver == "cpu_thermal" || i.driver == "soc_thermal") { + soc.push_back(i.input); + } else if (i.driver == "acpitz") { + acpi.push_back(i.input); + } + } + std::vector result = package.empty() ? cores : package; + const std::vector &amd = tdie.empty() ? tctl : tdie; + result.insert(result.end(), amd.begin(), amd.end()); + result.insert(result.end(), soc.begin(), soc.end()); + return result.empty() ? acpi : result; +} + +// The battery's condition in macOS's words: sysfs "Good" is "Normal", a failing battery +// "Service Recommended", other states (Overheat, Cold, …) as the kernel says them. Where the +// kernel doesn't know, the health decides, as on Windows (below 80% of design: service). +std::string battery_condition(const std::string &sysfs_health, double health) { + if (sysfs_health == "Good") return "Normal"; + if (sysfs_health == "Dead" || sysfs_health == "Unspecified failure" || sysfs_health == "Calibration required") + return "Service Recommended"; + if (!sysfs_health.empty() && sysfs_health != "Unknown") return sysfs_health; + if (health < 0) return {}; + return health >= 0.8 ? "Normal" : "Service Recommended"; +} + // busctl --json=short call … ListInhibitors: {"type":"a(ssssuu)","data":[[["what","who","why", // "mode",uid,pid],…]]}. A minimal reader for that one shape. Exposed for tests. std::vector parse_inhibitors(const std::string &json) { @@ -219,7 +250,9 @@ std::vector parse_inhibitors(const std::string &json) { PowerAssertion a; for (const auto &kind : split(what, ':')) { if (kind == "sleep") a.kind |= PC_ASSERT_SYSTEM_SLEEP; - if (kind == "idle") a.kind |= PC_ASSERT_DISPLAY_SLEEP; + // Keeping the display on keeps the machine awake too (and blocks idle suspend): both, + // as macOS and Windows report a display assertion. + if (kind == "idle") a.kind |= PC_ASSERT_DISPLAY_SLEEP | PC_ASSERT_SYSTEM_SLEEP; } if (a.kind == 0) continue; // shutdown, lid switch and power-key handling a.pid = static_cast(std::strtol(fields[5].c_str(), nullptr, 10)); @@ -341,7 +374,7 @@ std::vector session_inhibitors() { PowerAssertion a; // 4: suspend, 8: idle (the screen stays on). Logout and user-switch locks keep nothing awake. if (bits & 4) a.kind |= PC_ASSERT_SYSTEM_SLEEP; - if (bits & 8) a.kind |= PC_ASSERT_DISPLAY_SLEEP; + if (bits & 8) a.kind |= PC_ASSERT_DISPLAY_SLEEP | PC_ASSERT_SYSTEM_SLEEP; if (a.kind == 0) continue; const auto app = session_call(path, interface, "GetAppId"); const auto reason = session_call(path, interface, "GetReason"); diff --git a/core/src/platform/linux_services.cpp b/core/src/platform/linux_services.cpp index b59589d..5e87d29 100644 --- a/core/src/platform/linux_services.cpp +++ b/core/src/platform/linux_services.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -29,7 +30,11 @@ const std::string &systemctl() { std::vector systemctl_args(int32_t domain, std::initializer_list args) { std::vector argv{systemctl()}; - if (domain == PC_DOMAIN_USER) argv.emplace_back("--user"); + if (domain == PC_DOMAIN_USER) { + argv.emplace_back("--user"); + // The root copy (pkexec) manages the desktop user's manager, not root's. + if (acting_for_session_user()) argv.emplace_back("--machine=" + session_user_name() + "@.host"); + } argv.insert(argv.end(), args); return argv; } @@ -46,13 +51,6 @@ bool unit_enabled(const std::string &state) { return state != "disabled" && state != "masked" && state != "masked-runtime" && state != "bad" && !state.empty(); } -// Units the distribution ships (/usr/lib/systemd, /lib/systemd) are part of the OS; units in /etc -// and the user's ~/.config were added by an administrator, a package's postinst or the user. -bool os_unit(const std::string &fragment) { - return starts_with(fragment, "/usr/lib/systemd/") || starts_with(fragment, "/lib/systemd/") || - starts_with(fragment, "/usr/share/systemd/") || starts_with(fragment, "/run/systemd/generator"); -} - void add_services(std::vector &out, int32_t domain) { std::string text; std::set names; @@ -97,7 +95,7 @@ void add_services(std::vector &out, int32_t domain) { s.last_exit = static_cast(std::strtol(get("ExecMainStatus").c_str(), nullptr, 10)); const std::string state = get("UnitFileState"); s.enabled = state.empty() ? s.pid > 0 : unit_enabled(state); - s.apple = os_unit(get("FragmentPath")); + s.apple = systemd_os_unit(get("Id"), get("FragmentPath"), s.program); out.push_back(s); } } @@ -115,14 +113,12 @@ pc_result systemctl_result(int status, const std::string &err) { // ---- XDG autostart ---- -std::string home_directory() { - const char *home = std::getenv("HOME"); - return home ? home : ""; -} +std::string home_directory() { return session_home(); } std::string user_autostart_dir() { const char *config = std::getenv("XDG_CONFIG_HOME"); - return (config && *config ? std::string(config) : home_directory() + "/.config") + "/autostart"; + // XDG_CONFIG_HOME is the caller's own (pkexec passes it through only when set). + return (config && *config == '/' ? std::string(config) : home_directory() + "/.config") + "/autostart"; } std::vector system_autostart_dirs() { @@ -217,17 +213,68 @@ pc_result set_autostart(const std::string &file_id, bool enabled) { } if (!found) return PC_ERR_NOT_FOUND; if (enabled) return PC_OK; // only the system entry exists, and it isn't hidden by us - ::mkdir((home_directory() + "/.config").c_str(), 0700); - ::mkdir(user_autostart_dir().c_str(), 0700); + const std::string config = home_directory() + "/.config"; + if (::mkdir(config.c_str(), 0700) == 0) give_to_session_user(config); + if (::mkdir(user_autostart_dir().c_str(), 0700) == 0) give_to_session_user(user_autostart_dir()); } std::map keys{{"Hidden", enabled ? "false" : "true"}}; if (enabled && text.find("X-GNOME-Autostart-enabled=false") != std::string::npos) keys["X-GNOME-Autostart-enabled"] = "true"; - return write_atomically(user_path, set_desktop_keys(text, keys)) ? PC_OK : PC_ERR_PERMISSION; + if (!write_atomically(user_path, set_desktop_keys(text, keys))) return PC_ERR_PERMISSION; + give_to_session_user(user_path); + return PC_OK; +} + +// The pid of a startup entry's program, 0 when it isn't running. An interpreter (python3, sh) runs +// many scripts: which process is the entry's can't be told from its executable, so none is. +int32_t running_pid(const std::string &program, const std::unordered_map &by_path, + const std::unordered_map &by_name) { + if (program.empty()) return 0; + char resolved[PATH_MAX]; + const std::string real = ::realpath(program.c_str(), resolved) ? std::string(resolved) : program; + const std::string name = basename_of(real); + if (is_interpreter(name)) return 0; + if (auto it = by_path.find(real); it != by_path.end()) return it->second; + if (auto it = by_name.find(name); it != by_name.end()) return it->second; + return 0; } } // namespace +// "Part of the OS", the counterpart of Apple's own launchd jobs on macOS and the services under the +// Windows directory: a unit the distribution ships (unit file under /usr/lib/systemd and the like) +// that belongs to the system itself (systemd's own units and helpers, D-Bus, logins, the session's +// plumbing in /usr/libexec), not every daemon a package installed (docker, nginx, sshd, cups). +bool systemd_os_unit(const std::string &id, const std::string &fragment, const std::string &program) { + const bool shipped = starts_with(fragment, "/usr/lib/systemd/") || starts_with(fragment, "/lib/systemd/") || + starts_with(fragment, "/usr/share/systemd/") || + starts_with(fragment, "/run/systemd/generator"); + if (!shipped) return false; + for (const char *prefix : {"systemd-", + "dbus", + "getty@", + "serial-getty@", + "autovt@", + "user@", + "user-runtime-dir@", + "modprobe@", + "emergency.", + "rescue.", + "polkit", + "NetworkManager", + "display-manager", + "gdm", + "sddm", + "lightdm", + "accounts-daemon", + "udisks2", + "upower", + "wpa_supplicant"}) + if (starts_with(id, prefix)) return true; + return starts_with(program, "/usr/lib/systemd/") || starts_with(program, "/lib/systemd/") || + starts_with(program, "/usr/libexec/") || starts_with(program, "/usr/lib/polkit"); +} + std::vector> parse_systemctl_show(const std::string &text) { std::vector> units; std::map current; @@ -282,6 +329,16 @@ DesktopEntry parse_desktop_entry(const std::string &text) { bool valid_service_label(const std::string &label) { if (label.empty() || label.size() >= 256 || label[0] == '-') return false; + // Autostart entries are named after their .desktop file, which may hold spaces and UTF-8 + // ("My App.desktop"): any printable byte but '/' and a leading '.'. The file is opened under the + // autostart folders only, never passed to a program. + if (label.rfind("xdg:", 0) == 0) { + const std::string file = label.substr(4); + if (file.empty() || file[0] == '.') return false; + for (char c : file) + if (static_cast(c) < 0x20 || c == 0x7f || c == '/') return false; + return true; + } // Unit names: ASCII letters, digits, ":-_.\" and "@" for instances; "xdg:.desktop" for // autostart entries. Nothing reaches a shell, but a label is passed as one argument after "--". for (char c : label) @@ -366,14 +423,21 @@ std::vector startup_items() { } } - // Running instances: processes of this user whose program matches the entry's. - std::unordered_map running; - const uid_t me = ::getuid(); + // Running instances: processes of the session user whose executable is the entry's, by full + // path first (as Windows matches its startup items), by name second; the lowest pid of an app's + // processes, its first. /proc lists pids in no particular order. + std::unordered_map by_path, by_name; + const uid_t me = session_uid(); for (int32_t pid : list_pids()) { struct stat info{}; if (::stat(("/proc/" + std::to_string(pid)).c_str(), &info) != 0 || info.st_uid != me) continue; - const std::string exe = basename_of(read_link("/proc/" + std::to_string(pid) + "/exe")); - if (!exe.empty() && !running.count(exe)) running[exe] = pid; + const std::string exe = read_link("/proc/" + std::to_string(pid) + "/exe"); + if (exe.empty()) continue; + for (auto *map : {&by_path, &by_name}) { + const std::string key = map == &by_path ? exe : basename_of(exe); + auto [it, inserted] = map->emplace(key, pid); + if (!inserted) it->second = std::min(it->second, pid); + } } for (const auto &[file, found] : entries) { @@ -396,8 +460,7 @@ std::vector startup_items() { copy_string(item.program, sizeof(item.program), program); copy_string(item.config_path, sizeof(item.config_path), found.path); item.scope = found.scope; - auto pid = running.find(basename_of(program)); - item.pid = pid == running.end() ? 0 : pid->second; + item.pid = running_pid(program, by_path, by_name); item.enabled = !e.hidden && e.autostart_enabled; item.run_at_load = true; result.push_back(item); diff --git a/core/src/platform/windows.cpp b/core/src/platform/windows.cpp index 5ecd09e..fd7c7c0 100644 --- a/core/src/platform/windows.cpp +++ b/core/src/platform/windows.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -332,7 +333,8 @@ int32_t state_of(const ProcessEntry &entry) { bool all_suspended = true; for (ULONG i = 0; i < entry.NumberOfThreads; ++i) { const ThreadEntry &t = entry.Threads[i]; - if (t.ThreadState == kThreadRunning) return PC_STATE_RUNNING; + // Running, ready or standby: on a CPU or about to be, as thread_state reports a thread. + if (t.ThreadState == kThreadRunning || t.ThreadState == 1 || t.ThreadState == 3) return PC_STATE_RUNNING; if (!(t.ThreadState == kThreadWaiting && t.WaitReason == kWaitSuspended)) all_suspended = false; } return all_suspended ? PC_STATE_STOPPED : PC_STATE_SLEEPING; @@ -1023,7 +1025,10 @@ bool is_system_process(const RawProcess &process) { if (process.uid < kFirstRegularUser) return true; // SYSTEM and the service accounts // A process whose token we can't read belongs to another user or is protected: treat it // with the same care as a system one. - return process.uid == kUnknownUser; + if (process.uid == kUnknownUser) return true; + // The OS's own programs in the user's session (explorer, sihost, RuntimeBroker, ctfmon), like + // Finder and the Dock under /System on macOS: ending one needs confirmation. + return under_windows_directory(process.path); } int32_t self_pid() { return static_cast(GetCurrentProcessId()); } @@ -1108,14 +1113,17 @@ pc_result signal_process(int32_t pid, bool force) { return send_signal(pid, forc pc_result set_priority(int32_t pid, int32_t nice) { if (nice < -20 || nice > 20) return PC_ERR_INVALID; // Realtime is left out on purpose: it starves the system and needs a privilege anyway. + // Each class covers the nice values nearest the one nice_of reports for it (-15, -8, 0, 8, 15), so + // a value read back sets the same class, and macOS's steps (-10, -5, 0, 5, 10, 20) land on the + // class of the same name: High, Above normal, Normal, Below normal, Low. DWORD priority_class = NORMAL_PRIORITY_CLASS; - if (nice <= -11) + if (nice <= -10) priority_class = HIGH_PRIORITY_CLASS; else if (nice < 0) priority_class = ABOVE_NORMAL_PRIORITY_CLASS; else if (nice == 0) priority_class = NORMAL_PRIORITY_CLASS; - else if (nice <= 10) + else if (nice < 10) priority_class = BELOW_NORMAL_PRIORITY_CLASS; else priority_class = IDLE_PRIORITY_CLASS; @@ -1300,7 +1308,20 @@ std::string thread_name(DWORD thread_id) { return name; } +// Each thread's CPU time at the previous details read, by thread id and creation time (ids are +// reused): the next read turns the difference into a recent CPU share, as on macOS and Linux. +struct ThreadSample { + int64_t created = 0; + uint64_t cpu_ns = 0; + double at = 0; +}; +std::mutex thread_mutex; +std::unordered_map thread_samples; + void read_threads(int32_t pid, Details &out) { + using namespace std::chrono; + const double now = duration(steady_clock::now().time_since_epoch()).count(); + std::lock_guard lock(thread_mutex); std::vector buffer; if (!query_system(kSystemProcessInformation, buffer)) return; for (const ProcessEntry *entry : process_entries(buffer)) { @@ -1313,10 +1334,18 @@ void read_threads(int32_t pid, Details &out) { thread.cpu_percent = -1; thread.user_time_ns = static_cast(t.UserTime.QuadPart) * 100; thread.system_time_ns = static_cast(t.KernelTime.QuadPart) * 100; + const uint64_t cpu = thread.user_time_ns + thread.system_time_ns; + const auto previous = thread_samples.find(thread.id); + if (previous != thread_samples.end() && previous->second.created == t.CreateTime.QuadPart && + now > previous->second.at && cpu >= previous->second.cpu_ns) + thread.cpu_percent = + static_cast(cpu - previous->second.cpu_ns) / 1e7 / (now - previous->second.at); + thread_samples[thread.id] = {t.CreateTime.QuadPart, cpu, now}; thread.priority = t.Priority; thread.state = thread_state(t); out.threads.push_back(std::move(thread)); } + if (thread_samples.size() > 20000) thread_samples.clear(); out.threads_known = true; return; } diff --git a/core/src/platform/windows_power.cpp b/core/src/platform/windows_power.cpp index 485ce7e..f1dda9f 100644 --- a/core/src/platform/windows_power.cpp +++ b/core/src/platform/windows_power.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #pragma comment(lib, "ole32.lib") #pragma comment(lib, "oleaut32.lib") @@ -285,19 +286,34 @@ double nvme_smart_temperature(HANDLE disk) { return celsius > -40 && celsius < 150 ? celsius : -1; } -// The first physical drive's temperature from the storage stack (NVMe; SATA drives only when their -// driver answers the temperature property, since SMART pass-through needs an administrator). +// The hottest physical drive's temperature from the storage stack (NVMe; SATA drives only when +// their driver answers the temperature property, since SMART pass-through needs an administrator), +// as macOS reports its hottest NAND sensor and Linux its hottest drive. The drives that answer are +// found once; later reads open only those. double drive_temperature() { - for (int drive = 0; drive < 4; ++drive) { + static const std::vector drives = [] { + std::vector found; + for (int drive = 0; drive < 8; ++drive) { + wchar_t path[32]; + (void)swprintf_s(path, L"\\\\.\\PhysicalDrive%d", drive); + Handle disk(CreateFileW(path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr)); + if (!disk) continue; + if (drive_property_temperature(disk.get()) >= 0 || nvme_smart_temperature(disk.get()) >= 0) + found.push_back(drive); + } + return found; + }(); + double hottest = -1; + for (int drive : drives) { wchar_t path[32]; (void)swprintf_s(path, L"\\\\.\\PhysicalDrive%d", drive); Handle disk(CreateFileW(path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr)); if (!disk) continue; double celsius = drive_property_temperature(disk.get()); if (celsius < 0) celsius = nvme_smart_temperature(disk.get()); - if (celsius >= 0) return celsius; + hottest = std::max(hottest, celsius); } - return -1; + return hottest; } // Performance counters first; WMI only when the counter set is missing altogether (it is the same @@ -567,12 +583,7 @@ std::vector power_assertions() { const std::string report = run_hidden(std::wstring(L"\"") + system32 + L"\\powercfg.exe\" /requests", 5000); if (report.empty()) return {}; std::vector result = parse_power_requests(report); - const int64_t now = filetime_to_unix([] { - FILETIME ft{}; - GetSystemTimeAsFileTime(&ft); - return filetime_value(ft); - }()); - for (PowerAssertion &a : result) a.created = now; // powercfg doesn't say when it was taken + // powercfg doesn't say when a request was taken: created stays 0 ("unknown", procyon.h), as on Linux. return result; } diff --git a/core/src/platform/windows_services.cpp b/core/src/platform/windows_services.cpp index 564c200..4808ae4 100644 --- a/core/src/platform/windows_services.cpp +++ b/core/src/platform/windows_services.cpp @@ -118,8 +118,8 @@ void run_key_items(const RunSource &source, std::vector &out) { if (display.empty() || GetFileAttributesW(wide(executable).c_str()) == INVALID_FILE_ATTRIBUTES) display = utf8(value_name); copy_string(item.name, sizeof(item.name), display); - copy_string(item.program, sizeof(item.program), command); - copy_string(item.app_path, sizeof(item.app_path), executable); + // program is the executable (procyon.h), as on macOS and Linux; app_path is for app bundles. + copy_string(item.program, sizeof(item.program), executable.empty() ? command : executable); copy_string(item.config_path, sizeof(item.config_path), std::string(source.root == HKEY_CURRENT_USER ? "HKCU\\" : "HKLM\\") + utf8(source.key) + (source.view == KEY_WOW64_32KEY ? " (32-bit)" : "")); @@ -190,7 +190,6 @@ void folder_items(const std::string &folder, HKEY root, const char *tag, int32_t if (const auto dot = display.find_last_of('.'); dot != std::string::npos && dot > 0) display.resize(dot); copy_string(item.name, sizeof(item.name), display); copy_string(item.program, sizeof(item.program), target); - copy_string(item.app_path, sizeof(item.app_path), target); copy_string(item.config_path, sizeof(item.config_path), full); item.scope = scope; item.pid = target.empty() ? 0 : pid_of_executable(target); @@ -372,8 +371,7 @@ void add_task(IRegisteredTask *task, std::vector &out) { std::string display = executable.empty() ? std::string() : product_name(executable); if (display.empty() || GetFileAttributesW(wide(executable).c_str()) == INVALID_FILE_ATTRIBUTES) display = task_name; copy_string(item.name, sizeof(item.name), display); - copy_string(item.program, sizeof(item.program), command); - copy_string(item.app_path, sizeof(item.app_path), executable); + copy_string(item.program, sizeof(item.program), executable.empty() ? command : executable); copy_string(item.config_path, sizeof(item.config_path), "Task Scheduler " + task_path); item.scope = scope; item.pid = executable.empty() ? 0 : pid_of_executable(executable); @@ -594,8 +592,9 @@ std::vector services() { service.enabled = cfg->dwStartType != SERVICE_DISABLED; if (cfg->lpBinaryPathName) { const std::string command = utf8(cfg->lpBinaryPathName, wcslen(cfg->lpBinaryPathName)); - copy_string(service.program, sizeof(service.program), command); - service.apple = under_windows_directory(executable_of_command(command)); + const std::string executable = executable_of_command(command); + copy_string(service.program, sizeof(service.program), executable.empty() ? command : executable); + service.apple = under_windows_directory(executable); } } result.push_back(service); diff --git a/core/tests/core_tests.cpp b/core/tests/core_tests.cpp index 0a69925..df7500f 100644 --- a/core/tests/core_tests.cpp +++ b/core/tests/core_tests.cpp @@ -28,6 +28,10 @@ #include "helper_protocol.hpp" #if defined(__linux__) +#include + +#include + #include "platform/linux_internal.hpp" #endif #include "monitor.hpp" @@ -386,7 +390,7 @@ void inhibitor_parsing() { check(locks.size() == 2 && locks[0].pid == 4242 && locks[0].kind == PC_ASSERT_SYSTEM_SLEEP && locks[0].reason == "Firefox · Playing video", "sleep lock"); - check(locks.size() == 2 && locks[1].kind == PC_ASSERT_DISPLAY_SLEEP && + check(locks.size() == 2 && locks[1].kind == (PC_ASSERT_DISPLAY_SLEEP | PC_ASSERT_SYSTEM_SLEEP) && locks[1].reason == "GNOME Videos · Playing \"Movie\"", "idle lock keeps the display on, escapes read"); check(platform::parse_inhibitors("").empty() && platform::parse_inhibitors("{\"data\":[[]]}").empty(), "no locks"); @@ -400,6 +404,39 @@ void inhibitor_parsing() { "an empty string is still a value"); } +// Suspend and resume through the native signal numbers (SIGSTOP 19 and SIGCONT 18 on Linux, not +// macOS's 17 and 19): a child stops and continues. +// The machine's memory parts partition its total (the composition bar's proportions rely on it). +void memory_partition() { + platform::Memory m; + check(platform::memory(m), "memory read"); + const uint64_t parts = m.app + m.wired + m.compressed + m.cached + m.free; + check(parts <= m.total && m.total - parts <= m.total / 100, "memory parts add up to the total"); +} + +void native_signals() { + const pid_t child = ::fork(); + if (child == 0) { + ::pause(); + ::_exit(0); + } + check(child > 0, "child started"); + if (child <= 0) return; + const auto state = [child] { + platform::linux_internal::ProcStat stat; + for (int i = 0; i < 100; ++i) { + if (platform::linux_internal::read_stat(child, stat) && stat.state != 'S' && stat.state != 'R') + return stat.state; + ::usleep(10000); + } + return platform::linux_internal::read_stat(child, stat) ? stat.state : '?'; + }; + check(platform::send_signal(child, SIGSTOP) == PC_OK && state() == 'T', "SIGSTOP stops"); + check(platform::send_signal(child, SIGCONT) == PC_OK, "SIGCONT continues"); + (void)::kill(child, SIGKILL); + (void)::waitpid(child, nullptr, 0); +} + void systemd_parsing() { const auto units = platform::parse_systemctl_show( "Id=ssh.service\nDescription=OpenBSD Secure Shell server\nMainPID=812\nExecStart={ path=/usr/sbin/sshd ; " @@ -419,6 +456,47 @@ void systemd_parsing() { platform::valid_service_label("xdg:org.gnome.Foo.desktop") && platform::valid_service_label("dev-disk-by\\x2duuid.swap"), "unit and autostart labels accepted"); + check(platform::valid_service_label("xdg:My App.desktop") && platform::valid_service_label("xdg:\xc3\x9c" + "bersicht.desktop"), + "autostart labels with spaces and UTF-8 accepted"); + check(!platform::valid_service_label("xdg:../x.desktop") && !platform::valid_service_label("xdg:a/b.desktop") && + !platform::valid_service_label("xdg:") && !platform::valid_service_label("xdg:a\nb.desktop") && + !platform::valid_service_label("my unit.service"), + "autostart labels with a path, control byte or nothing rejected; units keep their rule"); + + using platform::HwmonInput; + const auto cpu = [](std::vector inputs) { return platform::cpu_sensor_inputs(inputs); }; + check(cpu({{"coretemp", "Core 0", "c0"}, {"coretemp", "Package id 0", "p"}, {"acpitz", "", "a"}}) == + std::vector{"p"}, + "coretemp package sensor preferred"); + check(cpu({{"coretemp", "Core 0", "c0"}, {"coretemp", "Core 1", "c1"}, {"acpitz", "", "a"}}) == + std::vector{"c0", "c1"}, + "coretemp cores without a package sensor, not ACPI"); + check(cpu({{"k10temp", "Tctl", "tctl"}, {"k10temp", "Tdie", "tdie"}}) == std::vector{"tdie"}, + "k10temp Tdie preferred over the offset Tctl"); + check(cpu({{"k10temp", "Tctl", "tctl"}}) == std::vector{"tctl"}, "k10temp Tctl alone"); + check(cpu({{"acpitz", "", "a"}, {"nvme", "Composite", "n"}}) == std::vector{"a"}, + "ACPI zone as the last resort"); + check(platform::battery_condition("Good", 0.5) == "Normal" && + platform::battery_condition("Dead", 1) == "Service Recommended" && + platform::battery_condition("Overheat", 1) == "Overheat" && + platform::battery_condition("Unknown", 0.79) == "Service Recommended" && + platform::battery_condition("", 0.9) == "Normal" && platform::battery_condition("", -1).empty(), + "battery condition in macOS's words"); + check(platform::linux_internal::arch_name("aarch64") == "arm64" && + platform::linux_internal::arch_name("i686") == "x86" && + platform::linux_internal::arch_name("x86_64") == "x86_64", + "architecture names as procyon.h spells them"); + check(platform::systemd_os_unit("systemd-journald.service", "/usr/lib/systemd/system/systemd-journald.service", + "/usr/lib/systemd/systemd-journald") && + platform::systemd_os_unit("accounts-daemon.service", "/usr/lib/systemd/system/accounts-daemon.service", + "/usr/libexec/accounts-daemon"), + "systemd's and the session's own units are part of the OS"); + check(!platform::systemd_os_unit("docker.service", "/usr/lib/systemd/system/docker.service", "/usr/bin/dockerd") && + !platform::systemd_os_unit("nginx.service", "/lib/systemd/system/nginx.service", "/usr/sbin/nginx") && + !platform::systemd_os_unit("systemd-custom.service", "/etc/systemd/system/systemd-custom.service", + "/usr/lib/systemd/x"), + "packaged daemons and administrators' units are third-party"); } #endif // __linux__ @@ -677,6 +755,8 @@ int main() { drm_fdinfo_parsing(); inhibitor_parsing(); systemd_parsing(); + native_signals(); + memory_partition(); #endif tick_wrap(); handle_denial(); diff --git a/docs/development.md b/docs/development.md index 71416f5..07c2c58 100644 --- a/docs/development.md +++ b/docs/development.md @@ -85,6 +85,8 @@ scripts/ build-macos-app.sh builds dist/Procyon.app build-windows.cmd builds build\windows (core, CLI, tests, app) and dist\windows\Procyon.exe build-linux.sh builds build/linux (core, CLI, tests, app) and dist/linux/procyon + bench-linux.py measures dist/linux/procyon against the spec's targets from /proc (bench-windows.py's twin) + screenshots-windows.ps1 renders the main screens with Procyon.exe --screenshot (make screenshots on Windows) package-linux.sh dist/Procyon--linux-.tar.gz (cmake --install into a staging prefix) make-icon.swift renders the app icon; make-icon-windows.ps1 converts it to Procyon.ico ``` @@ -111,6 +113,7 @@ make run rem release build, dist\windows\Procyon.exe, open it make test rem release build + core tests (make core is the same) make build rem debug build into build\windows-debug make bench rem measure every screen and the tray state against the spec's targets (scripts\bench-windows.py) +make screenshots rem render the main screens, light and dark, into dist\windows\screenshots make lint rem clang-format --dry-run, generated files and python checks (the last two need python) make format rem clang-format in place make ci rem lint + test + app, what the Windows CI job runs @@ -120,7 +123,11 @@ make help rem everything else Underneath, `scripts\build-windows.cmd [release|debug] [--no-tests]` finds Visual Studio through `vswhere`, runs `vcvars64.bat`, puts `build\tools` first on PATH, then falls back to the CMake and Ninja of the *C++ CMake tools* component or PATH. Everything builds from `core/CMakeLists.txt`, which adds `apps/windows` on Windows. Headless: -`build\windows\procyon-cli.exe 3 1000`; a screen at launch: `dist\windows\Procyon.exe --page processes`. +`build\windows\procyon-cli.exe 3 1000`; a screen at launch: `dist\windows\Procyon.exe --page processes`; a screen +as a PNG without showing a window: `dist\windows\Procyon.exe --screenshot out.png --page cpu --dark` (the window's +pixel size, after six samples; exit status 1 when the file can't be written); `Procyon.exe --version` prints the +version to the console it was started from. A second launch brings the running Procyon up instead of starting +another (a `Local\Procyon.Instance` mutex; `--no-settings` and `--screenshot` runs stay separate). `scripts\lint-windows.ps1` and `scripts\format-windows.ps1` are the Windows counterparts of `lint.sh`/`format.sh` (no Swift, no clang-tidy, no shellcheck); `scripts\tools-windows.ps1` fetches the pinned tool versions. @@ -142,6 +149,7 @@ make run # release build, dist/linux/procyon, open it make test # release build + core tests (make core is the same) make build # debug build into build/linux-debug make screenshots # render the main screens, light and dark, into dist/linux/screenshots +make bench # measure every screen and the background state against the spec's targets (needs a display) make install # cmake --install into PREFIX (default ~/.local) make package # dist/Procyon--linux-.tar.gz + .sha256 make lint # generated files, clang-format, clang-tidy (SKIP_TIDY=1 skips it), shellcheck, python @@ -150,7 +158,16 @@ make help # everything else Headless: `build/linux/procyon-cli 3 1000`; a screen at launch: `dist/linux/procyon --page processes`; any screen as a PNG without opening a window: `dist/linux/procyon --screenshot out.png --page cpu --dark` (2x, after six -samples; it needs a display, `xvfb-run -a` provides one in CI). +samples; it needs a display, `xvfb-run -a` provides one in CI; exit status 1 when the file can't be written). +`--background` starts without a window, as when it was closed (the macOS app's `-launchInMenuBar`). + +`scripts/bench-linux.py` is the counterpart of `bench-windows.py`, without a probe binary: it launches +`dist/linux/procyon --no-settings --page ` with `PROCYON_BENCH=1` (the app then prints a line when it draws its +first frame, which times startup), samples CPU time from `/proc//stat` and private memory (`RssAnon`) once a +second, and measures `background` with `--background`. The CLI's numbers are compared with `/proc/stat`, +`/proc/meminfo` and the process list. Output: `dist/bench-linux.json`. The same options as the Windows script, plus +`--renderer`: on Xvfb, which has no GPU, GTK's GL renderer runs on Mesa's llvmpipe, whose buffers count as the app's +private memory (110-180 MB against about 35 MB of Procyon's own), so CI measures with `--renderer cairo`. ## Development @@ -168,8 +185,9 @@ Tools: Xcode 27 provides `swift format`; `brew install clang-format llvm shellch ### CI/CD (GitHub Actions) - **`ci.yml`** runs on every push to `main` and every PR. Every OS has the same two kinds of job, all started at - once: **` · Lint, build & test`** (the quick answer, 2–5 minutes) and, on macOS and Windows, - **` · Performance (K/3)`**, the spec's targets measured by `scripts/bench-macos.py` / `bench-windows.py` + once: **` · Lint, build & test`** (the quick answer, 2–5 minutes) and + **` · Performance (K/3)`**, the spec's targets measured by `scripts/bench-macos.py` / `bench-windows.py` / + `bench-linux.py` with the screens split across three runners (`--shard K/3`, each builds the release app itself, so none waits for another; shard 1 also measures startup, installer size and accuracy). Measuring every screen on one runner took 7–11 minutes and was most of the run; split, the run takes about as long as one shard plus a build. @@ -178,12 +196,13 @@ Tools: Xcode 27 provides `swift format`; `brew install clang-format llvm shellch shards upload `dist/bench-K.json`. - Windows (`windows-latest`): `scripts\lint-windows.ps1` (after `scripts\tools-windows.ps1` fetched clang-format 19.1.0; the runner's Python checks the generated token header), `scripts\build-windows.cmd` - (core tests included), a `procyon-cli.exe` smoke run, `Procyon.exe` uploaded; the performance shards upload - `dist\bench-windows-K.json`. + (core tests included), a `procyon-cli.exe` smoke run, the Overview rendered with `--screenshot`, `Procyon.exe` + and the PNG uploaded; the performance shards upload `dist\bench-windows-K.json`. - Linux (`ubuntu-24.04`, the oldest supported base, so the binary's glibc and GTK requirements stay low): `SKIP_TIDY=1 scripts/lint.sh` with clang-format 19.1.0 from pipx, `scripts/build-linux.sh release` (core tests included), a `procyon-cli` smoke run, the Overview rendered offscreen under `xvfb-run` with `--screenshot`, the - binary and the PNG uploaded. No performance job yet (no `bench-linux.py`). + binary and the PNG uploaded; the performance shards run `bench-linux.py` under `xvfb-run` and upload + `dist/bench-linux-K.json`. - **`release.yml`** runs on tags `v*`, or manually: tests, universal (arm64 + x86_64) build, DMG + zip + SHA-256, GitHub release (versions with `-` are marked prerelease). With the secrets `MACOS_CERTIFICATE_P12`, `MACOS_CERTIFICATE_PASSWORD`, `APPLE_ID`, `APPLE_TEAM_ID` and `APPLE_APP_PASSWORD`, it signs with Developer ID @@ -342,7 +361,7 @@ in for the macOS open panel in **Who Is Using…**. | Spec item | Status | | --- | --- | -| Process list: name, PID, user, CPU, RAM, disk I/O, network | Done. `NtQuerySystemInformation` gives every process's counters without privileges, so nothing is `PC_PROC_RESTRICTED`; the path, user and "critical process" flag come from a limited-rights handle, which an unelevated Procyon cannot open for the OS's own processes (csrss, services, lsass, …): their user shows as unknown ("—") until Full Access. Memory is the private working set, like Task Manager. Per-process network comes from the `Microsoft-Windows-Kernel-Network` ETW provider in a real-time session of Procyon's own (`windows_network.cpp`): starting a session takes administrator rights, so `PC_CAP_PROCESS_NETWORK` and the network columns are on only with Full Access. | +| Process list: name, PID, user, CPU, RAM, disk I/O, network | Done. `NtQuerySystemInformation` gives every process's counters without privileges, so nothing is `PC_PROC_RESTRICTED`; the path, user and "critical process" flag come from a limited-rights handle, which an unelevated Procyon cannot open for the OS's own processes (csrss, services, lsass, …): their user shows as unknown ("—") until Full Access. Memory is the private working set, like Task Manager. Per-process network comes from the `Microsoft-Windows-Kernel-Network` ETW provider in a real-time session of Procyon's own (`windows_network.cpp`): starting a session takes administrator rights, so `PC_CAP_PROCESS_NETWORK` and the network columns are on only with Full Access, and the Network screen offers **Unlock Full Access** in their place. Programs under the Windows directory running in the user's session (explorer, sihost, RuntimeBroker) are `PC_PROC_SYSTEM`, like Finder and the Dock on macOS: ending one asks first. | | Flat / by app / tree views, search, sort, pin | Done (core). Apps are grouped by executable path; the app name is the executable's `FileDescription` ("Google Chrome"), what Task Manager shows. What lives under the Windows directory (svchost, dwm, …) is the OS, not an app: it groups by name, like the daemons of /System on macOS, and is not `PC_PROC_APP_BUNDLE`. **Pin to Top** keeps one app above the sorted rows in every view, as on macOS; a "top apps" row on Overview or a performance screen opens Processes on that app (by-app view, search cleared, the app pinned and selected), like the macOS `showInProcesses`. | | End task / force quit / end process tree | Done. End Task posts `WM_CLOSE` to a process's visible windows and terminates a process that has none; Force Quit and End Process Tree terminate. The idle process, `System`, processes flagged critical (`ProcessBreakOnTermination`) and, since that flag needs a handle an unelevated Procyon cannot get, the OS's own smss, csrss, wininit, winlogon, services, lsass, LsaIso, Registry, Memory Compression and Secure System by name are protected. End Process Tree follows the kernel's parent links only where the parent is older than the child: a reused parent pid adopts no strangers (macOS reparents orphans to launchd, so its tree never had this hole). | | Live charts, per-core usage, system info | Done. Hybrid cores (P/E) from `GetSystemCpuSetInformation`. | @@ -353,7 +372,7 @@ in for the macOS open panel in **Who Is Using…**. | Process details: path, command line, environment, threads | Done: command line through `ProcessCommandLineInformation` (works for every bitness), working directory and environment from the PEB of 64-bit processes, threads from the system process table with names from `GetThreadDescription`. Other users' processes need administrator rights. | | Startup apps with impact, enable/disable | Done for the Run keys (user, machine, 32-bit) and both Startup folders, with the enabled state Task Manager keeps under `StartupApproved`; entries are named after their executable's `FileDescription` ("Microsoft Edge"), not the registry value. Task Scheduler tasks with a logon or boot trigger outside `\Microsoft` (the OS's own) are listed too, through the Task Scheduler COM API, with their `Enabled` flag switched from the Startup screen; their label is `task:` plus the task path with `|` for `\`. | | Services: start/stop/restart, enable/disable | Done through the Service Control Manager. Disable remembers the start type (Automatic, Manual) under `HKCU\Software\Procyon\ServiceStartTypes` and Enable puts it back (Automatic when nothing was remembered), the way `launchctl enable` restores a job's definition. "Part of the OS" means the binary lives under the Windows directory. | -| Command palette, tray icon | Done: `Ctrl+K`; closing or minimizing the window keeps Procyon in the notification area (per-process sampling is skipped meanwhile, unless an alert rule watches apps; the Direct2D/DirectWrite stack and the embedded fonts are released and the working set trimmed, so the private working set in the tray is a few MB, well under the spec's 30 MB, and recreated when the window opens again), the tooltip shows the modules switched on in Settings (CPU, memory, network, GPU, like the macOS menu bar modules). Settings is the macOS form (at most 720 wide): Updates, Full access with its status and explanation, Notification area, Alerts (an enabled rule unfolds its threshold and duration), Appearance, Processes (default view), About with links. System has the hero card, Hardware and Software side by side, Kernel and Volumes. | +| Command palette, tray icon | Done: `Ctrl+K` (again to close it); an app's row opens its actions (End Task, Force Quit, Suspend, Set Priority, Get Info, Show in Processes, Open File Location, Copy Path, Copy PID), as on macOS; every word of the query must match. `Ctrl+Q` quits. The icon stays in the notification area while the window is open too (alerts are its notifications; clicking one opens the window), and is added again when Explorer restarts. Closing or minimizing the window (also with the drawn minimize button) keeps Procyon in the notification area (per-process sampling is skipped meanwhile, unless an alert rule watches apps; the Direct2D/DirectWrite stack and the embedded fonts are released and the working set trimmed, so the private working set in the tray is a few MB, well under the spec's 30 MB, and recreated when the window opens again), the tooltip shows the modules switched on in Settings (CPU, memory, network, GPU, like the macOS menu bar modules). Settings is the macOS form (at most 720 wide): Updates, Full access with its status and explanation, Notification area, Alerts (an enabled rule unfolds its threshold and duration), Appearance, Processes (default view), About with links. System has the hero card, Hardware and Software side by side, Kernel and Volumes. | | Battery | Done: level and times from `GetSystemPowerStatus`, capacity, cycles, rate and temperature from the battery class driver. Apps preventing sleep are read from `powercfg /requests` (run hidden, 5 s timeout; the kernel's `GetPowerRequestList` has no public layout and answers STATUS_INVALID_PARAMETER on Windows 11 25H2), parsed by section order (Display, System, Away mode, Execution, …) so localized headers don't matter; `[PROCESS]` entries are mapped from their NT path to a running pid, `[DRIVER]` entries carry the device description. powercfg needs administrator rights, so the list is empty without Full Access. | | Temperatures | ACPI thermal zones through the `Thermal Zone Information` performance counters (readable by every user; `MSAcpi_ThermalZoneTemperature` over WMI is the fallback, but it refuses non-administrators on most machines). Those are the firmware's zones, not the CPU die: die temperature is only reachable through a signed kernel driver reading MSRs. Many desktop boards publish a zone with a fixed placeholder (27.8 °C is common) and nothing behind it: a zone that has moved is preferred, and when none has, the CPU screen shows the board's reading labelled "Board zone (fixed reading)" rather than hiding the panel. The first physical drive through `IOCTL_STORAGE_QUERY_PROPERTY`: the generic temperature property, then the NVMe SMART / Health Information log page (the inbox NVMe driver rejects the generic property but serves the log page to any user). SATA SMART needs an administrator and is not read. Fans: not yet. | | Files & Ports | Done: listening ports, connections and **Who Is Using…** from the system handle table (named pipes are skipped before `NtQueryObject`, which would block on them); working directories are read from each process's PEB alone. IPv4 peers of dual-stack sockets (`::ffff:a.b.c.d` in the IPv6 table) are reported as IPv4, like macOS. Other users' processes need administrator rights. | @@ -426,7 +445,7 @@ instance per session). | Spec item | Status | | --- | --- | -| Process list: name, PID, user, CPU, RAM, disk I/O, network | Done except network. `/proc//stat` and `statm` are public, so CPU and memory are known for every process and nothing is `PC_PROC_RESTRICTED`; memory is resident minus shared pages (what the process holds itself). Disk I/O (`/proc//io`, bytes that reached the block layer) and the executable path are the owner's only: other users' processes show "—" until Full Access, and their path falls back to an absolute `argv[0]`. Kernel threads are left out, like `kernel_task`'s threads on macOS. Per-process network (`linux_network.cpp`) sums the kernel's TCP byte counters per socket (`sock_diag` netlink, `tcp_info.tcpi_bytes_received`/`tcpi_bytes_acked`, unprivileged), matched to processes by socket inode from `/proc//fd`, so only readable processes are counted (every process as root); loopback-only sockets are skipped, like `lo` in the machine totals. A dump walks the kernel's whole TCP hash (262,144 buckets on a 32 GB machine, about 4 ms per family), so it runs every 3 s and finds new sockets; in between each known socket is looked up by its id (a hash lookup, 128 per netlink send). A socket counts from the tick it is first seen (its earlier bytes would land in one tick as a rate it never had), and per-process totals add per-socket deltas, so a closing socket never makes a total run backwards. UDP has no per-socket counters: QUIC traffic isn't attributed, which the Network screen says under its top apps. | +| Process list: name, PID, user, CPU, RAM, disk I/O, network | Done except network. `/proc//stat` and `statm` are public, so CPU and memory are known for every process and nothing is `PC_PROC_RESTRICTED`; memory is resident minus shared pages (what the process holds itself). Disk I/O (`/proc//io`, bytes that reached the block layer) and the executable path are the owner's only: other users' processes show "—" until Full Access, and their path falls back to an absolute `argv[0]`. Kernel threads are left out, like `kernel_task`'s threads on macOS. Per-process network (`linux_network.cpp`) sums the kernel's TCP byte counters per socket (`sock_diag` netlink, `tcp_info.tcpi_bytes_received`/`tcpi_bytes_acked`, unprivileged), matched to processes by socket inode from `/proc//fd`, so only readable processes are counted (every process as root); loopback sockets count, as on macOS and Windows (the machine totals still skip `lo`). A dump walks the kernel's whole TCP hash (262,144 buckets on a 32 GB machine, about 4 ms per family), so it runs every 3 s and finds new sockets; in between each known socket is looked up by its id (a hash lookup, 128 per netlink send). A socket counts from the tick it is first seen (its earlier bytes would land in one tick as a rate it never had), and per-process totals add per-socket deltas, so a closing socket never makes a total run backwards. UDP has no per-socket counters: QUIC traffic isn't attributed, which the Network screen says under its top apps. | | Flat / by app / tree views | Done (core). An app is a `.desktop` entry: processes whose executable (or `StartupWMClass`, or the directory a launcher resolves into) matches an entry group under its name and are `PC_PROC_APP_BUNDLE`; everything else groups by name. | | End task / force quit / end process tree, suspend, signals | Done with POSIX signals. pid 1 (init), 2 (kthreadd) and Procyon are protected. | | Priority, CPU affinity | Done, applied to every thread (`/proc//task`), as `renice` and `taskset -a` do, since Linux schedules threads. Raising priority needs root. | @@ -436,9 +455,9 @@ instance per session). | GPU: usage, memory, temperature; per-process GPU | DRM cards in sysfs: `gpu_busy_percent` and VRAM on AMD, temperature from the card's hwmon, the name from `pci.ids`. Intel publishes busy time only through perf (root, or `perf_event_paranoid` ≤ 0); its GTs' idle residency is public (i915 `gt/gt*/rc6_residency_ms`, xe `tile*/gt*/gtidle/idle_residency_ms`), so utilization is the busiest GT's share of time out of RC6 since the previous sample: awake rather than busy, slightly high at light loads (7–8% against 5% of summed per-process engine time on the measuring machine). NVIDIA through NVML (`libnvidia-ml.so.1`, loaded when the driver is). Per-process GPU time from the DRM fdinfo engine counters (amdgpu, i915, nouveau, msm, panfrost, v3d; Linux 5.19+), the busiest engine kind per client, the descriptor list rescanned every 5 s; other users' processes are unreadable. | | Process details | Done: `cmdline`, `environ` (owner only), `cwd`, threads from `/proc//task` with recent CPU per thread. | | Startup apps | Done: XDG autostart (`~/.config/autostart`, `$XDG_CONFIG_DIRS/autostart`), filtered as GNOME's Startup Applications does (session components with `X-GNOME-Autostart-Phase`, other desktops' entries and hidden system entries are left out). Switching writes `Hidden=` into the user's copy, creating an override of a system entry when needed, so no root is needed. | -| Services | Done: every service unit of the system and user managers (`systemctl list-unit-files`, `list-units`, one `show` for all), aliases listed once; "part of the OS" means the unit file is under `/usr/lib/systemd`. Actions run `systemctl`, which asks polkit (the desktop's password dialog) for system units; a unit that doesn't exist is answered before polkit is asked. | +| Services | Done: every service unit of the system and user managers (`systemctl list-unit-files`, `list-units`, one `show` for all), aliases listed once; "part of the OS" (the counterpart of Apple's own jobs) means a unit the distribution ships under `/usr/lib/systemd` that belongs to the system itself: systemd's own units, D-Bus, logins and gettys, the session's plumbing (a program under `/usr/lib/systemd` or `/usr/libexec`, polkit, NetworkManager, display managers, udisks, upower). Packaged daemons such as docker, nginx, sshd and cups are third-party. Actions run `systemctl`, which asks polkit (the desktop's password dialog) for system units; a unit that doesn't exist is answered before polkit is asked. | | Files & Ports | Done: `/proc//fd` links and working directories; sockets from `/proc/net/{tcp,tcp6,udp,udp6}` matched to processes by inode. Other users' descriptors need root. | -| Battery, apps preventing sleep, temperatures | Battery from `/sys/class/power_supply` (energy or charge counters, health, cycles, adapter). Sleep: systemd-logind's `block` inhibitors (`busctl … ListInhibitors`) and GNOME's session inhibitors with the suspend or idle flag (`org.gnome.SessionManager.GetInhibitors`, where the Inhibit portal and `org.freedesktop.ScreenSaver` callers such as video players land); those carry an app id rather than a pid, so the pid comes from a registered session client, else the running process of the app's desktop entry. Temperatures from hwmon: `coretemp` package, `k10temp`/`zenpower` Tctl/Tdie, ARM thermal zones, ACPI as the fallback; NVMe/drivetemp for the disk. Fans: not yet. | +| Battery, apps preventing sleep, temperatures | Battery from `/sys/class/power_supply` (energy or charge counters, health capped at 100%, cycles, adapter); the condition in macOS's words (`Good` is Normal, a failing battery Service Recommended, else from the health). Sleep: systemd-logind's `block` inhibitors (`busctl … ListInhibitors`) and GNOME's session inhibitors with the suspend or idle flag (`org.gnome.SessionManager.GetInhibitors`, where the Inhibit portal and `org.freedesktop.ScreenSaver` callers such as video players land); those carry an app id rather than a pid, so the pid comes from a registered session client, else the running process of the app's desktop entry. A display inhibitor counts as keeping the system awake too, as on macOS and Windows. Temperatures from hwmon: `coretemp` package (its cores without one), `k10temp`/`zenpower` Tdie (Tctl, which carries an offset on early Zen, only without it), ARM thermal zones, ACPI as the fallback; NVMe/drivetemp for the disk. `PC_CAP_TEMPERATURE` means a CPU sensor, as on macOS and Windows. Fans: not yet. | | History, alerts, palette, settings | Shared with Windows: `~/.local/share/procyon/history.bin`, `GNotification` alerts, `Ctrl+K`, settings in `~/.config/procyon/settings.ini`. | | Energy, explanations for Linux processes, plugins | Not started (RAPL is root-only since 2020). | @@ -447,7 +466,11 @@ instance per session). There is no helper on Linux either: `helper_supported()` is false (the POSIX `HelperClient` builds, with `SO_PEERCRED` for the peer check, but nothing launches a helper). **Unlock Full Access** runs `pkexec env DISPLAY=… WAYLAND_DISPLAY=… XDG_RUNTIME_DIR=… procyon --page `; the window hides while the -root copy runs and comes back if authorization is dismissed. System services don't need it: polkit asks per action. +root copy runs and comes back if authorization is dismissed, or with an alert if the root copy fails as it starts. +The root copy serves the user who asked (`PKEXEC_UID`; `XDG_CONFIG_HOME`/`XDG_DATA_HOME` are passed through): it reads +and writes their `settings.ini` and `history.bin` (handing new files back to them), lists their autostart entries +and user units (`systemctl --user --machine=@.host`). Meanwhile the original copy is paused without a tray +icon, so one sampler, one tray icon and one writer remain. System services don't need it: polkit asks per action. ### Measured (i7-11700, 16 threads, about 175 processes, 1 s updates, release build) diff --git a/scripts/bench-linux.py b/scripts/bench-linux.py new file mode 100755 index 0000000..fae2f3e --- /dev/null +++ b/scripts/bench-linux.py @@ -0,0 +1,403 @@ +#!/usr/bin/env python3 +"""Measures Procyon for Linux against the non-functional targets in docs/procyon-spec.md. + + scripts/bench-linux.py build what is missing, measure, exit 1 on a missed target + scripts/bench-linux.py --report-only always exit 0 + scripts/bench-linux.py --attempts 3 measure a missed CPU or startup target again (CI) + scripts/bench-linux.py --pages overview processes --duration 30 + scripts/bench-linux.py --shard 2/3 one third of the screens (CI runs the three thirds in parallel) + +The counterpart of scripts/bench-macos.py and scripts/bench-windows.py. Measures the release app +(dist/linux/procyon) and the C++ core CLI (build/linux/procyon-cli) from /proc: startup time (launch to +the first frame the app reports under PROCYON_BENCH), CPU and private memory (RssAnon) at a 1 s refresh +on every screen and running in the background only (--background), the release tarball's size, and how +far the numbers are from the kernel's own counters. Writes dist/bench-linux.json and, on GitHub +Actions, a summary table. Needs a display: on CI, run it under xvfb-run. + +On a display without a GPU (Xvfb on a CI runner) GTK draws through Mesa's software OpenGL (llvmpipe), +whose buffers and JIT land in the app's private memory: 110-180 MB where the same screen holds about +35 MB on a desktop, whose GL buffers live in GPU memory. --renderer cairo (GSK_RENDERER) measures +Procyon's own footprint there; CI passes it. + +Shared CI runners are noisy: a fixed piece of work is timed alongside each measurement; its slowdown +against the fastest one of the run says how slow the runner was. A missed CPU or startup target whose +every attempt ran on a slow runner is reported as NOISY and does not fail. +""" + +import argparse +import json +import os +import re +import select +import statistics +import subprocess +import sys +import tarfile +import tempfile +import threading +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +APP = ROOT / "dist/linux/procyon" +BUILD = ROOT / "build/linux" +CLI = BUILD / "procyon-cli" +MB = 1024 * 1024 +TICKS = os.sysconf("SC_CLK_TCK") +RENDERER = None # GSK_RENDERER for the app (--renderer), None: GTK's choice + +# Every screen of the main window; `background` is the window closed, Procyon sampling in the +# background (tray or not), which has its own targets. +PAGES = [ + "overview", "processes", "cpu", "memory", "gpu", "disk", "network", "battery", "startup", "services", + "history", "inspect", "system", "settings", "background", +] + +# Targets from "Non-functional requirements" in docs/procyon-spec.md (the Windows script's values). +STARTUP_SECONDS = 1.0 # launch to first frame, median +CPU_LIMIT = 2.0 # % of a 4-core machine with the window open at a 1 s refresh +MEMORY_MB = 80 # private memory (RssAnon) with the window open, 90th percentile +BACKGROUND_CPU_LIMIT = 0.5 # % of a 4-core machine running in the background +BACKGROUND_MEMORY_MB = 30 +PACKAGE_MB = 20 # the release tarball +ACCURACY_PERCENT = 5 # vs the kernel's own counters; percentage points for CPU +NOISY_SLOWDOWN = 1.15 + + +def run(*args, **kwargs): + return subprocess.run(args, check=True, text=True, capture_output=True, cwd=ROOT, **kwargs).stdout + + +def ensure_built(): + if not (APP.is_file() and CLI.is_file()): + print("==> building dist/linux/procyon and the core CLI", flush=True) + subprocess.run([str(ROOT / "scripts/build-linux.sh"), "release", "--no-tests"], check=True, cwd=ROOT) + + +def calibrate(): + """Nanoseconds a fixed piece of work takes now: how busy the machine is.""" + start = time.perf_counter_ns() + total = 0 + for i in range(2_000_000): + total += i * i % 7 + return time.perf_counter_ns() - start + + +def cpu_ticks(pid): + """utime + stime of a process, in clock ticks.""" + with open(f"/proc/{pid}/stat") as f: + fields = f.read().rsplit(")", 1)[1].split() + return int(fields[11]) + int(fields[12]) + + +def private_bytes(pid): + """RssAnon: the memory the process holds itself (what the spec's 'private' means on Linux).""" + with open(f"/proc/{pid}/status") as f: + for line in f: + if line.startswith("RssAnon:"): + return int(line.split()[1]) * 1024 + return 0 + + +def probe(page, warmup, duration): + """Launches the app on `page` (or in the background), then samples its CPU and memory.""" + args = [str(APP), "--no-settings"] + args += ["--background"] if page == "background" else ["--page", page] + env = dict(os.environ, PROCYON_BENCH="1") + if RENDERER: + env["GSK_RENDERER"] = RENDERER + calibration = calibrate() + started = time.monotonic() + process = subprocess.Popen(args, env=env, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True) + startup = None + try: + if page != "background": + deadline = started + 15 + while time.monotonic() < deadline and startup is None: + ready, _, _ = select.select([process.stderr], [], [], 0.05) + if ready: + line = process.stderr.readline() + if not line: + break + if "first frame" in line: + startup = time.monotonic() - started + # Keep the pipe drained so the app never blocks on stderr. + threading.Thread(target=lambda: process.stderr.read(), daemon=True).start() + time.sleep(warmup) + result = {"page": page, "startup_seconds": startup, "calibration_ns": calibration} + if duration <= 0: + return result + memory = [] + ticks0, t0 = cpu_ticks(process.pid), time.monotonic() + end = t0 + duration + while time.monotonic() < end: + memory.append(private_bytes(process.pid)) + time.sleep(1) + ticks1, t1 = cpu_ticks(process.pid), time.monotonic() + memory.sort() + result.update( + cpu_percent_of_core=(ticks1 - ticks0) / TICKS / (t1 - t0) * 100, + memory_p90_bytes=memory[min(len(memory) - 1, int(len(memory) * 0.9))], + memory_peak_bytes=memory[-1], + memory_average_bytes=statistics.mean(memory), + ) + return result + finally: + process.terminate() + try: + process.wait(5) + except subprocess.TimeoutExpired: + process.kill() + + +def best(tries): + return min(tries, key=lambda r: r["cpu_percent_of_core"]) + + +def median_startup(launches): + measured = [launch["startup_seconds"] for launch in launches if launch["startup_seconds"] is not None] + return statistics.median(measured) if measured else None + + +def limits(page): + return (BACKGROUND_CPU_LIMIT, BACKGROUND_MEMORY_MB) if page == "background" else (CPU_LIMIT, MEMORY_MB) + + +def describe(page): + return "background only" if page == "background" else f"{page} open" + + +def package_size(tmp): + """The release tarball like scripts/package-linux.sh builds it, without touching dist/.""" + archive = Path(tmp, "procyon.tar.gz") + with tarfile.open(archive, "w:gz") as out: + for name in (APP, ROOT / "LICENSE", ROOT / "README.md"): + out.add(name, name.name) + return archive.stat().st_size + + +def system_cpu(): + """(busy, total) jiffies from /proc/stat's first line, iowait counted as idle like the core.""" + with open("/proc/stat") as f: + values = [int(v) for v in f.readline().split()[1:]] + idle = values[3] + values[4] + total = sum(values[:8]) + return total - idle, total + + +def meminfo(): + with open("/proc/meminfo") as f: + return {line.split(":")[0]: int(line.split()[1]) * 1024 for line in f} + + +def process_count(): + """Processes as the core lists them: every pid but kernel threads (kthreadd and its children).""" + count = 0 + for name in os.listdir("/proc"): + if not name.isdigit(): + continue + try: + with open(f"/proc/{name}/stat") as f: + fields = f.read().rsplit(")", 1)[1].split() + except OSError: + continue + if name != "2" and fields[1] != "2": + count += 1 + return count + + +def accuracy(seconds): + """Runs the core CLI and reads the kernel's own counters over the same window, then compares.""" + os_values = {} + + def os_cpu(): + time.sleep(1) # the CLI's first sample averages since the monitor was created + busy0, total0 = system_cpu() + time.sleep(seconds) + busy1, total1 = system_cpu() + os_values["cpu"] = (busy1 - busy0) / (total1 - total0) * 100 if total1 > total0 else 0.0 + + thread = threading.Thread(target=os_cpu) + thread.start() + output = run(str(CLI), str(seconds + 1), "1000") + thread.join() + info = meminfo() + memory = info["MemTotal"] - info["MemAvailable"] + swap = info["SwapTotal"] - info["SwapFree"] + processes = process_count() + + samples = re.findall( + r"^cpu ([\d.]+)% .*?mem ([\d.]+)/[\d.]+ GB .*?swap ([\d.]+) GB .*? (\d+) procs", output, re.M + ) + if len(samples) < 2: + sys.exit(f"bench: unexpected procyon-cli output:\n{output}") + cpu = statistics.mean(float(s[0]) for s in samples[1:]) + _, mem_gb, swap_gb, procs = samples[-1] + + def relative(ours, theirs): + return abs(ours - theirs) / theirs * 100 if theirs else (0.0 if ours == 0 else 100.0) + + ours_mem, ours_swap = float(mem_gb) * 1024 * MB, float(swap_gb) * 1024 * MB + return { + "cpu": {"procyon": cpu, "os": os_values["cpu"], "diff_points": abs(cpu - os_values["cpu"])}, + "memory_used": {"procyon": ours_mem, "os": memory, "diff_percent": relative(ours_mem, memory)}, + "swap_used": { + "procyon": ours_swap, + "os": swap, + "diff_percent": 0.0 if abs(ours_swap - swap) < 10 * MB else relative(ours_swap, swap), + }, + "process_count": {"procyon": int(procs), "os": processes, "diff_percent": relative(int(procs), processes)}, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--pages", nargs="+", default=PAGES, help="screens to measure") + parser.add_argument("--warmup", type=float, default=5, help="seconds after the first frame") + parser.add_argument("--duration", type=float, default=20, help="seconds of sampling per screen") + parser.add_argument("--launches", type=int, default=3, help="extra launches for the startup median") + parser.add_argument("--attempts", type=int, default=1, help="measure a screen up to this often while its CPU misses") + parser.add_argument("--report-only", action="store_true", help="exit 0 even when a target is missed") + parser.add_argument("--shard", default="1/1", help="K/N: measure one Nth of the screens; startup, size and " + "accuracy are measured by shard 1 only") + parser.add_argument("--known-misses", nargs="+", default=[], metavar="PAGE", + help="screens whose missed targets are reported but don't fail the run") + parser.add_argument("--renderer", help="GSK_RENDERER for the app (cairo on a display without a GPU, see above)") + parser.add_argument("--output", type=Path, default=ROOT / "dist/bench-linux.json") + args = parser.parse_args() + global RENDERER + RENDERER = args.renderer + try: + shard, shards = (int(n) for n in args.shard.split("/")) + assert 1 <= shard <= shards + except (ValueError, AssertionError): + parser.error("--shard takes K/N with 1 <= K <= N") + pages = args.pages[shard % shards :: shards] + whole = shard == 1 + title = f" {shard}/{shards}" if shards > 1 else "" + + ensure_built() + sizes = {} + if whole: + with tempfile.TemporaryDirectory() as tmp: + print("==> sizes", flush=True) + sizes = {"app_bytes": APP.stat().st_size, "package_bytes": package_size(tmp)} + + attempts = {} + for page in pages: + print(f"==> {page}: {args.warmup:g} s warm-up, {args.duration:g} s sampling", flush=True) + attempts[page] = [probe(page, args.warmup, args.duration)] + while len(attempts[page]) < args.attempts and best(attempts[page])["cpu_percent_of_core"] / 4 >= limits(page)[0]: + print(f"==> {page}: CPU missed, measuring again", flush=True) + attempts[page].append(probe(page, args.warmup, args.duration)) + launches = [[{"startup_seconds": a[0]["startup_seconds"], "calibration_ns": a[0]["calibration_ns"]} + for p, a in attempts.items() if p != "background"]] + while whole: + for i in range(args.launches): + print(f"==> launch {i + 1}/{args.launches}", flush=True) + launches[-1].append(probe("overview", 0, 0)) + if len(launches) >= args.attempts or (median_startup(launches[-1]) or STARTUP_SECONDS) < STARTUP_SECONDS: + break + print("==> startup missed, measuring again", flush=True) + launches.append([]) + + acc = {} + if whole: + print("==> accuracy against /proc/stat, /proc/meminfo and /proc", flush=True) + acc = accuracy(10) + + calibrations = [a["calibration_ns"] for tries in attempts.values() for a in tries] + calibrations += [launch["calibration_ns"] for batch in launches for launch in batch] + baseline = min((c for c in calibrations if c), default=1) + for tries in attempts.values(): + for a in tries: + a["runner_slowdown"] = a["calibration_ns"] / baseline + screens = [best(tries) for tries in attempts.values()] + batches = [ + {"median_seconds": median_startup(batch), + "runner_slowdown": statistics.median(launch["calibration_ns"] for launch in batch) / baseline if batch else 1, + "startup_seconds": [launch["startup_seconds"] for launch in batch]} + for batch in launches + ] + startup = min((b["median_seconds"] for b in batches if b["median_seconds"] is not None), default=None) + + def runner(slowdowns): + return f", runner {min(slowdowns):.2f}× slower" if min(slowdowns) >= 1.05 else "", min(slowdowns) > NOISY_SLOWDOWN + + checks = [] + if whole: + note, noisy = runner([b["runner_slowdown"] for b in batches]) + checks.append(("Startup, median to first frame", startup, STARTUP_SECONDS, + f"{startup:.2f} s{note}" if startup else "no frame", f"< {STARTUP_SECONDS:g} s", noisy)) + known_misses = set() + for s in screens: + if s["page"] in args.known_misses: + known_misses |= {f"CPU, {describe(s['page'])} at 1 s refresh", f"Memory, {describe(s['page'])}"} + cpu_limit, memory_limit = limits(s["page"]) + note, noisy = runner([a["runner_slowdown"] for a in attempts[s["page"]]]) + checks.append((f"CPU, {describe(s['page'])} at 1 s refresh", s["cpu_percent_of_core"] / 4, cpu_limit, + f"{s['cpu_percent_of_core'] / 4:.2f}% of a 4-core PC ({s['cpu_percent_of_core']:.1f}% of one core{note})", + f"< {cpu_limit:g}% on 4 cores", noisy)) + checks.append((f"Memory, {describe(s['page'])}", s["memory_p90_bytes"] / MB, memory_limit, + f"{s['memory_p90_bytes'] / MB:.1f} MB p90 (peak {s['memory_peak_bytes'] / MB:.1f}, " + f"average {s['memory_average_bytes'] / MB:.1f})", f"< {memory_limit} MB", False)) + if whole: + checks.append(("Package (tar.gz)", sizes["package_bytes"] / MB, PACKAGE_MB, + f"{sizes['package_bytes'] / MB:.1f} MB (procyon {sizes['app_bytes'] / MB:.1f} MB)", + f"< {PACKAGE_MB} MB", False)) + cpu = acc["cpu"] + checks.append(("Accuracy: CPU vs /proc/stat", cpu["diff_points"], ACCURACY_PERCENT, + f"{cpu['procyon']:.1f}% vs {cpu['os']:.1f}% ({cpu['diff_points']:.1f} points)", + f"< {ACCURACY_PERCENT} points", False)) + for key, label in (("memory_used", "memory in use vs MemTotal - MemAvailable"), + ("swap_used", "swap vs SwapTotal - SwapFree")): + a = acc[key] + checks.append((f"Accuracy: {label}", a["diff_percent"], ACCURACY_PERCENT, + f"{a['procyon'] / MB:,.0f} vs {a['os'] / MB:,.0f} MB ({a['diff_percent']:.1f}%)", + f"< {ACCURACY_PERCENT}%", False)) + p = acc["process_count"] + checks.append(("Accuracy: process count vs /proc", p["diff_percent"], ACCURACY_PERCENT, + f"{p['procyon']} vs {p['os']} ({p['diff_percent']:.1f}%)", f"< {ACCURACY_PERCENT}%", False)) + + def status(name, value, bound, noisy): + if value is not None and value < bound: + return "PASS" + return "KNOWN" if name in known_misses else "NOISY" if noisy else "FAIL" + + rows = [(name, shown, limit, status(name, value, bound, noisy)) for name, value, bound, shown, limit, noisy in checks] + width = max(len(r[0]) for r in rows) + print() + for name, shown, limit, result in rows: + print(f"{result:<5} {name:<{width}} {shown} (target {limit})") + + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps( + {"sizes": sizes, "screens": screens, "attempts": attempts, "startup": batches, "calibration_baseline_ns": baseline, + "accuracy": acc, "checks": [{"name": n, "value": s, "target": l, "result": r} for n, s, l, r in rows]}, + indent=2), encoding="utf-8") + if RENDERER: + print(f"\nGTK renderer: {RENDERER}") + print(f"\nWrote {os.path.relpath(args.output, ROOT)}") + + noisy = [r for r in rows if r[3] == "NOISY"] + if os.environ.get("GITHUB_ACTIONS"): + for name, shown, limit, _ in noisy: + print(f"::warning title=Performance target missed on a slow runner::{name}: {shown} (target {limit})") + if summary := os.environ.get("GITHUB_STEP_SUMMARY"): + marks = {"PASS": "✅", "KNOWN": "⚠️ known", "NOISY": "⚠️ noisy", "FAIL": "❌"} + with open(summary, "a", encoding="utf-8") as out: + out.write(f"### Performance targets (Linux{title})\n\n| | Target | Measured | Spec |\n| --- | --- | --- | --- |\n") + for name, shown, limit, result in rows: + out.write(f"| {marks[result]} | {name} | {shown} | {limit} |\n") + out.write("\nShared CI runners are noisy: treat CPU and startup as trends, not exact numbers. " + f"⚠️ noisy: missed, but every attempt ran on a runner over {NOISY_SLOWDOWN:g}× slower than its best.\n") + + failed = [r for r in rows if r[3] == "FAIL"] + if noisy: + print(f"\n{len(noisy)} target(s) missed on a slow runner, not counted", file=sys.stderr) + if failed and not args.report_only: + sys.exit(f"\n{len(failed)} target(s) missed") + + +if __name__ == "__main__": + main() diff --git a/scripts/screenshots-windows.ps1 b/scripts/screenshots-windows.ps1 new file mode 100644 index 0000000..a651e11 --- /dev/null +++ b/scripts/screenshots-windows.ps1 @@ -0,0 +1,21 @@ +# Renders the main screens, light and dark, into dist\windows\screenshots with the app's own +# --screenshot mode (the counterpart of `make screenshots` on Linux). Run after `make app`. +# scripts\screenshots-windows.ps1 [-Pages overview,processes,...] +param( + [string[]]$Pages = @('overview', 'processes', 'cpu', 'history', 'inspect', 'startup', 'services') +) +$ErrorActionPreference = 'Stop' +$root = Split-Path -Parent $PSScriptRoot +$app = Join-Path $root 'dist\windows\Procyon.exe' +$out = Join-Path $root 'dist\windows\screenshots' +if (-not (Test-Path $app)) { throw "$app is missing: run make app first" } +New-Item -ItemType Directory -Force $out | Out-Null +foreach ($page in $Pages) { + foreach ($theme in 'light', 'dark') { + $file = Join-Path $out "$page-$theme.png" + $process = Start-Process -FilePath $app -ArgumentList @('--screenshot', "`"$file`"", "--$theme", '--page', $page) ` + -Wait -PassThru + if ($process.ExitCode -ne 0) { throw "couldn't render $page ($theme)" } + } +} +Write-Output $out