From 1e647da7d5773405139d78c4b82c1e931fe036c4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:49:15 +0000 Subject: [PATCH 01/60] chore(vendor): add vendored btop sources Vendor the btop system monitor and its bundled fmt headers under vendor/btop so the project can build against a pinned copy instead of relying on a system install. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/LICENSE | 202 ++ vendor/btop/README.md | 1593 +++++++++ vendor/btop/include/fmt/LICENSE.rst | 27 + vendor/btop/include/fmt/args.h | 220 ++ vendor/btop/include/fmt/base.h | 2994 ++++++++++++++++ vendor/btop/include/fmt/chrono.h | 2241 ++++++++++++ vendor/btop/include/fmt/color.h | 637 ++++ vendor/btop/include/fmt/compile.h | 585 ++++ vendor/btop/include/fmt/core.h | 5 + vendor/btop/include/fmt/format-inl.h | 1953 +++++++++++ vendor/btop/include/fmt/format.h | 4383 ++++++++++++++++++++++++ vendor/btop/include/fmt/os.h | 428 +++ vendor/btop/include/fmt/ostream.h | 167 + vendor/btop/include/fmt/printf.h | 624 ++++ vendor/btop/include/fmt/ranges.h | 852 +++++ vendor/btop/include/fmt/std.h | 707 ++++ vendor/btop/include/fmt/xchar.h | 356 ++ vendor/btop/include/widechar_width.hpp | 1571 +++++++++ vendor/btop/src/btop.cpp | 1189 +++++++ vendor/btop/src/btop.hpp | 4 + vendor/btop/src/btop_cli.cpp | 272 ++ vendor/btop/src/btop_cli.hpp | 53 + vendor/btop/src/btop_config.cpp | 901 +++++ vendor/btop/src/btop_config.hpp | 137 + vendor/btop/src/btop_draw.cpp | 2551 ++++++++++++++ vendor/btop/src/btop_draw.hpp | 141 + vendor/btop/src/btop_input.cpp | 648 ++++ vendor/btop/src/btop_input.hpp | 78 + vendor/btop/src/btop_log.cpp | 160 + vendor/btop/src/btop_log.hpp | 69 + vendor/btop/src/btop_menu.cpp | 1963 +++++++++++ vendor/btop/src/btop_menu.hpp | 99 + vendor/btop/src/btop_shared.cpp | 360 ++ vendor/btop/src/btop_shared.hpp | 462 +++ vendor/btop/src/btop_theme.cpp | 473 +++ vendor/btop/src/btop_theme.hpp | 70 + vendor/btop/src/btop_tools.cpp | 769 +++++ vendor/btop/src/btop_tools.hpp | 466 +++ vendor/btop/src/linux/btop_collect.cpp | 3643 ++++++++++++++++++++ vendor/btop/src/osx/btop_collect.cpp | 2067 +++++++++++ vendor/btop/src/osx/sensors.cpp | 180 + vendor/btop/src/osx/sensors.hpp | 31 + vendor/btop/src/osx/smc.cpp | 154 + vendor/btop/src/osx/smc.hpp | 119 + 44 files changed, 36604 insertions(+) create mode 100644 vendor/btop/LICENSE create mode 100644 vendor/btop/README.md create mode 100644 vendor/btop/include/fmt/LICENSE.rst create mode 100644 vendor/btop/include/fmt/args.h create mode 100644 vendor/btop/include/fmt/base.h create mode 100644 vendor/btop/include/fmt/chrono.h create mode 100644 vendor/btop/include/fmt/color.h create mode 100644 vendor/btop/include/fmt/compile.h create mode 100644 vendor/btop/include/fmt/core.h create mode 100644 vendor/btop/include/fmt/format-inl.h create mode 100644 vendor/btop/include/fmt/format.h create mode 100644 vendor/btop/include/fmt/os.h create mode 100644 vendor/btop/include/fmt/ostream.h create mode 100644 vendor/btop/include/fmt/printf.h create mode 100644 vendor/btop/include/fmt/ranges.h create mode 100644 vendor/btop/include/fmt/std.h create mode 100644 vendor/btop/include/fmt/xchar.h create mode 100644 vendor/btop/include/widechar_width.hpp create mode 100644 vendor/btop/src/btop.cpp create mode 100644 vendor/btop/src/btop.hpp create mode 100644 vendor/btop/src/btop_cli.cpp create mode 100644 vendor/btop/src/btop_cli.hpp create mode 100644 vendor/btop/src/btop_config.cpp create mode 100644 vendor/btop/src/btop_config.hpp create mode 100644 vendor/btop/src/btop_draw.cpp create mode 100644 vendor/btop/src/btop_draw.hpp create mode 100644 vendor/btop/src/btop_input.cpp create mode 100644 vendor/btop/src/btop_input.hpp create mode 100644 vendor/btop/src/btop_log.cpp create mode 100644 vendor/btop/src/btop_log.hpp create mode 100644 vendor/btop/src/btop_menu.cpp create mode 100644 vendor/btop/src/btop_menu.hpp create mode 100644 vendor/btop/src/btop_shared.cpp create mode 100644 vendor/btop/src/btop_shared.hpp create mode 100644 vendor/btop/src/btop_theme.cpp create mode 100644 vendor/btop/src/btop_theme.hpp create mode 100644 vendor/btop/src/btop_tools.cpp create mode 100644 vendor/btop/src/btop_tools.hpp create mode 100644 vendor/btop/src/linux/btop_collect.cpp create mode 100644 vendor/btop/src/osx/btop_collect.cpp create mode 100644 vendor/btop/src/osx/sensors.cpp create mode 100644 vendor/btop/src/osx/sensors.hpp create mode 100644 vendor/btop/src/osx/smc.cpp create mode 100644 vendor/btop/src/osx/smc.hpp diff --git a/vendor/btop/LICENSE b/vendor/btop/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/vendor/btop/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/btop/README.md b/vendor/btop/README.md new file mode 100644 index 000000000..9b0c2936d --- /dev/null +++ b/vendor/btop/README.md @@ -0,0 +1,1593 @@ +# ![btop++](Img/logo.png) + + + Packaging status + + +![Linux](https://img.shields.io/badge/-Linux-grey?logo=linux) +![macOS](https://img.shields.io/badge/-OSX-black?logo=apple) +![FreeBSD](https://img.shields.io/badge/-FreeBSD-red?logo=freebsd) +![NetBSD](https://img.shields.io/badge/-NetBSD-black?logo=netbsd) +![OpenBSD](https://img.shields.io/badge/-OpenBSD-black?logo=openbsd) +![Usage](https://img.shields.io/badge/Usage-System%20resource%20monitor-yellow) +![c++23](https://img.shields.io/badge/cpp-c%2B%2B23-green) +![latest_release](https://img.shields.io/github/v/tag/aristocratos/btop?label=release) +[![Donate](https://img.shields.io/badge/-Donate-yellow?logo=paypal)](https://paypal.me/aristocratos) +[![Sponsor](https://img.shields.io/badge/-Sponsor-red?logo=github)](https://github.com/sponsors/aristocratos) +[![Coffee](https://img.shields.io/badge/-Buy%20me%20a%20Coffee-grey?logo=Ko-fi)](https://ko-fi.com/aristocratos) +[![btop](https://snapcraft.io/btop/badge.svg)](https://snapcraft.io/btop) +[![Continuous Build Linux](https://github.com/aristocratos/btop/actions/workflows/continuous-build-linux.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-linux.yml) +[![Continuous Build macOS](https://github.com/aristocratos/btop/actions/workflows/continuous-build-macos.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-macos.yml) +[![Continuous Build FreeBSD](https://github.com/aristocratos/btop/actions/workflows/continuous-build-freebsd.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-freebsd.yml) +[![Continuous Build NetBSD](https://github.com/aristocratos/btop/actions/workflows/continuous-build-netbsd.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-netbsd.yml) +[![Continuous Build OpenBSD](https://github.com/aristocratos/btop/actions/workflows/continuous-build-openbsd.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-openbsd.yml) + +## Index + +* [News](#news) +* [Documents](#documents) +* [Description](#description) +* [Features](#features) +* [Themes](#themes) +* [Support and funding](#support-and-funding) +* [Prerequisites](#prerequisites) (Read this if you are having issues!) +* [Screenshots](#screenshots) +* [Keybindings](#help-menu) +* [Installation Linux/macOS](#installation) +* [Compilation Linux](#compilation-linux) +* [Compilation macOS](#compilation-macos-osx) +* [Compilation FreeBSD](#compilation-freebsd) +* [Compilation NetBSD](#compilation-netbsd) +* [Compilation OpenBSD](#compilation-openbsd) +* [Testing](#testing) +* [GPU compatibility](#gpu-compatibility) +* [Installing the snap](#installing-the-snap) +* [Configurability](#configurability) +* [License](#license) + +If you are considering donating, please first consider donating to: + +[](https://www.qm4ua.org/) +[](https://donate.savethechildren.org) + + + +## News + +##### 22 March 2026 + +Updated contributing guidelines for AI generated code: + +* Submissions where any of the code is AI generated must be marked with [AI generated]. + + (When code is generated by prompting either directly to an LLM or through "comment prompting".) + +* Not needed when AI suggestions is used in "autocomplete" mode only for boilerplate or other repetitive code. + +* Failure to disclose the use of AI in a PR will result in a closed PR and deliberately trying to obfuscate the use of AI will result in your account getting blocked from contributing again. + +* "Vibe coded" PR's where it seems like the author doesn't understand the generated code will be dismissed. + + +##### 4 December 2025 + +Since there is a increasing amount of AI generated/assisted PR's, the following guidelines have been added to CONTRIBUTING.md: + +* Submissions where the majority of the code is AI generated must be marked with [AI generated]. + +* "Vibe coded" PR's where it seems like the author doesn't understand the generated code will be dismissed. + +##### 22 September 2024 + +Btop release v1.4.0 + +Intel GPU support added, note that only GPU utilization, power usage and clock speed available to monitor. Thanks to [@bjia56](https://github.com/bjia56) for contributions. + +NetBSD support added. Thanks to [@fraggerfox](https://github.com/fraggerfox) for contributions. + +See [CHANGELOG.md](CHANGELOG.md) and latest [release](https://github.com/aristocratos/btop/releases/latest) for detailed list of new features, bug fixes and new themes. + +##### 7 January 2024 + +Btop release v1.3.0 + +Big release with GPU support added for Linux and platform support for OpenBSD. Big thanks to [@romner-set](https://github.com/romner-set) (GPU support) and [@joske](https://github.com/joske) (OpenBSD support) for contributions. +And a multitude of bugfixes and small changes, see [CHANGELOG.md](CHANGELOG.md) and latest [release](https://github.com/aristocratos/btop/releases/latest) for detailed list and attributions. + +See news entry below for more information regarding GPU support. + +##### 25 November 2023 + +GPU monitoring added for Linux! + +Compile from git main to try it out. + +Use keys `5`, `6`, `7` and `0` to show/hide the gpu monitoring boxes. `5` = Gpu 1, `6` = Gpu 2, etc. + +Gpu stats/graphs can also be displayed in the "Cpu box" (not as verbose), see the cpu options menu for info and configuration. + +Note that the binaries provided on the release page (when released) and the continuous builds will not have gpu support enabled. + +Because the GPU support relies on loading of dynamic gpu libraries, gpu support will not work when also static linking. + +See [Compilation Linux](#compilation-linux) for more info on how to compile with gpu monitoring support. + +Many thanks to [@romner-set](https://github.com/romner-set) who wrote the vast majority of the implementation for GPU support. + +Big update with version bump to 1.3 coming soon. + +##### 28 August 2022 + +[![btop4win](https://github.com/aristocratos/btop4win/raw/master/Img/logo.png)](https://github.com/aristocratos/btop4win) + +First release of btop4win available at https://github.com/aristocratos/btop4win + +
+More... + +##### 16 January 2022 + +Release v1.2.0 with FreeBSD support. No release binaries for FreeBSD provided as of yet. + +Again a big thanks to [@joske](https://github.com/joske) for his porting efforts! + +Since compatibility with Linux, macOS and FreeBSD are done, the focus going forward will be on new features like GPU monitoring. + +##### 13 November 2021 + +Release v1.1.0 with macOS support. Binaries in [continuous-build-macos](https://github.com/aristocratos/btop/actions/workflows/continuous-build-macos.yml) are only x86 for now. +macOS binaries + installer are included for both x86 and ARM64 (Apple Silicon) in the releases. + +Big thank you to [@joske](https://github.com/joske) who wrote the vast majority of the implementation! + +##### 30 October 2021 + +Work on the OSX [macOS] and FreeBSD branches, both initiated and mostly worked on by [@joske](https://github.com/joske), will likely be completed in the coming weeks. +The OSX [macOS] branch has some memory leaks that needs to be sorted out and both have some issues with the processes cpu usage calculation and other smaller issues that needs fixing. + +If you want to help out, test for bugs/fix bugs or just try out the branches: + +**macOS / OSX** +```bash +# Install and use Homebrew or MacPorts package managers for easy dependency installation +brew install coreutils make gcc@11 lowdown +git clone https://github.com/aristocratos/btop.git +cd btop +git checkout OSX +gmake +``` + +**FreeBSD** +```bash +sudo pkg install gmake gcc11 coreutils git lowdown +git clone https://github.com/aristocratos/btop.git +cd btop +git checkout freebsd +gmake +``` + +Note that GNU make (`gmake`) is recommended but not required for macOS/OSX but it is required on FreeBSD. + + +##### 6 October 2021 + +macOS development have been started by [@joske](https://github.com/joske), big thanks :) +See branch [OSX](https://github.com/aristocratos/btop/tree/OSX) for current progress. + +##### 18 September 2021 + +The Linux version of btop++ is complete. Released as version 1.0.0 + +I will be providing statically compiled binaries for a range of architectures in every release for those having problems compiling. + +For compilation GCC 11 is required. + +Please report any bugs to the [Issues](https://github.com/aristocratos/btop/issues/new?assignees=aristocratos&labels=bug&template=bug_report.md&title=%5BBUG%5D) page. + +The development plan right now: + +* 1.1.0 macOS [OSX] support +* 1.2.0 FreeBSD support +* 1.3.0 Support for GPU monitoring +* 1.X.0 Other platforms and features... + +Windows support is not in the plans as of now, but if anyone else wants to take it on, I will try to help. + +##### 5 May 2021 + +This project is gonna take some time until it has complete feature parity with bpytop, since all system information gathering will have to be written from scratch without any external libraries. +And will need some help in the form of code contributions to get complete support for BSD and macOS/OSX. + +
+ +## Documents + +**[CHANGELOG.md](CHANGELOG.md)** + +**[CONTRIBUTING.md](CONTRIBUTING.md)** + +**[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)** + +## Description + +Resource monitor that shows usage and stats for processor, memory, disks, network and processes. + +C++ version and continuation of [bashtop](https://github.com/aristocratos/bashtop) and [bpytop](https://github.com/aristocratos/bpytop). + +## Features + +* Easy to use, with a game inspired menu system. +* Full mouse support: all buttons with a highlighted key are clickable and mouse scrolling works in process list and menu boxes. +* Fast and responsive UI with UP, DOWN key process selection. +* Function for showing detailed stats for selected process. +* Ability to filter processes. +* Easy switching between sorting options. +* Tree view of processes. +* Send any signal to selected process. +* Pause the process list. +* UI menu for changing all config file options. +* Auto scaling graph for network usage. +* Shows IO activity and speeds for disks. +* Battery meter +* Selectable symbols for the graphs. +* Custom presets +* And more... + +## Themes + +Btop++ uses the same theme files as bpytop and bashtop (some color values missing in bashtop themes). + +See [themes](https://github.com/aristocratos/btop/tree/main/themes) folder for available themes. + +Btop searches the following directories for system themes: + +* `../share/btop/themes` (this path is relative to the btop executable) +* `/usr/local/share/btop/themes` +* `/usr/share/btop/themes` + +The first directory that exists and isn't empty is used as the system themes directory. + +The user themes directory depends on which environment variables are set: + +* If `$XDG_CONFIG_HOME` is set, the user themes directory is `$XDG_CONFIG_HOME/btop/themes` +* Otherwise, if `$HOME` is set, the user themes directory is `$HOME/.config/btop/themes` +* Otherwise, the user themes directory is `~/.config/btop/themes` + +The `make install` command places the default themes in `[$PREFIX or /usr/local]/share/btop/themes`. +User created themes should be placed in the user themes directory. + +Use the `--themes-dir` command-line option to specify a custom themes directory. +When specified, this directory takes priority over the default search paths. + +Let me know if you want to contribute with new themes. + +The new Process list pausing and Process following features introduce a few new theme attributes. +These attributes still need to be added to all of the existing themes (except the default one). + +Process list banner attributes: +* proc_pause_bg: background color of the banner when the list is paused. +* proc_follow_bg: background color of the banner when the process following feature is active. +* proc_banner_bg: background color of the banner when the process following feature is active AND the list is paused. +* proc_banner_fg: foreground (text) color of the banner + +Process following attributes: +* followed_bg: background color of the followed process in the list. +* followed_fg: foreground color of the followed process in the list. + +## Support and funding + +You can sponsor this project through GitHub. See [my sponsors page](https://github.com/sponsors/aristocratos) for options. + +Or donate through [PayPal](https://paypal.me/aristocratos) or [ko-fi](https://ko-fi.com/aristocratos). + +Any support is greatly appreciated! + +## Prerequisites + +For the best experience run within a terminal with support for: + +* 24-bit truecolor ([See list of terminals with truecolor support](https://github.com/termstandard/colors)) +* 256-color terminals are supported through 24-bit to 256-color conversion when setting "truecolor" to False in the options or with "-lc/--low-color" arguments. +* 16 color TTY mode will be activated if a real tty device is detected. Can be forced with "-t/--tty" arguments. +* Wide characters (Are sometimes problematic in web-based terminals) + +Also necessary is a UTF8 locale and a font that includes: + +* Unicode Block “Braille Patterns” U+2800 - U+28FF (Not needed in TTY mode or with graphs set to type: block or tty.) +* Unicode Block “Geometric Shapes” U+25A0 - U+25FF +* Unicode Block "Box Drawing" and "Block Elements" U+2500 - U+259F + +### **Optional Dependencies (Needed for GPU monitoring)** + +GPU monitoring is supported on Linux and on macOS with Apple Silicon GPUs. + +GPU monitoring also requires a btop binary built with GPU support (`GPU_SUPPORT=true` flag). + +See [GPU compatibility](#gpu-compatibility) section for more about compiling with GPU support. + + * **NVIDIA** + + If you have an NVIDIA GPU you must use an official NVIDIA driver, both the closed-source and open-source ones have been verified to work. + + In addition to that you must also have the nvidia-ml dynamic library installed, which should be included with the driver package of your distribution. + + * **AMD** + + If you have an AMD GPU `rocm_smi_lib` is required, which may or may not be packaged for your distribution. + + * **INTEL** + + Requires a working C compiler if compiling from source. + + Also requires the user to have permission to read from SYSFS. + + Can be set with `make setcap` (preferred) or `make setuid` or by running btop with `sudo` or equivalent. + +### **Notice (Text rendering issues)** + +* If you are having problems with the characters in the graphs not looking like they do in the screenshots, it's likely a problem with your systems configured fallback font not having support for braille characters. + +* See [Terminess Powerline](https://github.com/ryanoasis/nerd-fonts/blob/master/patched-fonts/Terminus/TerminessNerdFontMono-Regular.ttf) for an example of a font that includes the braille symbols. + +* See comments by @sgleizes [link](https://github.com/aristocratos/bpytop/issues/100#issuecomment-684036827) and @XenHat [link](https://github.com/aristocratos/bpytop/issues/100#issuecomment-691585587) in issue #100 for possible solutions. + +* If text is misaligned and you use Konsole or Yakuake, turning off "Bi-Directional text rendering" is a possible fix. + +* Characters clipping into each other or text/border misalignments are not bugs caused by btop, but most likely a fontconfig or terminal problem where the braille characters making up the graphs aren't rendered correctly. + +* Look to the creators of the terminal emulator you use to fix these issues if the previously mentioned fixes don't work for you. + +## Screenshots + +#### Main UI showing details for a selected process + +![Screenshot 1](Img/normal.png) + +#### Main UI in TTY mode + +![Screenshot 2](Img/tty.png) + +#### Main UI with custom options + +![Screenshot 3](Img/alt.png) + +#### Main-menu + +![Screenshot 3](Img/main-menu.png) + +#### Options-menu + +![Screenshot 4](Img/options-menu.png) + +#### Help-menu + +![Screenshot 5](Img/help-menu.png) + +## Installation + +**Binaries for Linux are statically compiled with musl and work on kernel releases 2.6.39 and newer** + +1. **Download btop-(VERSION)-(ARCH)-(PLATFORM).tbz from [latest release](https://github.com/aristocratos/btop/releases/latest) and unpack to a new folder** + + **Notice! Use x86_64 for 64-bit x86 systems, i486 and i686 are 32-bit!** + +2. **Install (from created folder)** + + * **Run:** + + ```bash + # use "make install PREFIX=/target/dir" to set target, default: /usr/local + # only use "sudo" when installing to a NON user owned directory + sudo make install + ``` + +3. **(Optional/Required for Intel GPU and CPU wattage) Set extended capabilities or suid bit to btop** + + Enables signal sending to any process without starting with `sudo` and can prevent /proc read permissions problems on some systems. + + Is required for Intel GPU support and CPU wattage monitoring. + + * **Run:** + + ```bash + # run after make install and use same PREFIX if any was used at install + sudo make setcap + ``` + * **or** + + ```bash + # run after make install and use same PREFIX if any was used at install + # set SU_USER and SU_GROUP to select user and group, default is root:root + sudo make setuid + ``` + +* **Uninstall** + + * **Run:** + + ```bash + sudo make uninstall + ``` + +* **Show help** + + ```bash + make help + ``` + +**Binary release (from native os repo)** + +* **openSUSE** + * **Tumbleweed:** + ```bash + sudo zypper in btop + ``` + * For all other versions, see [openSUSE Software: btop](https://software.opensuse.org/package/btop) +* **Fedora** + ```bash + sudo dnf install btop + ``` +* **RHEL/Rocky/AlmaLinux 8+** + ```bash + sudo dnf install epel-release + sudo dnf install btop + ``` +* **FreeBSD** + ```sh + pkg install btop + ``` +* **NetBSD** + ```sh + pkg_add btop + ``` + + +**Binary release on Homebrew (macOS (x86_64 & ARM64) / Linux (x86_64))** + +* **[Homebrew](https://formulae.brew.sh/formula/btop)** + ```bash + brew install btop + ``` + +## Compilation Linux + + Requires at least GCC 14 or Clang 19. + + The Makefile also needs GNU `coreutils` and `sed` (should already be installed on any modern distribution). + + ### GPU compatibility + + Btop++ supports Nvidia and AMD GPUs and Intel IGPUs out of the box on Linux x86_64, provided you have the correct drivers and libraries. + + Gpu support for Nvidia or AMD will not work when static linking glibc (or musl, etc.)! + + For x86_64 Linux the flag `GPU_SUPPORT` is automatically set to `true`, to manually disable gpu support set the flag to false, like: + + `make GPU_SUPPORT=false` (or `cmake -DBTOP_GPU=false` with CMake) + + * **NVIDIA** + + You must use an official NVIDIA driver, both the closed-source and [open-source](https://github.com/NVIDIA/open-gpu-kernel-modules) ones have been verified to work. + + In addition to that you must also have the `nvidia-ml` dynamic library installed, which should be included with the driver package of your distribution. + + * **AMD** + + AMDGPU data is queried using the [ROCm SMI](https://github.com/rocm/rocm_smi_lib) library, which may or may not be packaged for your distribution. If your distribution doesn't provide a package, btop++ is statically linked to ROCm SMI with the `RSMI_STATIC=true` make flag. + + This flag expects the ROCm SMI source code in `lib/rocm_smi_lib`, and compilation will fail if it's not there. The latest tested version is 5.6.x, which can be obtained with the following command: + + ```bash + git clone https://github.com/rocm/rocm_smi_lib.git --depth 1 -b rocm-5.6.x lib/rocm_smi_lib + ``` + +
+ + +### With Make + + +1. **Install dependencies (example for Ubuntu 24.04 Noble)** + + ```bash + sudo apt install coreutils sed git build-essential lowdown + ``` + +2. **Clone repository** + + ```bash + git clone https://github.com/aristocratos/btop.git + cd btop + ``` + +3. **Compile** + + ```bash + make + ``` + + Options for make: + + | Flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `VERBOSE=true` | To display full compiler/linker commands | + | `STATIC=true` | For static compilation | + | `QUIET=true` | For less verbose output | + | `STRIP=true` | To force stripping of debug symbols (adds `-s` linker flag) | + | `DEBUG=true` | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging | + | `ARCH=` | To manually set the target architecture | + | `GPU_SUPPORT=` | Enable/disable GPU support (Enabled by default on X86_64 Linux) | + | `RSMI_STATIC=true` | To statically link the ROCm SMI library used for querying AMDGPU | + | `ADDFLAGS=` | For appending flags to both compiler and linker | + | `CXX=` | Manually set which compiler to use | + + Example: `make ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system. + + Notice! If using LDAP Authentication, usernames will show as UID number for LDAP users if compiling statically with glibc. + +4. **Install** + + ```bash + sudo make install + ``` + + Append `PREFIX=/target/dir` to set target, default: `/usr/local` + + Notice! Only use "sudo" when installing to a NON user owned directory. + +5. **(Optional/Required for Intel GPU support and CPU wattage) Set extended capabilities or suid bit to btop** + + No need for `sudo` to enable signal sending to any process and to prevent /proc read permissions problems on some systems. + + Also required for Intel GPU monitoring and CPU wattage monitoring. + + Run after make install and use same PREFIX if any was used at install. + + ```bash + sudo make setcap + ``` + + or + + Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `root` + + ```bash + sudo make setuid + ``` + +* **Uninstall** + + ```bash + sudo make uninstall + ``` + +* **Remove any object files from source dir** + + ```bash + make clean + ``` + +* **Remove all object files, binaries and created directories in source dir** + + ```bash + make distclean + ``` + +* **Show help** + + ```bash + make help + ``` + +
+
+ + +### With CMake (Community maintained) + + +1. **Install build dependencies** + + Requires Clang / GCC, CMake, Ninja, Lowdown and Git + + For example, with Debian Bookworm: + + ```bash + sudo apt install cmake git g++ ninja-build lowdown + ``` + +2. **Clone the repository** + + ```bash + git clone https://github.com/aristocratos/btop.git && cd btop + `````` + +3. **Compile** + + ```bash + # Configure + cmake -B build -G Ninja + # Build + cmake --build build + ``` + + This will automatically build a release version of btop. + + Some useful options to pass to the configure step: + + | Configure flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `-DBTOP_STATIC=` | Enables static linking (OFF by default) | + | `-DBTOP_LTO=` | Enables link time optimization (ON by default) | + | `-DBTOP_GPU=` | Enable GPU support (ON by default) | + | `-DBTOP_RSMI_STATIC=` | Build and link the ROCm SMI library statically (OFF by default) | + | `-DCMAKE_INSTALL_PREFIX=` | The installation prefix ('/usr/local' by default) | + + To force any other compiler, run `CXX= cmake -B build -G Ninja` + +4. **Install** + + ```bash + cmake --install build + ``` + + May require root privileges + +5. **Uninstall** + + CMake doesn't generate an uninstall target by default. To remove installed files, run + ``` + cat build/install_manifest.txt | xargs rm -irv + ``` + +6. **Cleanup build directory** + + ```bash + cmake --build build -t clean + ``` + +
+ +## Compilation macOS OSX + + Requires at least GCC 14 or Clang 19. + + The Makefile also needs GNU coreutils and `sed`. + + Install and use Homebrew or MacPorts package managers for easy dependency installation + +
+ + +### With Make + + +1. **Install dependencies (example for Homebrew)** + + ```bash + brew install coreutils make gcc@15 lowdown + ``` + +2. **Clone repository** + + ```bash + git clone https://github.com/aristocratos/btop.git + cd btop + ``` +3. **Compile** + + ```bash + gmake + ``` + + Options for make: + + | Flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `VERBOSE=true` | To display full compiler/linker commands | + | `STATIC=true` | For static compilation (only libgcc and libstdc++) | + | `QUIET=true` | For less verbose output | + | `STRIP=true` | To force stripping of debug symbols (adds `-s` linker flag) | + | `DEBUG=true` | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging | + | `GPU_SUPPORT=` | Enable/disable GPU support (Enabled by default on macOS) | + | `ARCH=` | To manually set the target architecture | + | `ADDFLAGS=` | For appending flags to both compiler and linker | + | `CXX=` | Manually set which compiler to use | + + Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system. + +4. **Install** + + ```bash + sudo gmake install + ``` + + Append `PREFIX=/target/dir` to set target, default: `/usr/local` + + Notice! Only use "sudo" when installing to a NON user owned directory. + +5. **(Recommended) Set suid bit to make btop always run as root (or other user)** + + ```bash + sudo gmake setuid + ``` + + No need for `sudo` to see information for non user owned processes and to enable signal sending to any process. + + Run after make install and use same PREFIX if any was used at install. + + Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel` + +* **Uninstall** + + ```bash + sudo gmake uninstall + ``` + +* **Remove any object files from source dir** + + ```bash + gmake clean + ``` + +* **Remove all object files, binaries and created directories in source dir** + + ```bash + gmake distclean + ``` + +* **Show help** + + ```bash + gmake help + ``` + +
+
+ + +### With CMake (Community maintained) + + +1. **Install build dependencies** + + Requires Clang, CMake, Ninja, Lowdown and Git + + ```bash + brew update --quiet + brew install cmake git llvm ninja lowdown + ``` + +2. **Clone the repository** + + ```bash + git clone https://github.com/aristocratos/btop.git && cd btop + ``` + +3. **Compile** + + ```bash + # Configure + export LLVM_PREFIX="$(brew --prefix llvm)" + export CXX="$LLVM_PREFIX/bin/clang++" + export CPPFLAGS="-I$LLVM_PREFIX/include" + export LDFLAGS="-L$LLVM_PREFIX/lib -L$LLVM_PREFIX/lib/c++ -Wl,-rpath,$LLVM_PREFIX/lib/c++ -fuse-ld=$LLVM_PREFIX/bin/ld64.lld" + cmake -B build -G Ninja + # Build + cmake --build build + ``` + + This will automatically build a release version of btop. + + Some useful options to pass to the configure step: + + | Configure flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `-DBTOP_LTO=` | Enables link time optimization (ON by default) | + | `-DBTOP_GPU=` | Enable GPU support (ON by default) | + | `-DCMAKE_INSTALL_PREFIX=` | The installation prefix ('/usr/local' by default) | + + To force any specific compiler, run `CXX= cmake -B build -G Ninja` + +4. **Install** + + ```bash + cmake --install build + ``` + + May require root privileges + +5. **Uninstall** + + CMake doesn't generate an uninstall target by default. To remove installed files, run + ``` + cat build/install_manifest.txt | xargs rm -irv + ``` + +6. **Cleanup build directory** + + ```bash + cmake --build build -t clean + ``` + +
+ +## Compilation FreeBSD + + Requires at least Clang 19 (default) or GCC 14. + + Note that GNU make (`gmake`) is required to compile on FreeBSD. + +
+ + +### With gmake + + +1. **Install dependencies** + + ```bash + sudo pkg install gmake coreutils git lowdown + ``` + +2. **Clone repository** + + ```bash + git clone https://github.com/aristocratos/btop.git + cd btop + ``` + +3. **Compile** + + ```bash + gmake + ``` + + Options for make: + + | Flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `VERBOSE=true` | To display full compiler/linker commands | + | `STATIC=true` | For static compilation (only libgcc and libstdc++) | + | `QUIET=true` | For less verbose output | + | `STRIP=true` | To force stripping of debug symbols (adds `-s` linker flag) | + | `DEBUG=true` | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging | + | `ARCH=` | To manually set the target architecture | + | `ADDFLAGS=` | For appending flags to both compiler and linker | + | `CXX=` | Manually set which compiler to use | + + Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system. + +4. **Install** + + ```bash + sudo gmake install + ``` + + Append `PREFIX=/target/dir` to set target, default: `/usr/local` + + Notice! Only use "sudo" when installing to a NON user owned directory. + +5. **(Recommended) Set suid bit to make btop always run as root (or other user)** + + ```bash + sudo gmake setuid + ``` + + No need for `sudo` to see information for non user owned processes and to enable signal sending to any process. + + Run after make install and use same PREFIX if any was used at install. + + Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel` + +* **Uninstall** + + ```bash + sudo gmake uninstall + ``` + +* **Remove any object files from source dir** + + ```bash + gmake clean + ``` + +* **Remove all object files, binaries and created directories in source dir** + + ```bash + gmake distclean + ``` + +* **Show help** + + ```bash + gmake help + ``` + +
+
+ + +### With CMake (Community maintained) + + +1. **Install build dependencies** + + Requires Clang / GCC, CMake, Ninja, Lowdown and Git + + ```bash + pkg install cmake ninja lowdown + ``` + +2. **Clone the repository** + + ```bash + git clone https://github.com/aristocratos/btop.git && cd btop + ``` + +3. **Compile** + + ```bash + # Configure + cmake -B build -G Ninja + # Build + cmake --build build + ``` + + This will automatically build a release version of btop. + + Some useful options to pass to the configure step: + + | Configure flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `-DBTOP_STATIC=` | Enables static linking (OFF by default) | + | `-DBTOP_LTO=` | Enables link time optimization (ON by default) | + | `-DCMAKE_INSTALL_PREFIX=` | The installation prefix ('/usr/local' by default) | + + _**Note:** Static linking does not work with GCC._ + + To force any other compiler, run `CXX= cmake -B build -G Ninja` + +4. **Install** + + ```bash + cmake --install build + ``` + + May require root privileges + +5. **Uninstall** + + CMake doesn't generate an uninstall target by default. To remove installed files, run + ``` + cat build/install_manifest.txt | xargs rm -irv + ``` + +6. **Cleanup build directory** + + ```bash + cmake --build build -t clean + ``` + +
+ +## Compilation NetBSD + + Requires at least GCC 14. + + Note that GNU make (`gmake`) is required to compile on NetBSD. + +
+ + +### With gmake + + +1. **Install dependencies** + + ```bash + /usr/sbin/pkg_add pkgin + pkgin install -y coregutils gcc14 git gmake + ``` + +2. **Clone repository** + + ```bash + git clone https://github.com/aristocratos/btop.git + cd btop + ``` + +3. **Compile** + + ```bash + CXX=/usr/pkg/gcc14/bin/g++ gmake CXXFLAGS="-DNDEBUG" + ``` + + Options for make: + + | Flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `VERBOSE=true` | To display full compiler/linker commands | + | `STATIC=true` | For static compilation (only libgcc and libstdc++) | + | `QUIET=true` | For less verbose output | + | `STRIP=true` | To force stripping of debug symbols (adds `-s` linker flag) | + | `DEBUG=true` | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging | + | `ARCH=` | To manually set the target architecture | + | `ADDFLAGS=` | For appending flags to both compiler and linker | + | `CXX=` | Manually set which compiler to use | + + Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system. + +4. **Install** + + ```bash + sudo gmake install + ``` + + Append `PREFIX=/target/dir` to set target, default: `/usr/local` + + Notice! Only use "sudo" when installing to a NON user owned directory. + +5. **(Recommended) Set suid bit to make btop always run as root (or other user)** + + ```bash + sudo gmake setuid + ``` + + No need for `sudo` to see information for non user owned processes and to enable signal sending to any process. + + Run after make install and use same PREFIX if any was used at install. + + Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel` + +* **Uninstall** + + ```bash + sudo gmake uninstall + ``` + +* **Remove any object files from source dir** + + ```bash + gmake clean + ``` + +* **Remove all object files, binaries and created directories in source dir** + + ```bash + gmake distclean + ``` + +* **Show help** + + ```bash + gmake help + ``` + +
+
+ + +### With CMake (Community maintained) + + +1. **Install build dependencies** + + Requires GCC, CMake, Ninja and Git + + ```bash + /usr/sbin/pkg_add pkgin + pkgin install cmake ninja-build gcc14 git + ``` + +2. **Clone the repository** + + ```bash + git clone https://github.com/aristocratos/btop.git && cd btop + ``` + +3. **Compile** + + ```bash + # Configure + CXX="/usr/pkg/gcc14/bin/g++" cmake -B build -G Ninja + # Build + cmake --build build + ``` + + This will automatically build a release version of btop. + + Some useful options to pass to the configure step: + + | Configure flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `-DBTOP_LTO=` | Enables link time optimization (ON by default) | + | `-DCMAKE_INSTALL_PREFIX=` | The installation prefix ('/usr/local' by default) | + + To force any other compiler, run `CXX= cmake -B build -G Ninja` + +4. **Install** + + ```bash + cmake --install build + ``` + + May require root privileges + +5. **Uninstall** + + CMake doesn't generate an uninstall target by default. To remove installed files, run + ``` + cat build/install_manifest.txt | xargs rm -irv + ``` + +6. **Cleanup build directory** + + ```bash + cmake --build build -t clean + ``` + +
+ +## Compilation OpenBSD + + Note that GNU make (`gmake`) is required to compile on OpenBSD. + +
+ + +### With gmake + + +1. **Install dependencies** + + ```bash + pkg_add coreutils git gmake lowdown + ``` + +2. **Clone repository** + + ```bash + git clone https://github.com/aristocratos/btop.git + cd btop + ``` + +3. **Compile** + + ```bash + gmake + ``` + + Options for make: + + | Flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `VERBOSE=true` | To display full compiler/linker commands | + | `STATIC=true` | For static compilation (only libgcc and libstdc++) | + | `QUIET=true` | For less verbose output | + | `STRIP=true` | To force stripping of debug symbols (adds `-s` linker flag) | + | `DEBUG=true` | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging | + | `ARCH=` | To manually set the target architecture | + | `ADDFLAGS=` | For appending flags to both compiler and linker | + | `CXX=` | Manually set which compiler to use | + + Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system. + +4. **Install** + + ```bash + sudo gmake install + ``` + + Append `PREFIX=/target/dir` to set target, default: `/usr/local` + + Notice! Only use "sudo" when installing to a NON user owned directory. + +5. **(Recommended) Set suid bit to make btop always run as root (or other user)** + + ```bash + sudo gmake setuid + ``` + + No need for `sudo` to see information for non user owned processes and to enable signal sending to any process. + + Run after make install and use same PREFIX if any was used at install. + + Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel` + +* **Uninstall** + + ```bash + sudo gmake uninstall + ``` + +* **Remove any object files from source dir** + + ```bash + gmake clean + ``` + +* **Remove all object files, binaries and created directories in source dir** + + ```bash + gmake distclean + ``` + +* **Show help** + + ```bash + gmake help + ``` + +
+
+ + +### With CMake (Community maintained) + + +1. **Install build dependencies** + + Requires GCC, CMake, Ninja, Lowdown and Git + + _**Note:** LLVM's libc++ shipped with OpenBSD 7.4 is too old and cannot compile btop._ + + ```bash + pkg_add cmake git ninja lowdown + ``` + +2. **Clone the repository** + + ```bash + git clone https://github.com/aristocratos/btop.git && cd btop + ``` + +3. **Compile** + + ```bash + # Configure + cmake -B build -G Ninja + # Build + cmake --build build + ``` + + This will automatically build a release version of btop. + + Some useful options to pass to the configure step: + + | Configure flag | Description | + |---------------------------------|-------------------------------------------------------------------------| + | `-DBTOP_LTO=` | Enables link time optimization (ON by default) | + | `-DCMAKE_INSTALL_PREFIX=` | The installation prefix ('/usr/local' by default) | + + To force any other compiler, run `CXX= cmake -B build -G Ninja` + +4. **Install** + + ```bash + cmake --install build + ``` + + May require root privileges + +5. **Uninstall** + + CMake doesn't generate an uninstall target by default. To remove installed files, run + ``` + cat build/install_manifest.txt | xargs rm -irv + ``` + +6. **Cleanup build directory** + + ```bash + cmake --build build -t clean + ``` + +
+ +## Testing + +Testing requires [CMake](cmake.org). Tests are build by default and can be run with `ctest --test-dir `. + +If you want to disable building tests, pass `-DBUILD_TESTING=OFF` to the configure step. + +## Installing the snap +[![btop](https://snapcraft.io/btop/badge.svg)](https://snapcraft.io/btop) + +### Note: there are now two snaps available: `btop` and `btop-desktop`. The desktop version is much larger and includes the desktop entries needed to allow for launching `btop` with a click. + + * **Install the snap** + + ```bash + sudo snap install btop + or + sudo snap install btop-desktop + ``` + * **Install the latest snap from the edge channel** + ``` + sudo snap install btop --edge + or + sudo snap install btop-desktop --edge + ``` + + * **Connect the interface** + + ```bash + sudo snap connect btop:removable-media + or + sudo snap connect btop-desktop:removable-media + ``` + +## Configurability + +All options changeable from within UI. +Config and log files stored in `$XDG_CONFIG_HOME/btop` or `$HOME/.config/btop` folder + +#### btop.conf: (auto generated if not found) + +```toml +#? Config file for btop v.1.4.5 + +#* Name of a btop++/bpytop/bashtop formatted ".theme" file, "Default" and "TTY" for builtin themes. +#* Themes should be placed in "../share/btop/themes" relative to binary or "$HOME/.config/btop/themes" +color_theme = "Default" + +#* If the theme set background should be shown, set to False if you want terminal background transparency. +theme_background = true + +#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false. +truecolor = true + +#* Set to true to force tty mode regardless if a real tty has been detected or not. +#* Will force 16-color mode and TTY theme, set all graph symbols to "tty" and swap out other non tty friendly symbols. +force_tty = false + +#* Define presets for the layout of the boxes. Preset 0 is always all boxes shown with default settings. Max 9 presets. +#* Format: "box_name:P:G,box_name:P:G" P=(0 or 1) for alternate positions, G=graph symbol to use for box. +#* Use whitespace " " as separator between different presets. +#* Example: "cpu:0:default,mem:0:tty,proc:1:default cpu:0:braille,proc:0:tty" +presets = "cpu:1:default,proc:0:default cpu:0:default,mem:0:default,net:0:default cpu:0:block,net:0:tty" + +#* Set to True to enable "h,j,k,l,g,G" keys for directional control in lists. +#* Conflicting keys for h:"help" and k:"kill" is accessible while holding shift. +vim_keys = false + +#* Rounded corners on boxes, is ignored if TTY mode is ON. +rounded_corners = true + +#* Use terminal synchronized output sequences to reduce flickering on supported terminals. +terminal_sync = true + +#* Default symbols to use for graph creation, "braille", "block" or "tty". +#* "braille" offers the highest resolution but might not be included in all fonts. +#* "block" has half the resolution of braille but uses more common characters. +#* "tty" uses only 3 different symbols but will work with most fonts and should work in a real TTY. +#* Note that "tty" only has half the horizontal resolution of the other two, so will show a shorter historical view. +graph_symbol = "braille" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_cpu = "default" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_mem = "default" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_net = "default" + +# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty". +graph_symbol_proc = "default" + +#* Manually set which boxes to show. Available values are "cpu mem net proc" and "gpu0" through "gpu5", separate values with whitespace. +shown_boxes = "cpu mem net proc" + +#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs. +update_ms = 2000 + +#* Processes sorting, "pid" "program" "arguments" "threads" "user" "memory" "cpu lazy" "cpu direct", +#* "cpu lazy" sorts top process over time (easier to follow), "cpu direct" updates top process directly. +proc_sorting = "cpu lazy" + +#* Reverse sorting order, True or False. +proc_reversed = false + +#* Show processes as a tree. +proc_tree = false + +#* Use the cpu graph colors in the process list. +proc_colors = true + +#* Use a darkening gradient in the process list. +proc_gradient = true + +#* If process cpu usage should be of the core it's running on or usage of the total available cpu power. +proc_per_core = false + +#* Show process memory as bytes instead of percent. +proc_mem_bytes = true + +#* Show cpu graph for each process. +proc_cpu_graphs = true + +#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate) +proc_info_smaps = false + +#* Show proc box on left side of screen instead of right. +proc_left = false + +#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop). +proc_filter_kernel = false + +#* Should the process list follow the selected process when detailed view is open. +proc_follow_detailed = true + +#* In tree-view, always accumulate child process resources in the parent process. +proc_aggregate = false + +#* In tree-view, auto-collapse processes with this many or more direct children when +#* entering tree mode. 0 to disable. Useful for collapsing multi-process apps like browsers. +proc_tree_auto_collapse = 0 + +#* Should cpu and memory usage display be preserved for dead processes when paused. +keep_dead_proc_usage = false + +#* Sets the CPU stat shown in upper half of the CPU graph, "total" is always available. +#* Select from a list of detected attributes from the options menu. +cpu_graph_upper = "Auto" + +#* Sets the CPU stat shown in lower half of the CPU graph, "total" is always available. +#* Select from a list of detected attributes from the options menu. +cpu_graph_lower = "Auto" + +#* Toggles if the lower CPU graph should be inverted. +cpu_invert_lower = true + +#* Set to True to completely disable the lower CPU graph. +cpu_single_graph = false + +#* Show cpu box at bottom of screen instead of top. +cpu_bottom = false + +#* Shows the system uptime in the CPU box. +show_uptime = true + +#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo. +show_cpu_watts = true + +#* Show cpu temperature. +check_temp = true + +#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors. +cpu_sensor = "Auto" + +#* Show temperatures for cpu cores also if check_temp is True and sensors has been found. +show_coretemp = true + +#* Set a custom mapping between core and coretemp, can be needed on certain cpus to get correct temperature for correct core. +#* Use lm-sensors or similar to see which cores are reporting temperatures on your machine. +#* Format "x:y" x=core with wrong temp, y=core with correct temp, use space as separator between multiple entries. +#* Example: "4:0 5:1 6:3" +cpu_core_map = "" + +#* Which temperature scale to use, available values: "celsius", "fahrenheit", "kelvin" and "rankine". +temp_scale = "celsius" + +#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024. +base_10_sizes = false + +#* Show CPU frequency. +show_cpu_freq = true + +#* How to calculate CPU frequency, available values: "first", "range", "lowest", "highest" and "average". +freq_mode = "first" + +#* Draw a clock at top of screen, formatting according to strftime, empty string to disable. +#* Special formatting: /host = hostname | /user = username | /uptime = system uptime +clock_format = "%X" + +#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort. +background_update = true + +#* Custom cpu model name, empty string to disable. +custom_cpu_name = "" + +#* Optional filter for shown disks, should be full path of a mountpoint, separate multiple values with whitespace " ". +#* Only disks matching the filter will be shown. Prepend exclude= to only show disks not matching the filter. Examples: disks_filter="/boot /home/user", disks_filter="exclude=/boot /home/user" +disks_filter = "" + +#* Show graphs instead of meters for memory values. +mem_graphs = true + +#* Show mem box below net box instead of above. +mem_below_net = false + +#* Count ZFS ARC in cached and available memory. +zfs_arc_cached = true + +#* If swap memory should be shown in memory box. +show_swap = true + +#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk. +swap_disk = true + +#* If mem box should be split to also show disks info. +show_disks = true + +#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar. +only_physical = true + +#* Read disks list from /etc/fstab. This also disables only_physical. +use_fstab = true + +#* Setting this to True will hide all datasets, and only show ZFS pools. (IO stats will be calculated per-pool) +zfs_hide_datasets = false + +#* Set to true to show available disk space for privileged users. +disk_free_priv = false + +#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view. +show_io_stat = true + +#* Toggles io mode for disks, showing big graphs for disk read/write speeds. +io_mode = false + +#* Set to True to show combined read/write io graphs in io mode. +io_graph_combined = false + +#* Set the top speed for the io graphs in MiB/s (100 by default), use format "mountpoint:speed" separate disks with whitespace " ". +#* Example: "/mnt/media:100 /:20 /boot:1". +io_graph_speeds = "" + +#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False. +net_download = 100 + +net_upload = 100 + +#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest. +net_auto = true + +#* Sync the auto scaling for download and upload to whichever currently has the highest scale. +net_sync = true + +#* Starts with the Network Interface specified here. +net_iface = "" + +#* "True" shows bitrates in base 10 (Kbps, Mbps). "False" shows bitrates in binary sizes (Kibps, Mibps, etc.). "Auto" uses base_10_sizes. +base_10_bitrate = "Auto" + +#* Show battery stats in top right if battery is present. +show_battery = true + +#* Which battery to use if multiple are present. "Auto" for auto detection. +selected_battery = "Auto" + +#* Show power stats of battery next to charge indicator. +show_battery_watts = true + +#* Set loglevel for "~/.local/state/btop.log" levels are: "ERROR" "WARNING" "INFO" "DEBUG". +#* The level set includes all lower levels, i.e. "DEBUG" will show all logging info. +log_level = "WARNING" +``` + +#### Command line options + +```text +Usage: btop [OPTIONS] + +Options: + -c, --config Path to a config file + -d, --debug Start in debug mode with additional logs and metrics + -f, --filter Set an initial process filter + --force-utf Override automatic UTF locale detection + -l, --low-color Disable true color, 256 colors only + -p, --preset Start with a preset (0-9) + -t, --tty Force tty mode with ANSI graph symbols and 16 colors only + --no-tty Force disable tty mode + -u, --update Set an initial update rate in milliseconds + --default-config Print default config to standard output + -h, --help Show this help message and exit + -V, --version Show a version message and exit (more with --version) +``` + +## LICENSE + +[Apache License 2.0](LICENSE) diff --git a/vendor/btop/include/fmt/LICENSE.rst b/vendor/btop/include/fmt/LICENSE.rst new file mode 100644 index 000000000..1cd1ef926 --- /dev/null +++ b/vendor/btop/include/fmt/LICENSE.rst @@ -0,0 +1,27 @@ +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. diff --git a/vendor/btop/include/fmt/args.h b/vendor/btop/include/fmt/args.h new file mode 100644 index 000000000..5e5f40f9e --- /dev/null +++ b/vendor/btop/include/fmt/args.h @@ -0,0 +1,220 @@ +// Formatting library for C++ - dynamic argument lists +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_ARGS_H_ +#define FMT_ARGS_H_ + +#ifndef FMT_MODULE +# include // std::reference_wrapper +# include // std::unique_ptr +# include +#endif + +#include "format.h" // std_string_view + +FMT_BEGIN_NAMESPACE +namespace detail { + +template struct is_reference_wrapper : std::false_type {}; +template +struct is_reference_wrapper> : std::true_type {}; + +template auto unwrap(const T& v) -> const T& { return v; } +template +auto unwrap(const std::reference_wrapper& v) -> const T& { + return static_cast(v); +} + +// node is defined outside dynamic_arg_list to workaround a C2504 bug in MSVC +// 2022 (v17.10.0). +// +// Workaround for clang's -Wweak-vtables. Unlike for regular classes, for +// templates it doesn't complain about inability to deduce single translation +// unit for placing vtable. So node is made a fake template. +template struct node { + virtual ~node() = default; + std::unique_ptr> next; +}; + +class dynamic_arg_list { + template struct typed_node : node<> { + T value; + + template + FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {} + + template + FMT_CONSTEXPR typed_node(const basic_string_view& arg) + : value(arg.data(), arg.size()) {} + }; + + std::unique_ptr> head_; + + public: + template auto push(const Arg& arg) -> const T& { + auto new_node = std::unique_ptr>(new typed_node(arg)); + auto& value = new_node->value; + new_node->next = std::move(head_); + head_ = std::move(new_node); + return value; + } +}; +} // namespace detail + +/** + * A dynamic list of formatting arguments with storage. + * + * It can be implicitly converted into `fmt::basic_format_args` for passing + * into type-erased formatting functions such as `fmt::vformat`. + */ +FMT_EXPORT template class dynamic_format_arg_store { + private: + using char_type = typename Context::char_type; + + template struct need_copy { + static constexpr detail::type mapped_type = + detail::mapped_type_constant::value; + + enum { + value = !(detail::is_reference_wrapper::value || + std::is_same>::value || + std::is_same>::value || + (mapped_type != detail::type::cstring_type && + mapped_type != detail::type::string_type && + mapped_type != detail::type::custom_type)) + }; + }; + + template + using stored_t = conditional_t< + std::is_convertible>::value && + !detail::is_reference_wrapper::value, + std::basic_string, T>; + + // Storage of basic_format_arg must be contiguous. + std::vector> data_; + std::vector> named_info_; + + // Storage of arguments not fitting into basic_format_arg must grow + // without relocation because items in data_ refer to it. + detail::dynamic_arg_list dynamic_args_; + + friend class basic_format_args; + + auto data() const -> const basic_format_arg* { + return named_info_.empty() ? data_.data() : data_.data() + 1; + } + + template void emplace_arg(const T& arg) { + data_.emplace_back(arg); + } + + template + void emplace_arg(const detail::named_arg& arg) { + if (named_info_.empty()) + data_.insert(data_.begin(), basic_format_arg(nullptr, 0)); + data_.emplace_back(detail::unwrap(arg.value)); + auto pop_one = [](std::vector>* data) { + data->pop_back(); + }; + std::unique_ptr>, decltype(pop_one)> + guard{&data_, pop_one}; + named_info_.push_back({arg.name, static_cast(data_.size() - 2u)}); + data_[0] = {named_info_.data(), named_info_.size()}; + guard.release(); + } + + public: + constexpr dynamic_format_arg_store() = default; + + operator basic_format_args() const { + return basic_format_args(data(), static_cast(data_.size()), + !named_info_.empty()); + } + + /** + * Adds an argument into the dynamic store for later passing to a formatting + * function. + * + * Note that custom types and string types (but not string views) are copied + * into the store dynamically allocating memory if necessary. + * + * **Example**: + * + * fmt::dynamic_format_arg_store store; + * store.push_back(42); + * store.push_back("abc"); + * store.push_back(1.5f); + * std::string result = fmt::vformat("{} and {} and {}", store); + */ + template void push_back(const T& arg) { + if (detail::const_check(need_copy::value)) + emplace_arg(dynamic_args_.push>(arg)); + else + emplace_arg(detail::unwrap(arg)); + } + + /** + * Adds a reference to the argument into the dynamic store for later passing + * to a formatting function. + * + * **Example**: + * + * fmt::dynamic_format_arg_store store; + * char band[] = "Rolling Stones"; + * store.push_back(std::cref(band)); + * band[9] = 'c'; // Changing str affects the output. + * std::string result = fmt::vformat("{}", store); + * // result == "Rolling Scones" + */ + template void push_back(std::reference_wrapper arg) { + static_assert( + need_copy::value, + "objects of built-in types and string views are always copied"); + emplace_arg(arg.get()); + } + + /** + * Adds named argument into the dynamic store for later passing to a + * formatting function. `std::reference_wrapper` is supported to avoid + * copying of the argument. The name is always copied into the store. + */ + template + void push_back(const detail::named_arg& arg) { + const char_type* arg_name = + dynamic_args_.push>(arg.name).c_str(); + if (detail::const_check(need_copy::value)) { + emplace_arg( + fmt::arg(arg_name, dynamic_args_.push>(arg.value))); + } else { + emplace_arg(fmt::arg(arg_name, arg.value)); + } + } + + /// Erase all elements from the store. + void clear() { + data_.clear(); + named_info_.clear(); + dynamic_args_ = {}; + } + + /// Reserves space to store at least `new_cap` arguments including + /// `new_cap_named` named arguments. + void reserve(size_t new_cap, size_t new_cap_named) { + FMT_ASSERT(new_cap >= new_cap_named, + "set of arguments includes set of named arguments"); + data_.reserve(new_cap); + named_info_.reserve(new_cap_named); + } + + /// Returns the number of elements in the store. + auto size() const noexcept -> size_t { return data_.size(); } +}; + +FMT_END_NAMESPACE + +#endif // FMT_ARGS_H_ diff --git a/vendor/btop/include/fmt/base.h b/vendor/btop/include/fmt/base.h new file mode 100644 index 000000000..42e192aca --- /dev/null +++ b/vendor/btop/include/fmt/base.h @@ -0,0 +1,2994 @@ +// Formatting library for C++ - the base API for char/UTF-8 +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_BASE_H_ +#define FMT_BASE_H_ + +#if defined(FMT_IMPORT_STD) && !defined(FMT_MODULE) +# define FMT_MODULE +#endif + +#ifndef FMT_MODULE +# include // CHAR_BIT +# include // FILE +# include // memcmp + +# include // std::enable_if +#endif + +// The fmt library version in the form major * 10000 + minor * 100 + patch. +#define FMT_VERSION 120000 + +// Detect compiler versions. +#if defined(__clang__) && !defined(__ibmxl__) +# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#else +# define FMT_CLANG_VERSION 0 +#endif +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define FMT_GCC_VERSION 0 +#endif +#if defined(__ICL) +# define FMT_ICC_VERSION __ICL +#elif defined(__INTEL_COMPILER) +# define FMT_ICC_VERSION __INTEL_COMPILER +#else +# define FMT_ICC_VERSION 0 +#endif +#if defined(_MSC_VER) +# define FMT_MSC_VERSION _MSC_VER +#else +# define FMT_MSC_VERSION 0 +#endif + +// Detect standard library versions. +#ifdef _GLIBCXX_RELEASE +# define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE +#else +# define FMT_GLIBCXX_RELEASE 0 +#endif +#ifdef _LIBCPP_VERSION +# define FMT_LIBCPP_VERSION _LIBCPP_VERSION +#else +# define FMT_LIBCPP_VERSION 0 +#endif + +#ifdef _MSVC_LANG +# define FMT_CPLUSPLUS _MSVC_LANG +#else +# define FMT_CPLUSPLUS __cplusplus +#endif + +// Detect __has_*. +#ifdef __has_feature +# define FMT_HAS_FEATURE(x) __has_feature(x) +#else +# define FMT_HAS_FEATURE(x) 0 +#endif +#ifdef __has_include +# define FMT_HAS_INCLUDE(x) __has_include(x) +#else +# define FMT_HAS_INCLUDE(x) 0 +#endif +#ifdef __has_builtin +# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#else +# define FMT_HAS_BUILTIN(x) 0 +#endif +#ifdef __has_cpp_attribute +# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#endif + +#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \ + (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \ + (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +// Detect C++14 relaxed constexpr. +#ifdef FMT_USE_CONSTEXPR +// Use the provided definition. +#elif FMT_GCC_VERSION >= 702 && FMT_CPLUSPLUS >= 201402L +// GCC only allows constexpr member functions in non-literal types since 7.2: +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66297. +# define FMT_USE_CONSTEXPR 1 +#elif FMT_ICC_VERSION +# define FMT_USE_CONSTEXPR 0 // https://github.com/fmtlib/fmt/issues/1628 +#elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 +# define FMT_USE_CONSTEXPR 1 +#else +# define FMT_USE_CONSTEXPR 0 +#endif +#if FMT_USE_CONSTEXPR +# define FMT_CONSTEXPR constexpr +#else +# define FMT_CONSTEXPR +#endif + +// Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated. +#if !defined(__cpp_lib_is_constant_evaluated) +# define FMT_USE_CONSTEVAL 0 +#elif FMT_CPLUSPLUS < 201709L +# define FMT_USE_CONSTEVAL 0 +#elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10 +# define FMT_USE_CONSTEVAL 0 +#elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000 +# define FMT_USE_CONSTEVAL 0 +#elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L +# define FMT_USE_CONSTEVAL 0 // consteval is broken in Apple clang < 14. +#elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929 +# define FMT_USE_CONSTEVAL 0 // consteval is broken in MSVC VS2019 < 16.10. +#elif defined(__cpp_consteval) +# define FMT_USE_CONSTEVAL 1 +#elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101 +# define FMT_USE_CONSTEVAL 1 +#else +# define FMT_USE_CONSTEVAL 0 +#endif +#if FMT_USE_CONSTEVAL +# define FMT_CONSTEVAL consteval +# define FMT_CONSTEXPR20 constexpr +#else +# define FMT_CONSTEVAL +# define FMT_CONSTEXPR20 +#endif + +// Check if exceptions are disabled. +#ifdef FMT_USE_EXCEPTIONS +// Use the provided definition. +#elif defined(__GNUC__) && !defined(__EXCEPTIONS) +# define FMT_USE_EXCEPTIONS 0 +#elif defined(__clang__) && !defined(__cpp_exceptions) +# define FMT_USE_EXCEPTIONS 0 +#elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS +# define FMT_USE_EXCEPTIONS 0 +#else +# define FMT_USE_EXCEPTIONS 1 +#endif +#if FMT_USE_EXCEPTIONS +# define FMT_TRY try +# define FMT_CATCH(x) catch (x) +#else +# define FMT_TRY if (true) +# define FMT_CATCH(x) if (false) +#endif + +#ifdef FMT_NO_UNIQUE_ADDRESS +// Use the provided definition. +#elif FMT_CPLUSPLUS < 202002L +// Not supported. +#elif FMT_HAS_CPP_ATTRIBUTE(no_unique_address) +# define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]] +// VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485). +#elif FMT_MSC_VERSION >= 1929 && !FMT_CLANG_VERSION +# define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]] +#endif +#ifndef FMT_NO_UNIQUE_ADDRESS +# define FMT_NO_UNIQUE_ADDRESS +#endif + +#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough) +# define FMT_FALLTHROUGH [[fallthrough]] +#elif defined(__clang__) +# define FMT_FALLTHROUGH [[clang::fallthrough]] +#elif FMT_GCC_VERSION >= 700 && \ + (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520) +# define FMT_FALLTHROUGH [[gnu::fallthrough]] +#else +# define FMT_FALLTHROUGH +#endif + +// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings. +#if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__) +# define FMT_NORETURN [[noreturn]] +#else +# define FMT_NORETURN +#endif + +#ifdef FMT_NODISCARD +// Use the provided definition. +#elif FMT_HAS_CPP17_ATTRIBUTE(nodiscard) +# define FMT_NODISCARD [[nodiscard]] +#else +# define FMT_NODISCARD +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_VISIBILITY(value) __attribute__((visibility(value))) +#else +# define FMT_VISIBILITY(value) +#endif + +// Detect pragmas. +#define FMT_PRAGMA_IMPL(x) _Pragma(#x) +#if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER) +// Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884 +// and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582. +# define FMT_PRAGMA_GCC(x) FMT_PRAGMA_IMPL(GCC x) +#else +# define FMT_PRAGMA_GCC(x) +#endif +#if FMT_CLANG_VERSION +# define FMT_PRAGMA_CLANG(x) FMT_PRAGMA_IMPL(clang x) +#else +# define FMT_PRAGMA_CLANG(x) +#endif +#if FMT_MSC_VERSION +# define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__)) +#else +# define FMT_MSC_WARNING(...) +#endif + +// Enable minimal optimizations for more compact code in debug mode. +FMT_PRAGMA_GCC(push_options) +#if !defined(__OPTIMIZE__) && !defined(__CUDACC__) && !defined(FMT_MODULE) +FMT_PRAGMA_GCC(optimize("Og")) +# define FMT_GCC_OPTIMIZED +#endif +FMT_PRAGMA_CLANG(diagnostic push) + +#ifdef FMT_ALWAYS_INLINE +// Use the provided definition. +#elif FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_ALWAYS_INLINE inline __attribute__((always_inline)) +#else +# define FMT_ALWAYS_INLINE inline +#endif +// A version of FMT_ALWAYS_INLINE to prevent code bloat in debug mode. +#if defined(NDEBUG) || defined(FMT_GCC_OPTIMIZED) +# define FMT_INLINE FMT_ALWAYS_INLINE +#else +# define FMT_INLINE inline +#endif + +#ifndef FMT_BEGIN_NAMESPACE +# define FMT_BEGIN_NAMESPACE \ + namespace fmt { \ + inline namespace v12 { +# define FMT_END_NAMESPACE \ + } \ + } +#endif + +#ifndef FMT_EXPORT +# define FMT_EXPORT +# define FMT_BEGIN_EXPORT +# define FMT_END_EXPORT +#endif + +#ifdef _WIN32 +# define FMT_WIN32 1 +#else +# define FMT_WIN32 0 +#endif + +#if !defined(FMT_HEADER_ONLY) && FMT_WIN32 +# if defined(FMT_LIB_EXPORT) +# define FMT_API __declspec(dllexport) +# elif defined(FMT_SHARED) +# define FMT_API __declspec(dllimport) +# endif +#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) +# define FMT_API FMT_VISIBILITY("default") +#endif +#ifndef FMT_API +# define FMT_API +#endif + +#ifndef FMT_OPTIMIZE_SIZE +# define FMT_OPTIMIZE_SIZE 0 +#endif + +// FMT_BUILTIN_TYPE=0 may result in smaller library size at the cost of higher +// per-call binary size by passing built-in types through the extension API. +#ifndef FMT_BUILTIN_TYPES +# define FMT_BUILTIN_TYPES 1 +#endif + +#define FMT_APPLY_VARIADIC(expr) \ + using unused = int[]; \ + (void)unused { 0, (expr, 0)... } + +FMT_BEGIN_NAMESPACE + +// Implementations of enable_if_t and other metafunctions for older systems. +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; +template using bool_constant = std::integral_constant; +template +using remove_reference_t = typename std::remove_reference::type; +template +using remove_const_t = typename std::remove_const::type; +template +using remove_cvref_t = typename std::remove_cv>::type; +template +using make_unsigned_t = typename std::make_unsigned::type; +template +using underlying_t = typename std::underlying_type::type; +template using decay_t = typename std::decay::type; +using nullptr_t = decltype(nullptr); + +#if (FMT_GCC_VERSION && FMT_GCC_VERSION < 500) || FMT_MSC_VERSION +// A workaround for gcc 4.9 & MSVC v141 to make void_t work in a SFINAE context. +template struct void_t_impl { + using type = void; +}; +template using void_t = typename void_t_impl::type; +#else +template using void_t = void; +#endif + +struct monostate { + constexpr monostate() {} +}; + +// An enable_if helper to be used in template parameters which results in much +// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed +// to workaround a bug in MSVC 2019 (see #1140 and #1186). +#ifdef FMT_DOC +# define FMT_ENABLE_IF(...) +#else +# define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0 +#endif + +template constexpr auto min_of(T a, T b) -> T { + return a < b ? a : b; +} +template constexpr auto max_of(T a, T b) -> T { + return a > b ? a : b; +} + +FMT_NORETURN FMT_API void assert_fail(const char* file, int line, + const char* message); + +namespace detail { +// Suppresses "unused variable" warnings with the method described in +// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/. +// (void)var does not work on many Intel compilers. +template FMT_CONSTEXPR void ignore_unused(const T&...) {} + +constexpr auto is_constant_evaluated(bool default_value = false) noexcept + -> bool { +// Workaround for incompatibility between clang 14 and libstdc++ consteval-based +// std::is_constant_evaluated: https://github.com/fmtlib/fmt/issues/3247. +#if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \ + (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500) + ignore_unused(default_value); + return __builtin_is_constant_evaluated(); +#elif defined(__cpp_lib_is_constant_evaluated) + ignore_unused(default_value); + return std::is_constant_evaluated(); +#else + return default_value; +#endif +} + +// Suppresses "conditional expression is constant" warnings. +template FMT_ALWAYS_INLINE constexpr auto const_check(T val) -> T { + return val; +} + +FMT_NORETURN FMT_API void assert_fail(const char* file, int line, + const char* message); + +#if defined(FMT_ASSERT) +// Use the provided definition. +#elif defined(NDEBUG) +// FMT_ASSERT is not empty to avoid -Wempty-body. +# define FMT_ASSERT(condition, message) \ + fmt::detail::ignore_unused((condition), (message)) +#else +# define FMT_ASSERT(condition, message) \ + ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ + ? (void)0 \ + : ::fmt::assert_fail(__FILE__, __LINE__, (message))) +#endif + +#ifdef FMT_USE_INT128 +// Use the provided definition. +#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \ + !(FMT_CLANG_VERSION && FMT_MSC_VERSION) +# define FMT_USE_INT128 1 +using int128_opt = __int128_t; // An optional native 128-bit integer. +using uint128_opt = __uint128_t; +inline auto map(int128_opt x) -> int128_opt { return x; } +inline auto map(uint128_opt x) -> uint128_opt { return x; } +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +enum class int128_opt {}; +enum class uint128_opt {}; +// Reduce template instantiations. +inline auto map(int128_opt) -> monostate { return {}; } +inline auto map(uint128_opt) -> monostate { return {}; } +#endif + +#ifndef FMT_USE_BITINT +# define FMT_USE_BITINT (FMT_CLANG_VERSION >= 1500) +#endif + +#if FMT_USE_BITINT +FMT_PRAGMA_CLANG(diagnostic ignored "-Wbit-int-extension") +template using bitint = _BitInt(N); +template using ubitint = unsigned _BitInt(N); +#else +template struct bitint {}; +template struct ubitint {}; +#endif // FMT_USE_BITINT + +// Casts a nonnegative integer to unsigned. +template +FMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t { + FMT_ASSERT(std::is_unsigned::value || value >= 0, "negative value"); + return static_cast>(value); +} + +template +using unsigned_char = conditional_t; + +// A heuristic to detect std::string and std::[experimental::]string_view. +// It is mainly used to avoid dependency on <[experimental/]string_view>. +template +struct is_std_string_like : std::false_type {}; +template +struct is_std_string_like().find_first_of( + typename T::value_type(), 0))>> + : std::is_convertible().data()), + const typename T::value_type*> {}; + +// Check if the literal encoding is UTF-8. +enum { is_utf8_enabled = "\u00A7"[1] == '\xA7' }; +enum { use_utf8 = !FMT_WIN32 || is_utf8_enabled }; + +#ifndef FMT_UNICODE +# define FMT_UNICODE 1 +#endif + +static_assert(!FMT_UNICODE || use_utf8, + "Unicode support requires compiling with /utf-8"); + +template constexpr auto narrow(T*) -> char* { return nullptr; } +constexpr FMT_ALWAYS_INLINE auto narrow(const char* s) -> const char* { + return s; +} + +template +FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, size_t n) -> int { + if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n); + for (; n != 0; ++s1, ++s2, --n) { + if (*s1 < *s2) return -1; + if (*s1 > *s2) return 1; + } + return 0; +} + +namespace adl { +using namespace std; + +template +auto invoke_back_inserter() + -> decltype(back_inserter(std::declval())); +} // namespace adl + +template +struct is_back_insert_iterator : std::false_type {}; + +template +struct is_back_insert_iterator< + It, bool_constant()), + It>::value>> : std::true_type {}; + +// Extracts a reference to the container from *insert_iterator. +template +inline FMT_CONSTEXPR20 auto get_container(OutputIt it) -> + typename OutputIt::container_type& { + struct accessor : OutputIt { + FMT_CONSTEXPR20 accessor(OutputIt base) : OutputIt(base) {} + using OutputIt::container; + }; + return *accessor(it).container; +} +} // namespace detail + +// Parsing-related public API and forward declarations. +FMT_BEGIN_EXPORT + +/** + * An implementation of `std::basic_string_view` for pre-C++17. It provides a + * subset of the API. `fmt::basic_string_view` is used for format strings even + * if `std::basic_string_view` is available to prevent issues when a library is + * compiled with a different `-std` option than the client code (which is not + * recommended). + */ +template class basic_string_view { + private: + const Char* data_; + size_t size_; + + public: + using value_type = Char; + using iterator = const Char*; + + constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {} + + /// Constructs a string view object from a C string and a size. + constexpr basic_string_view(const Char* s, size_t count) noexcept + : data_(s), size_(count) {} + + constexpr basic_string_view(nullptr_t) = delete; + + /// Constructs a string view object from a C string. +#if FMT_GCC_VERSION + FMT_ALWAYS_INLINE +#endif + FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) { +#if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION + if (std::is_same::value && !detail::is_constant_evaluated()) { + size_ = __builtin_strlen(detail::narrow(s)); // strlen is not constexpr. + return; + } +#endif + size_t len = 0; + while (*s++) ++len; + size_ = len; + } + + /// Constructs a string view from a `std::basic_string` or a + /// `std::basic_string_view` object. + template ::value&& std::is_same< + typename S::value_type, Char>::value)> + FMT_CONSTEXPR basic_string_view(const S& s) noexcept + : data_(s.data()), size_(s.size()) {} + + /// Returns a pointer to the string data. + constexpr auto data() const noexcept -> const Char* { return data_; } + + /// Returns the string size. + constexpr auto size() const noexcept -> size_t { return size_; } + + constexpr auto begin() const noexcept -> iterator { return data_; } + constexpr auto end() const noexcept -> iterator { return data_ + size_; } + + constexpr auto operator[](size_t pos) const noexcept -> const Char& { + return data_[pos]; + } + + FMT_CONSTEXPR void remove_prefix(size_t n) noexcept { + data_ += n; + size_ -= n; + } + + FMT_CONSTEXPR auto starts_with(basic_string_view sv) const noexcept + -> bool { + return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0; + } + FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool { + return size_ >= 1 && *data_ == c; + } + FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool { + return starts_with(basic_string_view(s)); + } + + FMT_CONSTEXPR auto compare(basic_string_view other) const -> int { + int result = + detail::compare(data_, other.data_, min_of(size_, other.size_)); + if (result != 0) return result; + return size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + } + + FMT_CONSTEXPR friend auto operator==(basic_string_view lhs, + basic_string_view rhs) -> bool { + return lhs.compare(rhs) == 0; + } + friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) != 0; + } + friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) < 0; + } + friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) <= 0; + } + friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) > 0; + } + friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) >= 0; + } +}; + +using string_view = basic_string_view; + +template class basic_appender; +using appender = basic_appender; + +// Checks whether T is a container with contiguous storage. +template struct is_contiguous : std::false_type {}; + +class context; +template class generic_context; +template class parse_context; + +// Longer aliases for C++20 compatibility. +template using basic_format_parse_context = parse_context; +using format_parse_context = parse_context; +template +using basic_format_context = + conditional_t::value, context, + generic_context>; +using format_context = context; + +template +using buffered_context = + conditional_t::value, context, + generic_context, Char>>; + +template class basic_format_arg; +template class basic_format_args; + +// A separate type would result in shorter symbols but break ABI compatibility +// between clang and gcc on ARM (#1919). +using format_args = basic_format_args; + +// A formatter for objects of type T. +template +struct formatter { + // A deleted default constructor indicates a disabled formatter. + formatter() = delete; +}; + +/// Reports a format error at compile time or, via a `format_error` exception, +/// at runtime. +// This function is intentionally not constexpr to give a compile-time error. +FMT_NORETURN FMT_API void report_error(const char* message); + +enum class presentation_type : unsigned char { + // Common specifiers: + none = 0, + debug = 1, // '?' + string = 2, // 's' (string, bool) + + // Integral, bool and character specifiers: + dec = 3, // 'd' + hex, // 'x' or 'X' + oct, // 'o' + bin, // 'b' or 'B' + chr, // 'c' + + // String and pointer specifiers: + pointer = 3, // 'p' + + // Floating-point specifiers: + exp = 1, // 'e' or 'E' (1 since there is no FP debug presentation) + fixed, // 'f' or 'F' + general, // 'g' or 'G' + hexfloat // 'a' or 'A' +}; + +enum class align { none, left, right, center, numeric }; +enum class sign { none, minus, plus, space }; +enum class arg_id_kind { none, index, name }; + +// Basic format specifiers for built-in and string types. +class basic_specs { + private: + // Data is arranged as follows: + // + // 0 1 2 3 + // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + // |type |align| w | p | s |u|#|L| f | unused | + // +-----+-----+---+---+---+-+-+-+-----+---------------------------+ + // + // w - dynamic width info + // p - dynamic precision info + // s - sign + // u - uppercase (e.g. 'X' for 'x') + // # - alternate form ('#') + // L - localized + // f - fill size + // + // Bitfields are not used because of compiler bugs such as gcc bug 61414. + enum : unsigned { + type_mask = 0x00007, + align_mask = 0x00038, + width_mask = 0x000C0, + precision_mask = 0x00300, + sign_mask = 0x00C00, + uppercase_mask = 0x01000, + alternate_mask = 0x02000, + localized_mask = 0x04000, + fill_size_mask = 0x38000, + + align_shift = 3, + width_shift = 6, + precision_shift = 8, + sign_shift = 10, + fill_size_shift = 15, + + max_fill_size = 4 + }; + + unsigned data_ = 1 << fill_size_shift; + static_assert(sizeof(basic_specs::data_) * CHAR_BIT >= 18, ""); + + // Character (code unit) type is erased to prevent template bloat. + char fill_data_[max_fill_size] = {' '}; + + FMT_CONSTEXPR void set_fill_size(size_t size) { + data_ = (data_ & ~fill_size_mask) | + (static_cast(size) << fill_size_shift); + } + + public: + constexpr auto type() const -> presentation_type { + return static_cast(data_ & type_mask); + } + FMT_CONSTEXPR void set_type(presentation_type t) { + data_ = (data_ & ~type_mask) | static_cast(t); + } + + constexpr auto align() const -> align { + return static_cast((data_ & align_mask) >> align_shift); + } + FMT_CONSTEXPR void set_align(fmt::align a) { + data_ = (data_ & ~align_mask) | (static_cast(a) << align_shift); + } + + constexpr auto dynamic_width() const -> arg_id_kind { + return static_cast((data_ & width_mask) >> width_shift); + } + FMT_CONSTEXPR void set_dynamic_width(arg_id_kind w) { + data_ = (data_ & ~width_mask) | (static_cast(w) << width_shift); + } + + FMT_CONSTEXPR auto dynamic_precision() const -> arg_id_kind { + return static_cast((data_ & precision_mask) >> + precision_shift); + } + FMT_CONSTEXPR void set_dynamic_precision(arg_id_kind p) { + data_ = (data_ & ~precision_mask) | + (static_cast(p) << precision_shift); + } + + constexpr auto dynamic() const -> bool { + return (data_ & (width_mask | precision_mask)) != 0; + } + + constexpr auto sign() const -> sign { + return static_cast((data_ & sign_mask) >> sign_shift); + } + FMT_CONSTEXPR void set_sign(fmt::sign s) { + data_ = (data_ & ~sign_mask) | (static_cast(s) << sign_shift); + } + + constexpr auto upper() const -> bool { return (data_ & uppercase_mask) != 0; } + FMT_CONSTEXPR void set_upper() { data_ |= uppercase_mask; } + + constexpr auto alt() const -> bool { return (data_ & alternate_mask) != 0; } + FMT_CONSTEXPR void set_alt() { data_ |= alternate_mask; } + FMT_CONSTEXPR void clear_alt() { data_ &= ~alternate_mask; } + + constexpr auto localized() const -> bool { + return (data_ & localized_mask) != 0; + } + FMT_CONSTEXPR void set_localized() { data_ |= localized_mask; } + + constexpr auto fill_size() const -> size_t { + return (data_ & fill_size_mask) >> fill_size_shift; + } + + template ::value)> + constexpr auto fill() const -> const Char* { + return fill_data_; + } + template ::value)> + constexpr auto fill() const -> const Char* { + return nullptr; + } + + template constexpr auto fill_unit() const -> Char { + using uchar = unsigned char; + return static_cast(static_cast(fill_data_[0]) | + (static_cast(fill_data_[1]) << 8) | + (static_cast(fill_data_[2]) << 16)); + } + + FMT_CONSTEXPR void set_fill(char c) { + fill_data_[0] = c; + set_fill_size(1); + } + + template + FMT_CONSTEXPR void set_fill(basic_string_view s) { + auto size = s.size(); + set_fill_size(size); + if (size == 1) { + unsigned uchar = static_cast>(s[0]); + fill_data_[0] = static_cast(uchar); + fill_data_[1] = static_cast(uchar >> 8); + fill_data_[2] = static_cast(uchar >> 16); + return; + } + FMT_ASSERT(size <= max_fill_size, "invalid fill"); + for (size_t i = 0; i < size; ++i) + fill_data_[i & 3] = static_cast(s[i]); + } + + FMT_CONSTEXPR void copy_fill_from(const basic_specs& specs) { + set_fill_size(specs.fill_size()); + for (size_t i = 0; i < max_fill_size; ++i) + fill_data_[i] = specs.fill_data_[i]; + } +}; + +// Format specifiers for built-in and string types. +struct format_specs : basic_specs { + int width; + int precision; + + constexpr format_specs() : width(0), precision(-1) {} +}; + +/** + * Parsing context consisting of a format string range being parsed and an + * argument counter for automatic indexing. + */ +template class parse_context { + private: + basic_string_view fmt_; + int next_arg_id_; + + enum { use_constexpr_cast = !FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200 }; + + FMT_CONSTEXPR void do_check_arg_id(int arg_id); + + public: + using char_type = Char; + using iterator = const Char*; + + constexpr explicit parse_context(basic_string_view fmt, + int next_arg_id = 0) + : fmt_(fmt), next_arg_id_(next_arg_id) {} + + /// Returns an iterator to the beginning of the format string range being + /// parsed. + constexpr auto begin() const noexcept -> iterator { return fmt_.begin(); } + + /// Returns an iterator past the end of the format string range being parsed. + constexpr auto end() const noexcept -> iterator { return fmt_.end(); } + + /// Advances the begin iterator to `it`. + FMT_CONSTEXPR void advance_to(iterator it) { + fmt_.remove_prefix(detail::to_unsigned(it - begin())); + } + + /// Reports an error if using the manual argument indexing; otherwise returns + /// the next argument index and switches to the automatic indexing. + FMT_CONSTEXPR auto next_arg_id() -> int { + if (next_arg_id_ < 0) { + report_error("cannot switch from manual to automatic argument indexing"); + return 0; + } + int id = next_arg_id_++; + do_check_arg_id(id); + return id; + } + + /// Reports an error if using the automatic argument indexing; otherwise + /// switches to the manual indexing. + FMT_CONSTEXPR void check_arg_id(int id) { + if (next_arg_id_ > 0) { + report_error("cannot switch from automatic to manual argument indexing"); + return; + } + next_arg_id_ = -1; + do_check_arg_id(id); + } + FMT_CONSTEXPR void check_arg_id(basic_string_view) { + next_arg_id_ = -1; + } + FMT_CONSTEXPR void check_dynamic_spec(int arg_id); +}; + +#ifndef FMT_USE_LOCALE +# define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1) +#endif + +// A type-erased reference to std::locale to avoid the heavy include. +class locale_ref { +#if FMT_USE_LOCALE + private: + const void* locale_; // A type-erased pointer to std::locale. + + public: + constexpr locale_ref() : locale_(nullptr) {} + + template + locale_ref(const Locale& loc); + + inline explicit operator bool() const noexcept { return locale_ != nullptr; } +#endif // FMT_USE_LOCALE + + public: + template auto get() const -> Locale; +}; + +FMT_END_EXPORT + +namespace detail { + +// Specifies if `T` is a code unit type. +template struct is_code_unit : std::false_type {}; +template <> struct is_code_unit : std::true_type {}; +template <> struct is_code_unit : std::true_type {}; +template <> struct is_code_unit : std::true_type {}; +template <> struct is_code_unit : std::true_type {}; +#ifdef __cpp_char8_t +template <> struct is_code_unit : bool_constant {}; +#endif + +// Constructs fmt::basic_string_view from types implicitly convertible +// to it, deducing Char. Explicitly convertible types such as the ones returned +// from FMT_STRING are intentionally excluded. +template ::value)> +constexpr auto to_string_view(const Char* s) -> basic_string_view { + return s; +} +template ::value)> +constexpr auto to_string_view(const T& s) + -> basic_string_view { + return s; +} +template +constexpr auto to_string_view(basic_string_view s) + -> basic_string_view { + return s; +} + +template +struct has_to_string_view : std::false_type {}; +// detail:: is intentional since to_string_view is not an extension point. +template +struct has_to_string_view< + T, void_t()))>> + : std::true_type {}; + +/// String's character (code unit) type. detail:: is intentional to prevent ADL. +template ()))> +using char_t = typename V::value_type; + +enum class type { + none_type, + // Integer types should go first, + int_type, + uint_type, + long_long_type, + ulong_long_type, + int128_type, + uint128_type, + bool_type, + char_type, + last_integer_type = char_type, + // followed by floating-point types. + float_type, + double_type, + long_double_type, + last_numeric_type = long_double_type, + cstring_type, + string_type, + pointer_type, + custom_type +}; + +// Maps core type T to the corresponding type enum constant. +template +struct type_constant : std::integral_constant {}; + +#define FMT_TYPE_CONSTANT(Type, constant) \ + template \ + struct type_constant \ + : std::integral_constant {} + +FMT_TYPE_CONSTANT(int, int_type); +FMT_TYPE_CONSTANT(unsigned, uint_type); +FMT_TYPE_CONSTANT(long long, long_long_type); +FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); +FMT_TYPE_CONSTANT(int128_opt, int128_type); +FMT_TYPE_CONSTANT(uint128_opt, uint128_type); +FMT_TYPE_CONSTANT(bool, bool_type); +FMT_TYPE_CONSTANT(Char, char_type); +FMT_TYPE_CONSTANT(float, float_type); +FMT_TYPE_CONSTANT(double, double_type); +FMT_TYPE_CONSTANT(long double, long_double_type); +FMT_TYPE_CONSTANT(const Char*, cstring_type); +FMT_TYPE_CONSTANT(basic_string_view, string_type); +FMT_TYPE_CONSTANT(const void*, pointer_type); + +constexpr auto is_integral_type(type t) -> bool { + return t > type::none_type && t <= type::last_integer_type; +} +constexpr auto is_arithmetic_type(type t) -> bool { + return t > type::none_type && t <= type::last_numeric_type; +} + +constexpr auto set(type rhs) -> int { return 1 << static_cast(rhs); } +constexpr auto in(type t, int set) -> bool { + return ((set >> static_cast(t)) & 1) != 0; +} + +// Bitsets of types. +enum { + sint_set = + set(type::int_type) | set(type::long_long_type) | set(type::int128_type), + uint_set = set(type::uint_type) | set(type::ulong_long_type) | + set(type::uint128_type), + bool_set = set(type::bool_type), + char_set = set(type::char_type), + float_set = set(type::float_type) | set(type::double_type) | + set(type::long_double_type), + string_set = set(type::string_type), + cstring_set = set(type::cstring_type), + pointer_set = set(type::pointer_type) +}; + +struct view {}; + +template +struct is_view : std::false_type {}; +template +struct is_view> : std::is_base_of {}; + +template struct named_arg; +template struct is_named_arg : std::false_type {}; +template struct is_static_named_arg : std::false_type {}; + +template +struct is_named_arg> : std::true_type {}; + +template struct named_arg : view { + const Char* name; + const T& value; + + named_arg(const Char* n, const T& v) : name(n), value(v) {} + static_assert(!is_named_arg::value, "nested named arguments"); +}; + +template constexpr auto count() -> int { return B ? 1 : 0; } +template constexpr auto count() -> int { + return (B1 ? 1 : 0) + count(); +} + +template constexpr auto count_named_args() -> int { + return count::value...>(); +} +template constexpr auto count_static_named_args() -> int { + return count::value...>(); +} + +template struct named_arg_info { + const Char* name; + int id; +}; + +// named_args is non-const to suppress a bogus -Wmaybe-uninitialized in gcc 13. +template +FMT_CONSTEXPR void check_for_duplicate(named_arg_info* named_args, + int named_arg_index, + basic_string_view arg_name) { + for (int i = 0; i < named_arg_index; ++i) { + if (named_args[i].name == arg_name) report_error("duplicate named arg"); + } +} + +template ::value)> +void init_named_arg(named_arg_info*, int& arg_index, int&, const T&) { + ++arg_index; +} +template ::value)> +void init_named_arg(named_arg_info* named_args, int& arg_index, + int& named_arg_index, const T& arg) { + check_for_duplicate(named_args, named_arg_index, arg.name); + named_args[named_arg_index++] = {arg.name, arg_index++}; +} + +template ::value)> +FMT_CONSTEXPR void init_static_named_arg(named_arg_info*, int& arg_index, + int&) { + ++arg_index; +} +template ::value)> +FMT_CONSTEXPR void init_static_named_arg(named_arg_info* named_args, + int& arg_index, int& named_arg_index) { + check_for_duplicate(named_args, named_arg_index, T::name); + named_args[named_arg_index++] = {T::name, arg_index++}; +} + +// To minimize the number of types we need to deal with, long is translated +// either to int or to long long depending on its size. +enum { long_short = sizeof(long) == sizeof(int) && FMT_BUILTIN_TYPES }; +using long_type = conditional_t; +using ulong_type = conditional_t; + +template +using format_as_result = + remove_cvref_t()))>; +template +using format_as_member_result = + remove_cvref_t::format_as(std::declval()))>; + +template +struct use_format_as : std::false_type {}; +// format_as member is only used to avoid injection into the std namespace. +template +struct use_format_as_member : std::false_type {}; + +// Only map owning types because mapping views can be unsafe. +template +struct use_format_as< + T, bool_constant>::value>> + : std::true_type {}; +template +struct use_format_as_member< + T, bool_constant>::value>> + : std::true_type {}; + +template > +using use_formatter = + bool_constant<(std::is_class::value || std::is_enum::value || + std::is_union::value || std::is_array::value) && + !has_to_string_view::value && !is_named_arg::value && + !use_format_as::value && !use_format_as_member::value>; + +template > +auto has_formatter_impl(T* p, buffered_context* ctx = nullptr) + -> decltype(formatter().format(*p, *ctx), std::true_type()); +template auto has_formatter_impl(...) -> std::false_type; + +// T can be const-qualified to check if it is const-formattable. +template constexpr auto has_formatter() -> bool { + return decltype(has_formatter_impl(static_cast(nullptr)))::value; +} + +// Maps formatting argument types to natively supported types or user-defined +// types with formatters. Returns void on errors to be SFINAE-friendly. +template struct type_mapper { + static auto map(signed char) -> int; + static auto map(unsigned char) -> unsigned; + static auto map(short) -> int; + static auto map(unsigned short) -> unsigned; + static auto map(int) -> int; + static auto map(unsigned) -> unsigned; + static auto map(long) -> long_type; + static auto map(unsigned long) -> ulong_type; + static auto map(long long) -> long long; + static auto map(unsigned long long) -> unsigned long long; + static auto map(int128_opt) -> int128_opt; + static auto map(uint128_opt) -> uint128_opt; + static auto map(bool) -> bool; + + template + static auto map(bitint) -> conditional_t; + template + static auto map(ubitint) + -> conditional_t; + + template ::value)> + static auto map(T) -> conditional_t< + std::is_same::value || std::is_same::value, Char, void>; + + static auto map(float) -> float; + static auto map(double) -> double; + static auto map(long double) -> long double; + + static auto map(Char*) -> const Char*; + static auto map(const Char*) -> const Char*; + template , + FMT_ENABLE_IF(!std::is_pointer::value)> + static auto map(const T&) -> conditional_t::value, + basic_string_view, void>; + + static auto map(void*) -> const void*; + static auto map(const void*) -> const void*; + static auto map(volatile void*) -> const void*; + static auto map(const volatile void*) -> const void*; + static auto map(nullptr_t) -> const void*; + template ::value || + std::is_member_pointer::value)> + static auto map(const T&) -> void; + + template ::value)> + static auto map(const T& x) -> decltype(map(format_as(x))); + template ::value)> + static auto map(const T& x) -> decltype(map(formatter::format_as(x))); + + template ::value)> + static auto map(T&) -> conditional_t(), T&, void>; + + template ::value)> + static auto map(const T& named_arg) -> decltype(map(named_arg.value)); +}; + +// detail:: is used to workaround a bug in MSVC 2017. +template +using mapped_t = decltype(detail::type_mapper::map(std::declval())); + +// A type constant after applying type_mapper. +template +using mapped_type_constant = type_constant, Char>; + +template ::value> +using stored_type_constant = std::integral_constant< + type, Context::builtin_types || TYPE == type::int_type ? TYPE + : type::custom_type>; +// A parse context with extra data used only in compile-time checks. +template +class compile_parse_context : public parse_context { + private: + int num_args_; + const type* types_; + using base = parse_context; + + public: + FMT_CONSTEXPR explicit compile_parse_context(basic_string_view fmt, + int num_args, const type* types, + int next_arg_id = 0) + : base(fmt, next_arg_id), num_args_(num_args), types_(types) {} + + constexpr auto num_args() const -> int { return num_args_; } + constexpr auto arg_type(int id) const -> type { return types_[id]; } + + FMT_CONSTEXPR auto next_arg_id() -> int { + int id = base::next_arg_id(); + if (id >= num_args_) report_error("argument not found"); + return id; + } + + FMT_CONSTEXPR void check_arg_id(int id) { + base::check_arg_id(id); + if (id >= num_args_) report_error("argument not found"); + } + using base::check_arg_id; + + FMT_CONSTEXPR void check_dynamic_spec(int arg_id) { + ignore_unused(arg_id); + if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id])) + report_error("width/precision is not integer"); + } +}; + +// An argument reference. +template union arg_ref { + FMT_CONSTEXPR arg_ref(int idx = 0) : index(idx) {} + FMT_CONSTEXPR arg_ref(basic_string_view n) : name(n) {} + + int index; + basic_string_view name; +}; + +// Format specifiers with width and precision resolved at formatting rather +// than parsing time to allow reusing the same parsed specifiers with +// different sets of arguments (precompilation of format strings). +template struct dynamic_format_specs : format_specs { + arg_ref width_ref; + arg_ref precision_ref; +}; + +// Converts a character to ASCII. Returns '\0' on conversion failure. +template ::value)> +constexpr auto to_ascii(Char c) -> char { + return c <= 0xff ? static_cast(c) : '\0'; +} + +// Returns the number of code units in a code point or 1 on error. +template +FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int { + if (const_check(sizeof(Char) != 1)) return 1; + auto c = static_cast(*begin); + return static_cast((0x3a55000000000000ull >> (2 * (c >> 3))) & 3) + 1; +} + +// Parses the range [begin, end) as an unsigned integer. This function assumes +// that the range is non-empty and the first character is a digit. +template +FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end, + int error_value) noexcept -> int { + FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); + unsigned value = 0, prev = 0; + auto p = begin; + do { + prev = value; + value = value * 10 + unsigned(*p - '0'); + ++p; + } while (p != end && '0' <= *p && *p <= '9'); + auto num_digits = p - begin; + begin = p; + int digits10 = static_cast(sizeof(int) * CHAR_BIT * 3 / 10); + if (num_digits <= digits10) return static_cast(value); + // Check for overflow. + unsigned max = INT_MAX; + return num_digits == digits10 + 1 && + prev * 10ull + unsigned(p[-1] - '0') <= max + ? static_cast(value) + : error_value; +} + +FMT_CONSTEXPR inline auto parse_align(char c) -> align { + switch (c) { + case '<': return align::left; + case '>': return align::right; + case '^': return align::center; + } + return align::none; +} + +template constexpr auto is_name_start(Char c) -> bool { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; +} + +template +FMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + Char c = *begin; + if (c >= '0' && c <= '9') { + int index = 0; + if (c != '0') + index = parse_nonnegative_int(begin, end, INT_MAX); + else + ++begin; + if (begin == end || (*begin != '}' && *begin != ':')) + report_error("invalid format string"); + else + handler.on_index(index); + return begin; + } + if (FMT_OPTIMIZE_SIZE > 1 || !is_name_start(c)) { + report_error("invalid format string"); + return begin; + } + auto it = begin; + do { + ++it; + } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9'))); + handler.on_name({begin, to_unsigned(it - begin)}); + return it; +} + +template struct dynamic_spec_handler { + parse_context& ctx; + arg_ref& ref; + arg_id_kind& kind; + + FMT_CONSTEXPR void on_index(int id) { + ref = id; + kind = arg_id_kind::index; + ctx.check_arg_id(id); + ctx.check_dynamic_spec(id); + } + FMT_CONSTEXPR void on_name(basic_string_view id) { + ref = id; + kind = arg_id_kind::name; + ctx.check_arg_id(id); + } +}; + +template struct parse_dynamic_spec_result { + const Char* end; + arg_id_kind kind; +}; + +// Parses integer | "{" [arg_id] "}". +template +FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end, + int& value, arg_ref& ref, + parse_context& ctx) + -> parse_dynamic_spec_result { + FMT_ASSERT(begin != end, ""); + auto kind = arg_id_kind::none; + if ('0' <= *begin && *begin <= '9') { + int val = parse_nonnegative_int(begin, end, -1); + if (val == -1) report_error("number is too big"); + value = val; + } else { + if (*begin == '{') { + ++begin; + if (begin != end) { + Char c = *begin; + if (c == '}' || c == ':') { + int id = ctx.next_arg_id(); + ref = id; + kind = arg_id_kind::index; + ctx.check_dynamic_spec(id); + } else { + begin = parse_arg_id(begin, end, + dynamic_spec_handler{ctx, ref, kind}); + } + } + if (begin != end && *begin == '}') return {++begin, kind}; + } + report_error("invalid format string"); + } + return {begin, kind}; +} + +template +FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end, + format_specs& specs, arg_ref& width_ref, + parse_context& ctx) -> const Char* { + auto result = parse_dynamic_spec(begin, end, specs.width, width_ref, ctx); + specs.set_dynamic_width(result.kind); + return result.end; +} + +template +FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end, + format_specs& specs, + arg_ref& precision_ref, + parse_context& ctx) -> const Char* { + ++begin; + if (begin == end) { + report_error("invalid precision"); + return begin; + } + auto result = + parse_dynamic_spec(begin, end, specs.precision, precision_ref, ctx); + specs.set_dynamic_precision(result.kind); + return result.end; +} + +enum class state { start, align, sign, hash, zero, width, precision, locale }; + +// Parses standard format specifiers. +template +FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end, + dynamic_format_specs& specs, + parse_context& ctx, type arg_type) + -> const Char* { + auto c = '\0'; + if (end - begin > 1) { + auto next = to_ascii(begin[1]); + c = parse_align(next) == align::none ? to_ascii(*begin) : '\0'; + } else { + if (begin == end) return begin; + c = to_ascii(*begin); + } + + struct { + state current_state = state::start; + FMT_CONSTEXPR void operator()(state s, bool valid = true) { + if (current_state >= s || !valid) + report_error("invalid format specifier"); + current_state = s; + } + } enter_state; + + using pres = presentation_type; + constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; + struct { + const Char*& begin; + format_specs& specs; + type arg_type; + + FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* { + if (!in(arg_type, set)) report_error("invalid format specifier"); + specs.set_type(pres_type); + return begin + 1; + } + } parse_presentation_type{begin, specs, arg_type}; + + for (;;) { + switch (c) { + case '<': + case '>': + case '^': + enter_state(state::align); + specs.set_align(parse_align(c)); + ++begin; + break; + case '+': + case ' ': + specs.set_sign(c == ' ' ? sign::space : sign::plus); + FMT_FALLTHROUGH; + case '-': + enter_state(state::sign, in(arg_type, sint_set | float_set)); + ++begin; + break; + case '#': + enter_state(state::hash, is_arithmetic_type(arg_type)); + specs.set_alt(); + ++begin; + break; + case '0': + enter_state(state::zero); + if (!is_arithmetic_type(arg_type)) + report_error("format specifier requires numeric argument"); + if (specs.align() == align::none) { + // Ignore 0 if align is specified for compatibility with std::format. + specs.set_align(align::numeric); + specs.set_fill('0'); + } + ++begin; + break; + // clang-format off + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': case '{': + // clang-format on + enter_state(state::width); + begin = parse_width(begin, end, specs, specs.width_ref, ctx); + break; + case '.': + enter_state(state::precision, + in(arg_type, float_set | string_set | cstring_set)); + begin = parse_precision(begin, end, specs, specs.precision_ref, ctx); + break; + case 'L': + enter_state(state::locale, is_arithmetic_type(arg_type)); + specs.set_localized(); + ++begin; + break; + case 'd': return parse_presentation_type(pres::dec, integral_set); + case 'X': specs.set_upper(); FMT_FALLTHROUGH; + case 'x': return parse_presentation_type(pres::hex, integral_set); + case 'o': return parse_presentation_type(pres::oct, integral_set); + case 'B': specs.set_upper(); FMT_FALLTHROUGH; + case 'b': return parse_presentation_type(pres::bin, integral_set); + case 'E': specs.set_upper(); FMT_FALLTHROUGH; + case 'e': return parse_presentation_type(pres::exp, float_set); + case 'F': specs.set_upper(); FMT_FALLTHROUGH; + case 'f': return parse_presentation_type(pres::fixed, float_set); + case 'G': specs.set_upper(); FMT_FALLTHROUGH; + case 'g': return parse_presentation_type(pres::general, float_set); + case 'A': specs.set_upper(); FMT_FALLTHROUGH; + case 'a': return parse_presentation_type(pres::hexfloat, float_set); + case 'c': + if (arg_type == type::bool_type) report_error("invalid format specifier"); + return parse_presentation_type(pres::chr, integral_set); + case 's': + return parse_presentation_type(pres::string, + bool_set | string_set | cstring_set); + case 'p': + return parse_presentation_type(pres::pointer, pointer_set | cstring_set); + case '?': + return parse_presentation_type(pres::debug, + char_set | string_set | cstring_set); + case '}': return begin; + default: { + if (*begin == '}') return begin; + // Parse fill and alignment. + auto fill_end = begin + code_point_length(begin); + if (end - fill_end <= 0) { + report_error("invalid format specifier"); + return begin; + } + if (*begin == '{') { + report_error("invalid fill character '{'"); + return begin; + } + auto alignment = parse_align(to_ascii(*fill_end)); + enter_state(state::align, alignment != align::none); + specs.set_fill( + basic_string_view(begin, to_unsigned(fill_end - begin))); + specs.set_align(alignment); + begin = fill_end + 1; + } + } + if (begin == end) return begin; + c = to_ascii(*begin); + } +} + +template +FMT_CONSTEXPR FMT_INLINE auto parse_replacement_field(const Char* begin, + const Char* end, + Handler&& handler) + -> const Char* { + ++begin; + if (begin == end) { + handler.on_error("invalid format string"); + return end; + } + int arg_id = 0; + switch (*begin) { + case '}': + handler.on_replacement_field(handler.on_arg_id(), begin); + return begin + 1; + case '{': handler.on_text(begin, begin + 1); return begin + 1; + case ':': arg_id = handler.on_arg_id(); break; + default: { + struct id_adapter { + Handler& handler; + int arg_id; + + FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); } + FMT_CONSTEXPR void on_name(basic_string_view id) { + arg_id = handler.on_arg_id(id); + } + } adapter = {handler, 0}; + begin = parse_arg_id(begin, end, adapter); + arg_id = adapter.arg_id; + Char c = begin != end ? *begin : Char(); + if (c == '}') { + handler.on_replacement_field(arg_id, begin); + return begin + 1; + } + if (c != ':') { + handler.on_error("missing '}' in format string"); + return end; + } + break; + } + } + begin = handler.on_format_specs(arg_id, begin + 1, end); + if (begin == end || *begin != '}') + return handler.on_error("unknown format specifier"), end; + return begin + 1; +} + +template +FMT_CONSTEXPR void parse_format_string(basic_string_view fmt, + Handler&& handler) { + auto begin = fmt.data(), end = begin + fmt.size(); + auto p = begin; + while (p != end) { + auto c = *p++; + if (c == '{') { + handler.on_text(begin, p - 1); + begin = p = parse_replacement_field(p - 1, end, handler); + } else if (c == '}') { + if (p == end || *p != '}') + return handler.on_error("unmatched '}' in format string"); + handler.on_text(begin, p); + begin = ++p; + } + } + handler.on_text(begin, end); +} + +// Checks char specs and returns true iff the presentation type is char-like. +FMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool { + auto type = specs.type(); + if (type != presentation_type::none && type != presentation_type::chr && + type != presentation_type::debug) { + return false; + } + if (specs.align() == align::numeric || specs.sign() != sign::none || + specs.alt()) { + report_error("invalid format specifier for char"); + } + return true; +} + +// A base class for compile-time strings. +struct compile_string {}; + +template +FMT_VISIBILITY("hidden") // Suppress an ld warning on macOS (#3769). +FMT_CONSTEXPR auto invoke_parse(parse_context& ctx) -> const Char* { + using mapped_type = remove_cvref_t>; + constexpr bool formattable = + std::is_constructible>::value; + if (!formattable) return ctx.begin(); // Error is reported in the value ctor. + using formatted_type = conditional_t; + return formatter().parse(ctx); +} + +template struct arg_pack {}; + +template +class format_string_checker { + private: + type types_[max_of(1, NUM_ARGS)]; + named_arg_info named_args_[max_of(1, NUM_NAMED_ARGS)]; + compile_parse_context context_; + + using parse_func = auto (*)(parse_context&) -> const Char*; + parse_func parse_funcs_[max_of(1, NUM_ARGS)]; + + public: + template + FMT_CONSTEXPR explicit format_string_checker(basic_string_view fmt, + arg_pack) + : types_{mapped_type_constant::value...}, + named_args_{}, + context_(fmt, NUM_ARGS, types_), + parse_funcs_{&invoke_parse...} { + int arg_index = 0, named_arg_index = 0; + FMT_APPLY_VARIADIC( + init_static_named_arg(named_args_, arg_index, named_arg_index)); + ignore_unused(arg_index, named_arg_index); + } + + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + + FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + context_.check_arg_id(id); + return id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { + for (int i = 0; i < NUM_NAMED_ARGS; ++i) { + if (named_args_[i].name == id) return named_args_[i].id; + } + if (!DYNAMIC_NAMES) on_error("argument not found"); + return -1; + } + + FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) { + on_format_specs(id, begin, begin); // Call parse() on empty specs. + } + + FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char* end) + -> const Char* { + context_.advance_to(begin); + if (id >= 0 && id < NUM_ARGS) return parse_funcs_[id](context_); + + // If id is out of range, it means we do not know the type and cannot parse + // the format at compile time. Instead, skip over content until we finish + // the format spec, accounting for any nested replacements. + for (int bracket_count = 0; + begin != end && (bracket_count > 0 || *begin != '}'); ++begin) { + if (*begin == '{') + ++bracket_count; + else if (*begin == '}') + --bracket_count; + } + return begin; + } + + FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) { + report_error(message); + } +}; + +/// A contiguous memory buffer with an optional growing ability. It is an +/// internal class and shouldn't be used directly, only via `memory_buffer`. +template class buffer { + private: + T* ptr_; + size_t size_; + size_t capacity_; + + using grow_fun = void (*)(buffer& buf, size_t capacity); + grow_fun grow_; + + protected: + // Don't initialize ptr_ since it is not accessed to save a few cycles. + FMT_MSC_WARNING(suppress : 26495) + FMT_CONSTEXPR buffer(grow_fun grow, size_t sz) noexcept + : size_(sz), capacity_(sz), grow_(grow) {} + + constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0, + size_t cap = 0) noexcept + : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {} + + FMT_CONSTEXPR20 ~buffer() = default; + buffer(buffer&&) = default; + + /// Sets the buffer data and capacity. + FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept { + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + public: + using value_type = T; + using const_reference = const T&; + + buffer(const buffer&) = delete; + void operator=(const buffer&) = delete; + + auto begin() noexcept -> T* { return ptr_; } + auto end() noexcept -> T* { return ptr_ + size_; } + + auto begin() const noexcept -> const T* { return ptr_; } + auto end() const noexcept -> const T* { return ptr_ + size_; } + + /// Returns the size of this buffer. + constexpr auto size() const noexcept -> size_t { return size_; } + + /// Returns the capacity of this buffer. + constexpr auto capacity() const noexcept -> size_t { return capacity_; } + + /// Returns a pointer to the buffer data (not null-terminated). + FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; } + FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; } + + /// Clears this buffer. + FMT_CONSTEXPR void clear() { size_ = 0; } + + // Tries resizing the buffer to contain `count` elements. If T is a POD type + // the new elements may not be initialized. + FMT_CONSTEXPR void try_resize(size_t count) { + try_reserve(count); + size_ = min_of(count, capacity_); + } + + // Tries increasing the buffer capacity to `new_capacity`. It can increase the + // capacity by a smaller amount than requested but guarantees there is space + // for at least one additional element either by increasing the capacity or by + // flushing the buffer if it is full. + FMT_CONSTEXPR void try_reserve(size_t new_capacity) { + if (new_capacity > capacity_) grow_(*this, new_capacity); + } + + FMT_CONSTEXPR void push_back(const T& value) { + try_reserve(size_ + 1); + ptr_[size_++] = value; + } + + /// Appends data to the end of the buffer. + template +// Workaround for MSVC2019 to fix error C2893: Failed to specialize function +// template 'void fmt::v11::detail::buffer::append(const U *,const U *)'. +#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1940 + FMT_CONSTEXPR20 +#endif + void + append(const U* begin, const U* end) { + while (begin != end) { + auto count = to_unsigned(end - begin); + try_reserve(size_ + count); + auto free_cap = capacity_ - size_; + if (free_cap < count) count = free_cap; + // A loop is faster than memcpy on small sizes. + T* out = ptr_ + size_; + for (size_t i = 0; i < count; ++i) out[i] = begin[i]; + size_ += count; + begin += count; + } + } + + template FMT_CONSTEXPR auto operator[](Idx index) -> T& { + return ptr_[index]; + } + template + FMT_CONSTEXPR auto operator[](Idx index) const -> const T& { + return ptr_[index]; + } +}; + +struct buffer_traits { + constexpr explicit buffer_traits(size_t) {} + constexpr auto count() const -> size_t { return 0; } + constexpr auto limit(size_t size) const -> size_t { return size; } +}; + +class fixed_buffer_traits { + private: + size_t count_ = 0; + size_t limit_; + + public: + constexpr explicit fixed_buffer_traits(size_t limit) : limit_(limit) {} + constexpr auto count() const -> size_t { return count_; } + FMT_CONSTEXPR auto limit(size_t size) -> size_t { + size_t n = limit_ > count_ ? limit_ - count_ : 0; + count_ += size; + return min_of(size, n); + } +}; + +// A buffer that writes to an output iterator when flushed. +template +class iterator_buffer : public Traits, public buffer { + private: + OutputIt out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() == buffer_size) static_cast(buf).flush(); + } + + void flush() { + auto size = this->size(); + this->clear(); + const T* begin = data_; + const T* end = begin + this->limit(size); + while (begin != end) *out_++ = *begin++; + } + + public: + explicit iterator_buffer(OutputIt out, size_t n = buffer_size) + : Traits(n), buffer(grow, data_, 0, buffer_size), out_(out) {} + iterator_buffer(iterator_buffer&& other) noexcept + : Traits(other), + buffer(grow, data_, 0, buffer_size), + out_(other.out_) {} + ~iterator_buffer() { + // Don't crash if flush fails during unwinding. + FMT_TRY { flush(); } + FMT_CATCH(...) {} + } + + auto out() -> OutputIt { + flush(); + return out_; + } + auto count() const -> size_t { return Traits::count() + this->size(); } +}; + +template +class iterator_buffer : public fixed_buffer_traits, + public buffer { + private: + T* out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() == buf.capacity()) + static_cast(buf).flush(); + } + + void flush() { + size_t n = this->limit(this->size()); + if (this->data() == out_) { + out_ += n; + this->set(data_, buffer_size); + } + this->clear(); + } + + public: + explicit iterator_buffer(T* out, size_t n = buffer_size) + : fixed_buffer_traits(n), buffer(grow, out, 0, n), out_(out) {} + iterator_buffer(iterator_buffer&& other) noexcept + : fixed_buffer_traits(other), + buffer(static_cast(other)), + out_(other.out_) { + if (this->data() != out_) { + this->set(data_, buffer_size); + this->clear(); + } + } + ~iterator_buffer() { flush(); } + + auto out() -> T* { + flush(); + return out_; + } + auto count() const -> size_t { + return fixed_buffer_traits::count() + this->size(); + } +}; + +template class iterator_buffer : public buffer { + public: + explicit iterator_buffer(T* out, size_t = 0) + : buffer([](buffer&, size_t) {}, out, 0, ~size_t()) {} + + auto out() -> T* { return &*this->end(); } +}; + +template +class container_buffer : public buffer { + private: + using value_type = typename Container::value_type; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t capacity) { + auto& self = static_cast(buf); + self.container.resize(capacity); + self.set(&self.container[0], capacity); + } + + public: + Container& container; + + explicit container_buffer(Container& c) + : buffer(grow, c.size()), container(c) {} +}; + +// A buffer that writes to a container with the contiguous storage. +template +class iterator_buffer< + OutputIt, + enable_if_t::value && + is_contiguous::value, + typename OutputIt::container_type::value_type>> + : public container_buffer { + private: + using base = container_buffer; + + public: + explicit iterator_buffer(typename OutputIt::container_type& c) : base(c) {} + explicit iterator_buffer(OutputIt out, size_t = 0) + : base(get_container(out)) {} + + auto out() -> OutputIt { return OutputIt(this->container); } +}; + +// A buffer that counts the number of code units written discarding the output. +template class counting_buffer : public buffer { + private: + enum { buffer_size = 256 }; + T data_[buffer_size]; + size_t count_ = 0; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() != buffer_size) return; + static_cast(buf).count_ += buf.size(); + buf.clear(); + } + + public: + FMT_CONSTEXPR counting_buffer() : buffer(grow, data_, 0, buffer_size) {} + + constexpr auto count() const noexcept -> size_t { + return count_ + this->size(); + } +}; + +template +struct is_back_insert_iterator> : std::true_type {}; + +template +struct has_back_insert_iterator_container_append : std::false_type {}; +template +struct has_back_insert_iterator_container_append< + OutputIt, InputIt, + void_t()) + .append(std::declval(), + std::declval()))>> : std::true_type {}; + +template +struct has_back_insert_iterator_container_insert_at_end : std::false_type {}; + +template +struct has_back_insert_iterator_container_insert_at_end< + OutputIt, InputIt, + void_t()) + .insert(get_container(std::declval()).end(), + std::declval(), + std::declval()))>> : std::true_type {}; + +// An optimized version of std::copy with the output value type (T). +template ::value&& + has_back_insert_iterator_container_append< + OutputIt, InputIt>::value)> +FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out) + -> OutputIt { + get_container(out).append(begin, end); + return out; +} + +template ::value && + !has_back_insert_iterator_container_append< + OutputIt, InputIt>::value && + has_back_insert_iterator_container_insert_at_end< + OutputIt, InputIt>::value)> +FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out) + -> OutputIt { + auto& c = get_container(out); + c.insert(c.end(), begin, end); + return out; +} + +template ::value && + (has_back_insert_iterator_container_append< + OutputIt, InputIt>::value || + has_back_insert_iterator_container_insert_at_end< + OutputIt, InputIt>::value)))> +FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt { + while (begin != end) *out++ = static_cast(*begin++); + return out; +} + +template +FMT_CONSTEXPR auto copy(basic_string_view s, OutputIt out) -> OutputIt { + return copy(s.begin(), s.end(), out); +} + +template +struct is_buffer_appender : std::false_type {}; +template +struct is_buffer_appender< + It, bool_constant< + is_back_insert_iterator::value && + std::is_base_of, + typename It::container_type>::value>> + : std::true_type {}; + +// Maps an output iterator to a buffer. +template ::value)> +auto get_buffer(OutputIt out) -> iterator_buffer { + return iterator_buffer(out); +} +template ::value)> +auto get_buffer(OutputIt out) -> buffer& { + return get_container(out); +} + +template +auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) { + return buf.out(); +} +template +auto get_iterator(buffer&, OutputIt out) -> OutputIt { + return out; +} + +// This type is intentionally undefined, only used for errors. +template struct type_is_unformattable_for; + +template struct string_value { + const Char* data; + size_t size; + auto str() const -> basic_string_view { return {data, size}; } +}; + +template struct custom_value { + using char_type = typename Context::char_type; + void* value; + void (*format)(void* arg, parse_context& parse_ctx, Context& ctx); +}; + +template struct named_arg_value { + const named_arg_info* data; + size_t size; +}; + +struct custom_tag {}; + +#if !FMT_BUILTIN_TYPES +# define FMT_BUILTIN , monostate +#else +# define FMT_BUILTIN +#endif + +// A formatting argument value. +template class value { + public: + using char_type = typename Context::char_type; + + union { + monostate no_value; + int int_value; + unsigned uint_value; + long long long_long_value; + unsigned long long ulong_long_value; + int128_opt int128_value; + uint128_opt uint128_value; + bool bool_value; + char_type char_value; + float float_value; + double double_value; + long double long_double_value; + const void* pointer; + string_value string; + custom_value custom; + named_arg_value named_args; + }; + + constexpr FMT_INLINE value() : no_value() {} + constexpr FMT_INLINE value(signed char x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned char x FMT_BUILTIN) : uint_value(x) {} + constexpr FMT_INLINE value(signed short x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned short x FMT_BUILTIN) : uint_value(x) {} + constexpr FMT_INLINE value(int x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned x FMT_BUILTIN) : uint_value(x) {} + FMT_CONSTEXPR FMT_INLINE value(long x FMT_BUILTIN) : value(long_type(x)) {} + FMT_CONSTEXPR FMT_INLINE value(unsigned long x FMT_BUILTIN) + : value(ulong_type(x)) {} + constexpr FMT_INLINE value(long long x FMT_BUILTIN) : long_long_value(x) {} + constexpr FMT_INLINE value(unsigned long long x FMT_BUILTIN) + : ulong_long_value(x) {} + FMT_INLINE value(int128_opt x FMT_BUILTIN) : int128_value(x) {} + FMT_INLINE value(uint128_opt x FMT_BUILTIN) : uint128_value(x) {} + constexpr FMT_INLINE value(bool x FMT_BUILTIN) : bool_value(x) {} + + template + constexpr FMT_INLINE value(bitint x FMT_BUILTIN) : long_long_value(x) { + static_assert(N <= 64, "unsupported _BitInt"); + } + template + constexpr FMT_INLINE value(ubitint x FMT_BUILTIN) : ulong_long_value(x) { + static_assert(N <= 64, "unsupported _BitInt"); + } + + template ::value)> + constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) { + static_assert( + std::is_same::value || std::is_same::value, + "mixing character types is disallowed"); + } + + constexpr FMT_INLINE value(float x FMT_BUILTIN) : float_value(x) {} + constexpr FMT_INLINE value(double x FMT_BUILTIN) : double_value(x) {} + FMT_INLINE value(long double x FMT_BUILTIN) : long_double_value(x) {} + + FMT_CONSTEXPR FMT_INLINE value(char_type* x FMT_BUILTIN) { + string.data = x; + if (is_constant_evaluated()) string.size = 0; + } + FMT_CONSTEXPR FMT_INLINE value(const char_type* x FMT_BUILTIN) { + string.data = x; + if (is_constant_evaluated()) string.size = 0; + } + template , + FMT_ENABLE_IF(!std::is_pointer::value)> + FMT_CONSTEXPR value(const T& x FMT_BUILTIN) { + static_assert(std::is_same::value, + "mixing character types is disallowed"); + auto sv = to_string_view(x); + string.data = sv.data(); + string.size = sv.size(); + } + FMT_INLINE value(void* x FMT_BUILTIN) : pointer(x) {} + FMT_INLINE value(const void* x FMT_BUILTIN) : pointer(x) {} + FMT_INLINE value(volatile void* x FMT_BUILTIN) + : pointer(const_cast(x)) {} + FMT_INLINE value(const volatile void* x FMT_BUILTIN) + : pointer(const_cast(x)) {} + FMT_INLINE value(nullptr_t) : pointer(nullptr) {} + + template ::value || + std::is_member_pointer::value)> + value(const T&) { + // Formatting of arbitrary pointers is disallowed. If you want to format a + // pointer cast it to `void*` or `const void*`. In particular, this forbids + // formatting of `[const] volatile char*` printed as bool by iostreams. + static_assert(sizeof(T) == 0, + "formatting of non-void pointers is disallowed"); + } + + template ::value)> + value(const T& x) : value(format_as(x)) {} + template ::value)> + value(const T& x) : value(formatter::format_as(x)) {} + + template ::value)> + value(const T& named_arg) : value(named_arg.value) {} + + template ::value || !FMT_BUILTIN_TYPES)> + FMT_CONSTEXPR20 FMT_INLINE value(T& x) : value(x, custom_tag()) {} + + FMT_ALWAYS_INLINE value(const named_arg_info* args, size_t size) + : named_args{args, size} {} + + private: + template ())> + FMT_CONSTEXPR value(T& x, custom_tag) { + using value_type = remove_const_t; + // T may overload operator& e.g. std::vector::reference in libc++. + if (!is_constant_evaluated()) { + custom.value = + const_cast(&reinterpret_cast(x)); + } else { + custom.value = nullptr; +#if defined(__cpp_if_constexpr) + if constexpr (std::is_same*>::value) + custom.value = const_cast(&x); +#endif + } + custom.format = format_custom; + } + + template ())> + FMT_CONSTEXPR value(const T&, custom_tag) { + // Cannot format an argument; to make type T formattable provide a + // formatter specialization: https://fmt.dev/latest/api.html#udt. + type_is_unformattable_for _; + } + + // Formats an argument of a custom type, such as a user-defined class. + template + static void format_custom(void* arg, parse_context& parse_ctx, + Context& ctx) { + auto f = formatter(); + parse_ctx.advance_to(f.parse(parse_ctx)); + using qualified_type = + conditional_t(), const T, T>; + // format must be const for compatibility with std::format and compilation. + const auto& cf = f; + ctx.advance_to(cf.format(*static_cast(arg), ctx)); + } +}; + +enum { packed_arg_bits = 4 }; +// Maximum number of arguments with packed types. +enum { max_packed_args = 62 / packed_arg_bits }; +enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; +enum : unsigned long long { has_named_args_bit = 1ULL << 62 }; + +template +struct is_output_iterator : std::false_type {}; + +template <> struct is_output_iterator : std::true_type {}; + +template +struct is_output_iterator< + It, T, + enable_if_t&>()++), + T>::value>> : std::true_type {}; + +template constexpr auto encode_types() -> unsigned long long { + return 0; +} + +template +constexpr auto encode_types() -> unsigned long long { + return static_cast(stored_type_constant::value) | + (encode_types() << packed_arg_bits); +} + +template +constexpr auto make_descriptor() -> unsigned long long { + return NUM_ARGS <= max_packed_args ? encode_types() + : is_unpacked_bit | NUM_ARGS; +} + +template +using arg_t = conditional_t, + basic_format_arg>; + +template +struct named_arg_store { + // args_[0].named_args points to named_args to avoid bloating format_args. + arg_t args[1u + NUM_ARGS]; + named_arg_info + named_args[static_cast(NUM_NAMED_ARGS)]; + + template + FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values) + : args{{named_args, NUM_NAMED_ARGS}, values...} { + int arg_index = 0, named_arg_index = 0; + FMT_APPLY_VARIADIC( + init_named_arg(named_args, arg_index, named_arg_index, values)); + } + + named_arg_store(named_arg_store&& rhs) { + args[0] = {named_args, NUM_NAMED_ARGS}; + for (size_t i = 1; i < sizeof(args) / sizeof(*args); ++i) + args[i] = rhs.args[i]; + for (size_t i = 0; i < NUM_NAMED_ARGS; ++i) + named_args[i] = rhs.named_args[i]; + } + + named_arg_store(const named_arg_store& rhs) = delete; + auto operator=(const named_arg_store& rhs) -> named_arg_store& = delete; + auto operator=(named_arg_store&& rhs) -> named_arg_store& = delete; + operator const arg_t*() const { return args + 1; } +}; + +// An array of references to arguments. It can be implicitly converted to +// `basic_format_args` for passing into type-erased formatting functions +// such as `vformat`. It is a plain struct to reduce binary size in debug mode. +template +struct format_arg_store { + // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. + using type = + conditional_t[max_of(1, NUM_ARGS)], + named_arg_store>; + type args; +}; + +// TYPE can be different from type_constant, e.g. for __float128. +template struct native_formatter { + private: + dynamic_format_specs specs_; + + public: + using nonlocking = void; + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin(); + auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE); + if (const_check(TYPE == type::char_type)) check_char_specs(specs_); + return end; + } + + template + FMT_CONSTEXPR void set_debug_format(bool set = true) { + specs_.set_type(set ? presentation_type::debug : presentation_type::none); + } + + FMT_PRAGMA_CLANG(diagnostic ignored "-Wundefined-inline") + template + FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const + -> decltype(ctx.out()); +}; + +template +struct locking + : bool_constant::value == type::custom_type> {}; +template +struct locking>::nonlocking>> + : std::false_type {}; + +template FMT_CONSTEXPR inline auto is_locking() -> bool { + return locking::value; +} +template +FMT_CONSTEXPR inline auto is_locking() -> bool { + return locking::value || is_locking(); +} + +FMT_API void vformat_to(buffer& buf, string_view fmt, format_args args, + locale_ref loc = {}); + +#if FMT_WIN32 +FMT_API void vprint_mojibake(FILE*, string_view, format_args, bool); +#else // format_args is passed by reference since it is defined later. +inline void vprint_mojibake(FILE*, string_view, const format_args&, bool) {} +#endif +} // namespace detail + +// The main public API. + +template +FMT_CONSTEXPR void parse_context::do_check_arg_id(int arg_id) { + // Argument id is only checked at compile time during parsing because + // formatting has its own validation. + if (detail::is_constant_evaluated() && use_constexpr_cast) { + auto ctx = static_cast*>(this); + if (arg_id >= ctx->num_args()) report_error("argument not found"); + } +} + +template +FMT_CONSTEXPR void parse_context::check_dynamic_spec(int arg_id) { + using detail::compile_parse_context; + if (detail::is_constant_evaluated() && use_constexpr_cast) + static_cast*>(this)->check_dynamic_spec(arg_id); +} + +FMT_BEGIN_EXPORT + +// An output iterator that appends to a buffer. It is used instead of +// back_insert_iterator to reduce symbol sizes and avoid dependency. +template class basic_appender { + protected: + detail::buffer* container; + + public: + using container_type = detail::buffer; + + FMT_CONSTEXPR basic_appender(detail::buffer& buf) : container(&buf) {} + + FMT_CONSTEXPR20 auto operator=(T c) -> basic_appender& { + container->push_back(c); + return *this; + } + FMT_CONSTEXPR20 auto operator*() -> basic_appender& { return *this; } + FMT_CONSTEXPR20 auto operator++() -> basic_appender& { return *this; } + FMT_CONSTEXPR20 auto operator++(int) -> basic_appender { return *this; } +}; + +// A formatting argument. Context is a template parameter for the compiled API +// where output can be unbuffered. +template class basic_format_arg { + private: + detail::value value_; + detail::type type_; + + friend class basic_format_args; + + using char_type = typename Context::char_type; + + public: + class handle { + private: + detail::custom_value custom_; + + public: + explicit handle(detail::custom_value custom) : custom_(custom) {} + + void format(parse_context& parse_ctx, Context& ctx) const { + custom_.format(custom_.value, parse_ctx, ctx); + } + }; + + constexpr basic_format_arg() : type_(detail::type::none_type) {} + basic_format_arg(const detail::named_arg_info* args, size_t size) + : value_(args, size) {} + template + basic_format_arg(T&& val) + : value_(val), type_(detail::stored_type_constant::value) {} + + constexpr explicit operator bool() const noexcept { + return type_ != detail::type::none_type; + } + auto type() const -> detail::type { return type_; } + + /** + * Visits an argument dispatching to the appropriate visit method based on + * the argument type. For example, if the argument type is `double` then + * `vis(value)` will be called with the value of type `double`. + */ + template + FMT_CONSTEXPR FMT_INLINE auto visit(Visitor&& vis) const -> decltype(vis(0)) { + using detail::map; + switch (type_) { + case detail::type::none_type: break; + case detail::type::int_type: return vis(value_.int_value); + case detail::type::uint_type: return vis(value_.uint_value); + case detail::type::long_long_type: return vis(value_.long_long_value); + case detail::type::ulong_long_type: return vis(value_.ulong_long_value); + case detail::type::int128_type: return vis(map(value_.int128_value)); + case detail::type::uint128_type: return vis(map(value_.uint128_value)); + case detail::type::bool_type: return vis(value_.bool_value); + case detail::type::char_type: return vis(value_.char_value); + case detail::type::float_type: return vis(value_.float_value); + case detail::type::double_type: return vis(value_.double_value); + case detail::type::long_double_type: return vis(value_.long_double_value); + case detail::type::cstring_type: return vis(value_.string.data); + case detail::type::string_type: return vis(value_.string.str()); + case detail::type::pointer_type: return vis(value_.pointer); + case detail::type::custom_type: return vis(handle(value_.custom)); + } + return vis(monostate()); + } + + auto format_custom(const char_type* parse_begin, + parse_context& parse_ctx, Context& ctx) + -> bool { + if (type_ != detail::type::custom_type) return false; + parse_ctx.advance_to(parse_begin); + value_.custom.format(value_.custom.value, parse_ctx, ctx); + return true; + } +}; + +/** + * A view of a collection of formatting arguments. To avoid lifetime issues it + * should only be used as a parameter type in type-erased functions such as + * `vformat`: + * + * void vlog(fmt::string_view fmt, fmt::format_args args); // OK + * fmt::format_args args = fmt::make_format_args(); // Dangling reference + */ +template class basic_format_args { + private: + // A descriptor that contains information about formatting arguments. + // If the number of arguments is less or equal to max_packed_args then + // argument types are passed in the descriptor. This reduces binary code size + // per formatting function call. + unsigned long long desc_; + union { + // If is_packed() returns true then argument values are stored in values_; + // otherwise they are stored in args_. This is done to improve cache + // locality and reduce compiled code size since storing larger objects + // may require more code (at least on x86-64) even if the same amount of + // data is actually copied to stack. It saves ~10% on the bloat test. + const detail::value* values_; + const basic_format_arg* args_; + }; + + constexpr auto is_packed() const -> bool { + return (desc_ & detail::is_unpacked_bit) == 0; + } + constexpr auto has_named_args() const -> bool { + return (desc_ & detail::has_named_args_bit) != 0; + } + + FMT_CONSTEXPR auto type(int index) const -> detail::type { + int shift = index * detail::packed_arg_bits; + unsigned mask = (1 << detail::packed_arg_bits) - 1; + return static_cast((desc_ >> shift) & mask); + } + + template + using store = + detail::format_arg_store; + + public: + using format_arg = basic_format_arg; + + constexpr basic_format_args() : desc_(0), args_(nullptr) {} + + /// Constructs a `basic_format_args` object from `format_arg_store`. + template + constexpr FMT_ALWAYS_INLINE basic_format_args( + const store& s) + : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)), + values_(s.args) {} + + template detail::max_packed_args)> + constexpr basic_format_args(const store& s) + : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)), + args_(s.args) {} + + /// Constructs a `basic_format_args` object from a dynamic list of arguments. + constexpr basic_format_args(const format_arg* args, int count, + bool has_named = false) + : desc_(detail::is_unpacked_bit | detail::to_unsigned(count) | + (has_named ? +detail::has_named_args_bit : 0)), + args_(args) {} + + /// Returns the argument with the specified id. + FMT_CONSTEXPR auto get(int id) const -> format_arg { + auto arg = format_arg(); + if (!is_packed()) { + if (id < max_size()) arg = args_[id]; + return arg; + } + if (static_cast(id) >= detail::max_packed_args) return arg; + arg.type_ = type(id); + if (arg.type_ != detail::type::none_type) arg.value_ = values_[id]; + return arg; + } + + template + auto get(basic_string_view name) const -> format_arg { + int id = get_id(name); + return id >= 0 ? get(id) : format_arg(); + } + + template + FMT_CONSTEXPR auto get_id(basic_string_view name) const -> int { + if (!has_named_args()) return -1; + const auto& named_args = + (is_packed() ? values_[-1] : args_[-1].value_).named_args; + for (size_t i = 0; i < named_args.size; ++i) { + if (named_args.data[i].name == name) return named_args.data[i].id; + } + return -1; + } + + auto max_size() const -> int { + unsigned long long max_packed = detail::max_packed_args; + return static_cast(is_packed() ? max_packed + : desc_ & ~detail::is_unpacked_bit); + } +}; + +// A formatting context. +class context { + private: + appender out_; + format_args args_; + FMT_NO_UNIQUE_ADDRESS locale_ref loc_; + + public: + using char_type = char; ///< The character type for the output. + using iterator = appender; + using format_arg = basic_format_arg; + enum { builtin_types = FMT_BUILTIN_TYPES }; + + /// Constructs a `context` object. References to the arguments are stored + /// in the object so make sure they have appropriate lifetimes. + FMT_CONSTEXPR context(iterator out, format_args args, locale_ref loc = {}) + : out_(out), args_(args), loc_(loc) {} + context(context&&) = default; + context(const context&) = delete; + void operator=(const context&) = delete; + + FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); } + inline auto arg(string_view name) const -> format_arg { + return args_.get(name); + } + FMT_CONSTEXPR auto arg_id(string_view name) const -> int { + return args_.get_id(name); + } + auto args() const -> const format_args& { return args_; } + + // Returns an iterator to the beginning of the output range. + FMT_CONSTEXPR auto out() const -> iterator { return out_; } + + // Advances the begin iterator to `it`. + FMT_CONSTEXPR void advance_to(iterator) {} + + FMT_CONSTEXPR auto locale() const -> locale_ref { return loc_; } +}; + +template struct runtime_format_string { + basic_string_view str; +}; + +/** + * Creates a runtime format string. + * + * **Example**: + * + * // Check format string at runtime instead of compile-time. + * fmt::print(fmt::runtime("{:d}"), "I am not a number"); + */ +inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; } + +/// A compile-time format string. Use `format_string` in the public API to +/// prevent type deduction. +template struct fstring { + private: + static constexpr int num_static_named_args = + detail::count_static_named_args(); + + using checker = detail::format_string_checker< + char, static_cast(sizeof...(T)), num_static_named_args, + num_static_named_args != detail::count_named_args()>; + + using arg_pack = detail::arg_pack; + + public: + string_view str; + using t = fstring; + + // Reports a compile-time error if S is not a valid format string for T. + template + FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const char (&s)[N]) : str(s, N - 1) { + using namespace detail; + static_assert(count<(is_view>::value && + std::is_reference::value)...>() == 0, + "passing views as lvalues is disallowed"); + if (FMT_USE_CONSTEVAL) parse_format_string(s, checker(s, arg_pack())); +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert( + FMT_USE_CONSTEVAL && sizeof(s) != 0, + "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING"); +#endif + } + template ::value)> + FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const S& s) : str(s) { + auto sv = string_view(str); + if (FMT_USE_CONSTEVAL) + detail::parse_format_string(sv, checker(sv, arg_pack())); +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert( + FMT_USE_CONSTEVAL && sizeof(s) != 0, + "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING"); +#endif + } + template ::value&& + std::is_same::value)> + FMT_ALWAYS_INLINE fstring(const S&) : str(S()) { + FMT_CONSTEXPR auto sv = string_view(S()); + FMT_CONSTEXPR int unused = + (parse_format_string(sv, checker(sv, arg_pack())), 0); + detail::ignore_unused(unused); + } + fstring(runtime_format_string<> fmt) : str(fmt.str) {} + + // Returning by reference generates better code in debug mode. + FMT_ALWAYS_INLINE operator const string_view&() const { return str; } + auto get() const -> string_view { return str; } +}; + +template using format_string = typename fstring::t; + +template +using is_formattable = bool_constant::value, int*, T>, Char>, + void>::value>; +#ifdef __cpp_concepts +template +concept formattable = is_formattable, Char>::value; +#endif + +// A formatter specialization for natively supported types. +template +struct formatter::value != + detail::type::custom_type>> + : detail::native_formatter::value> { +}; + +/** + * Constructs an object that stores references to arguments and can be + * implicitly converted to `format_args`. `Context` can be omitted in which case + * it defaults to `context`. See `arg` for lifetime considerations. + */ +// Take arguments by lvalue references to avoid some lifetime issues, e.g. +// auto args = make_format_args(std::string()); +template (), + unsigned long long DESC = detail::make_descriptor()> +constexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args) + -> detail::format_arg_store { + // Suppress warnings for pathological types convertible to detail::value. + FMT_PRAGMA_GCC(diagnostic ignored "-Wconversion") + return {{args...}}; +} + +template +using vargs = + detail::format_arg_store(), + detail::make_descriptor()>; + +/** + * Returns a named argument to be used in a formatting function. + * It should only be used in a call to a formatting function. + * + * **Example**: + * + * fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); + */ +template +inline auto arg(const Char* name, const T& arg) -> detail::named_arg { + return {name, arg}; +} + +/// Formats a string and writes the output to `out`. +template , + char>::value)> +auto vformat_to(OutputIt&& out, string_view fmt, format_args args) + -> remove_cvref_t { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, fmt, args, {}); + return detail::get_iterator(buf, out); +} + +/** + * Formats `args` according to specifications in `fmt`, writes the result to + * the output iterator `out` and returns the iterator past the end of the output + * range. `format_to` does not append a terminating null character. + * + * **Example**: + * + * auto out = std::vector(); + * fmt::format_to(std::back_inserter(out), "{}", 42); + */ +template , + char>::value)> +FMT_INLINE auto format_to(OutputIt&& out, format_string fmt, T&&... args) + -> remove_cvref_t { + return vformat_to(out, fmt.str, vargs{{args...}}); +} + +template struct format_to_n_result { + /// Iterator past the end of the output range. + OutputIt out; + /// Total (not truncated) output size. + size_t size; +}; + +template ::value)> +auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + detail::vformat_to(buf, fmt, args, {}); + return {buf.out(), buf.count()}; +} + +/** + * Formats `args` according to specifications in `fmt`, writes up to `n` + * characters of the result to the output iterator `out` and returns the total + * (not truncated) output size and the iterator past the end of the output + * range. `format_to_n` does not append a terminating null character. + */ +template ::value)> +FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string fmt, + T&&... args) -> format_to_n_result { + return vformat_to_n(out, n, fmt.str, vargs{{args...}}); +} + +struct format_to_result { + /// Pointer to just after the last successful write in the array. + char* out; + /// Specifies if the output was truncated. + bool truncated; + + FMT_CONSTEXPR operator char*() const { + // Report truncation to prevent silent data loss. + if (truncated) report_error("output is truncated"); + return out; + } +}; + +template +auto vformat_to(char (&out)[N], string_view fmt, format_args args) + -> format_to_result { + auto result = vformat_to_n(out, N, fmt, args); + return {result.out, result.size > N}; +} + +template +FMT_INLINE auto format_to(char (&out)[N], format_string fmt, T&&... args) + -> format_to_result { + auto result = vformat_to_n(out, N, fmt.str, vargs{{args...}}); + return {result.out, result.size > N}; +} + +/// Returns the number of chars in the output of `format(fmt, args...)`. +template +FMT_NODISCARD FMT_INLINE auto formatted_size(format_string fmt, + T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + detail::vformat_to(buf, fmt.str, vargs{{args...}}, {}); + return buf.count(); +} + +FMT_API void vprint(string_view fmt, format_args args); +FMT_API void vprint(FILE* f, string_view fmt, format_args args); +FMT_API void vprintln(FILE* f, string_view fmt, format_args args); +FMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args); + +/** + * Formats `args` according to specifications in `fmt` and writes the output + * to `stdout`. + * + * **Example**: + * + * fmt::print("The answer is {}.", 42); + */ +template +FMT_INLINE void print(format_string fmt, T&&... args) { + vargs va = {{args...}}; + if (detail::const_check(!detail::use_utf8)) + return detail::vprint_mojibake(stdout, fmt.str, va, false); + return detail::is_locking() ? vprint_buffered(stdout, fmt.str, va) + : vprint(fmt.str, va); +} + +/** + * Formats `args` according to specifications in `fmt` and writes the + * output to the file `f`. + * + * **Example**: + * + * fmt::print(stderr, "Don't {}!", "panic"); + */ +template +FMT_INLINE void print(FILE* f, format_string fmt, T&&... args) { + vargs va = {{args...}}; + if (detail::const_check(!detail::use_utf8)) + return detail::vprint_mojibake(f, fmt.str, va, false); + return detail::is_locking() ? vprint_buffered(f, fmt.str, va) + : vprint(f, fmt.str, va); +} + +/// Formats `args` according to specifications in `fmt` and writes the output +/// to the file `f` followed by a newline. +template +FMT_INLINE void println(FILE* f, format_string fmt, T&&... args) { + vargs va = {{args...}}; + return detail::const_check(detail::use_utf8) + ? vprintln(f, fmt.str, va) + : detail::vprint_mojibake(f, fmt.str, va, true); +} + +/// Formats `args` according to specifications in `fmt` and writes the output +/// to `stdout` followed by a newline. +template +FMT_INLINE void println(format_string fmt, T&&... args) { + return fmt::println(stdout, fmt, static_cast(args)...); +} + +FMT_PRAGMA_CLANG(diagnostic pop) +FMT_PRAGMA_GCC(pop_options) +FMT_END_EXPORT +FMT_END_NAMESPACE + +#ifdef FMT_HEADER_ONLY +# include "format.h" +#endif +#endif // FMT_BASE_H_ diff --git a/vendor/btop/include/fmt/chrono.h b/vendor/btop/include/fmt/chrono.h new file mode 100644 index 000000000..a788d3ecf --- /dev/null +++ b/vendor/btop/include/fmt/chrono.h @@ -0,0 +1,2241 @@ +// Formatting library for C++ - chrono support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_CHRONO_H_ +#define FMT_CHRONO_H_ + +#ifndef FMT_MODULE +# include +# include +# include // std::isfinite +# include // std::memcpy +# include +# include +# include +# include +# include +#endif + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +// Enable safe chrono durations, unless explicitly disabled. +#ifndef FMT_SAFE_DURATION_CAST +# define FMT_SAFE_DURATION_CAST 1 +#endif +#if FMT_SAFE_DURATION_CAST + +// For conversion between std::chrono::durations without undefined +// behaviour or erroneous results. +// This is a stripped down version of duration_cast, for inclusion in fmt. +// See https://github.com/pauldreik/safe_duration_cast +// +// Copyright Paul Dreik 2019 +namespace safe_duration_cast { + +// DEPRECATED! +template ::value && + std::numeric_limits::is_signed == + std::numeric_limits::is_signed)> +FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec) + -> To { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + + // A and B are both signed, or both unsigned. + if (detail::const_check(F::digits <= T::digits)) { + // From fits in To without any problem. + } else { + // From does not always fit in To, resort to a dynamic check. + if (from < (T::min)() || from > (T::max)()) { + // outside range. + ec = 1; + return {}; + } + } + return static_cast(from); +} + +/// Converts From to To, without loss. If the dynamic value of from +/// can't be converted to To without loss, ec is set. +template ::value && + std::numeric_limits::is_signed != + std::numeric_limits::is_signed)> +FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec) + -> To { + ec = 0; + using F = std::numeric_limits; + using T = std::numeric_limits; + static_assert(F::is_integer, "From must be integral"); + static_assert(T::is_integer, "To must be integral"); + + if (detail::const_check(F::is_signed && !T::is_signed)) { + // From may be negative, not allowed! + if (fmt::detail::is_negative(from)) { + ec = 1; + return {}; + } + // From is positive. Can it always fit in To? + if (detail::const_check(F::digits > T::digits) && + from > static_cast(detail::max_value())) { + ec = 1; + return {}; + } + } + + if (detail::const_check(!F::is_signed && T::is_signed && + F::digits >= T::digits) && + from > static_cast(detail::max_value())) { + ec = 1; + return {}; + } + return static_cast(from); // Lossless conversion. +} + +template ::value)> +FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec) + -> To { + ec = 0; + return from; +} // function + +// clang-format off +/** + * converts From to To if possible, otherwise ec is set. + * + * input | output + * ---------------------------------|--------------- + * NaN | NaN + * Inf | Inf + * normal, fits in output | converted (possibly lossy) + * normal, does not fit in output | ec is set + * subnormal | best effort + * -Inf | -Inf + */ +// clang-format on +template ::value)> +FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To { + ec = 0; + using T = std::numeric_limits; + static_assert(std::is_floating_point::value, "From must be floating"); + static_assert(std::is_floating_point::value, "To must be floating"); + + // catch the only happy case + if (std::isfinite(from)) { + if (from >= T::lowest() && from <= (T::max)()) { + return static_cast(from); + } + // not within range. + ec = 1; + return {}; + } + + // nan and inf will be preserved + return static_cast(from); +} // function + +template ::value)> +FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To { + ec = 0; + static_assert(std::is_floating_point::value, "From must be floating"); + return from; +} + +/// Safe duration_cast between floating point durations +template ::value), + FMT_ENABLE_IF(std::is_floating_point::value)> +auto safe_duration_cast(std::chrono::duration from, + int& ec) -> To { + using From = std::chrono::duration; + ec = 0; + + // the basic idea is that we need to convert from count() in the from type + // to count() in the To type, by multiplying it with this: + struct Factor + : std::ratio_divide {}; + + static_assert(Factor::num > 0, "num must be positive"); + static_assert(Factor::den > 0, "den must be positive"); + + // the conversion is like this: multiply from.count() with Factor::num + // /Factor::den and convert it to To::rep, all this without + // overflow/underflow. let's start by finding a suitable type that can hold + // both To, From and Factor::num + using IntermediateRep = + typename std::common_type::type; + + // force conversion of From::rep -> IntermediateRep to be safe, + // even if it will never happen be narrowing in this context. + IntermediateRep count = + safe_float_conversion(from.count(), ec); + if (ec) { + return {}; + } + + // multiply with Factor::num without overflow or underflow + if (detail::const_check(Factor::num != 1)) { + constexpr auto max1 = detail::max_value() / + static_cast(Factor::num); + if (count > max1) { + ec = 1; + return {}; + } + constexpr auto min1 = std::numeric_limits::lowest() / + static_cast(Factor::num); + if (count < min1) { + ec = 1; + return {}; + } + count *= static_cast(Factor::num); + } + + // this can't go wrong, right? den>0 is checked earlier. + if (detail::const_check(Factor::den != 1)) { + using common_t = typename std::common_type::type; + count /= static_cast(Factor::den); + } + + // convert to the to type, safely + using ToRep = typename To::rep; + + const ToRep tocount = safe_float_conversion(count, ec); + if (ec) { + return {}; + } + return To{tocount}; +} +} // namespace safe_duration_cast +#endif + +namespace detail { + +// Check if std::chrono::utc_time is available. +#ifdef FMT_USE_UTC_TIME +// Use the provided definition. +#elif defined(__cpp_lib_chrono) +# define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L) +#else +# define FMT_USE_UTC_TIME 0 +#endif +#if FMT_USE_UTC_TIME +using utc_clock = std::chrono::utc_clock; +#else +struct utc_clock { + template void to_sys(T); +}; +#endif + +// Check if std::chrono::local_time is available. +#ifdef FMT_USE_LOCAL_TIME +// Use the provided definition. +#elif defined(__cpp_lib_chrono) +# define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L) +#else +# define FMT_USE_LOCAL_TIME 0 +#endif +#if FMT_USE_LOCAL_TIME +using local_t = std::chrono::local_t; +#else +struct local_t {}; +#endif + +} // namespace detail + +template +using sys_time = std::chrono::time_point; + +template +using utc_time = std::chrono::time_point; + +template +using local_time = std::chrono::time_point; + +namespace detail { + +// Prevents expansion of a preceding token as a function-style macro. +// Usage: f FMT_NOMACRO() +#define FMT_NOMACRO + +template struct null {}; +inline auto gmtime_r(...) -> null<> { return null<>(); } +inline auto gmtime_s(...) -> null<> { return null<>(); } + +// It is defined here and not in ostream.h because the latter has expensive +// includes. +template class formatbuf : public StreamBuf { + private: + using char_type = typename StreamBuf::char_type; + using streamsize = decltype(std::declval().sputn(nullptr, 0)); + using int_type = typename StreamBuf::int_type; + using traits_type = typename StreamBuf::traits_type; + + buffer& buffer_; + + public: + explicit formatbuf(buffer& buf) : buffer_(buf) {} + + protected: + // The put area is always empty. This makes the implementation simpler and has + // the advantage that the streambuf and the buffer are always in sync and + // sputc never writes into uninitialized memory. A disadvantage is that each + // call to sputc always results in a (virtual) call to overflow. There is no + // disadvantage here for sputn since this always results in a call to xsputn. + + auto overflow(int_type ch) -> int_type override { + if (!traits_type::eq_int_type(ch, traits_type::eof())) + buffer_.push_back(static_cast(ch)); + return ch; + } + + auto xsputn(const char_type* s, streamsize count) -> streamsize override { + buffer_.append(s, s + count); + return count; + } +}; + +inline auto get_classic_locale() -> const std::locale& { + static const auto& locale = std::locale::classic(); + return locale; +} + +template struct codecvt_result { + static constexpr size_t max_size = 32; + CodeUnit buf[max_size]; + CodeUnit* end; +}; + +template +void write_codecvt(codecvt_result& out, string_view in, + const std::locale& loc) { + FMT_PRAGMA_CLANG(diagnostic push) + FMT_PRAGMA_CLANG(diagnostic ignored "-Wdeprecated") + auto& f = std::use_facet>(loc); + FMT_PRAGMA_CLANG(diagnostic pop) + auto mb = std::mbstate_t(); + const char* from_next = nullptr; + auto result = f.in(mb, in.begin(), in.end(), from_next, std::begin(out.buf), + std::end(out.buf), out.end); + if (result != std::codecvt_base::ok) + FMT_THROW(format_error("failed to format time")); +} + +template +auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc) + -> OutputIt { + if (const_check(detail::use_utf8) && loc != get_classic_locale()) { + // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and + // gcc-4. +#if FMT_MSC_VERSION != 0 || \ + (defined(__GLIBCXX__) && \ + (!defined(_GLIBCXX_USE_DUAL_ABI) || _GLIBCXX_USE_DUAL_ABI == 0)) + // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5 + // and newer. + using code_unit = wchar_t; +#else + using code_unit = char32_t; +#endif + + using unit_t = codecvt_result; + unit_t unit; + write_codecvt(unit, in, loc); + // In UTF-8 is used one to four one-byte code units. + auto u = + to_utf8>(); + if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)})) + FMT_THROW(format_error("failed to format time")); + return copy(u.c_str(), u.c_str() + u.size(), out); + } + return copy(in.data(), in.data() + in.size(), out); +} + +template ::value)> +auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc) + -> OutputIt { + codecvt_result unit; + write_codecvt(unit, sv, loc); + return copy(unit.buf, unit.end, out); +} + +template ::value)> +auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc) + -> OutputIt { + return write_encoded_tm_str(out, sv, loc); +} + +template +inline void do_write(buffer& buf, const std::tm& time, + const std::locale& loc, char format, char modifier) { + auto&& format_buf = formatbuf>(buf); + auto&& os = std::basic_ostream(&format_buf); + os.imbue(loc); + const auto& facet = std::use_facet>(loc); + auto end = facet.put(os, os, Char(' '), &time, format, modifier); + if (end.failed()) FMT_THROW(format_error("failed to format time")); +} + +template ::value)> +auto write(OutputIt out, const std::tm& time, const std::locale& loc, + char format, char modifier = 0) -> OutputIt { + auto&& buf = get_buffer(out); + do_write(buf, time, loc, format, modifier); + return get_iterator(buf, out); +} + +template ::value)> +auto write(OutputIt out, const std::tm& time, const std::locale& loc, + char format, char modifier = 0) -> OutputIt { + auto&& buf = basic_memory_buffer(); + do_write(buf, time, loc, format, modifier); + return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc); +} + +template +using is_similar_arithmetic_type = + bool_constant<(std::is_integral::value && std::is_integral::value) || + (std::is_floating_point::value && + std::is_floating_point::value)>; + +FMT_NORETURN inline void throw_duration_error() { + FMT_THROW(format_error("cannot format duration")); +} + +// Cast one integral duration to another with an overflow check. +template ::value&& + std::is_integral::value)> +auto duration_cast(std::chrono::duration from) -> To { +#if !FMT_SAFE_DURATION_CAST + return std::chrono::duration_cast(from); +#else + // The conversion factor: to.count() == factor * from.count(). + using factor = std::ratio_divide; + + using common_rep = typename std::common_type::type; + common_rep count = from.count(); // This conversion is lossless. + + // Multiply from.count() by factor and check for overflow. + if (const_check(factor::num != 1)) { + if (count > max_value() / factor::num) throw_duration_error(); + const auto min = (std::numeric_limits::min)() / factor::num; + if (const_check(!std::is_unsigned::value) && count < min) + throw_duration_error(); + count *= factor::num; + } + if (const_check(factor::den != 1)) count /= factor::den; + int ec = 0; + auto to = + To(safe_duration_cast::lossless_integral_conversion( + count, ec)); + if (ec) throw_duration_error(); + return to; +#endif +} + +template ::value&& + std::is_floating_point::value)> +auto duration_cast(std::chrono::duration from) -> To { +#if FMT_SAFE_DURATION_CAST + // Preserve infinity and NaN. + if (!isfinite(from.count())) return static_cast(from.count()); + // Throwing version of safe_duration_cast is only available for + // integer to integer or float to float casts. + int ec; + To to = safe_duration_cast::safe_duration_cast(from, ec); + if (ec) throw_duration_error(); + return to; +#else + // Standard duration cast, may overflow. + return std::chrono::duration_cast(from); +#endif +} + +template ::value)> +auto duration_cast(std::chrono::duration from) -> To { + // Mixed integer <-> float cast is not supported by safe duration_cast. + return std::chrono::duration_cast(from); +} + +template +auto to_time_t(sys_time time_point) -> std::time_t { + // Cannot use std::chrono::system_clock::to_time_t since this would first + // require a cast to std::chrono::system_clock::time_point, which could + // overflow. + return detail::duration_cast>( + time_point.time_since_epoch()) + .count(); +} + +} // namespace detail + +FMT_BEGIN_EXPORT + +/** + * Converts given time since epoch as `std::time_t` value into calendar time, + * expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this + * function is thread-safe on most platforms. + */ +inline auto gmtime(std::time_t time) -> std::tm { + struct dispatcher { + std::time_t time_; + std::tm tm_; + + inline dispatcher(std::time_t t) : time_(t) {} + + inline auto run() -> bool { + using namespace fmt::detail; + return handle(gmtime_r(&time_, &tm_)); + } + + inline auto handle(std::tm* tm) -> bool { return tm != nullptr; } + + inline auto handle(detail::null<>) -> bool { + using namespace fmt::detail; + return fallback(gmtime_s(&tm_, &time_)); + } + + inline auto fallback(int res) -> bool { return res == 0; } + +#if !FMT_MSC_VERSION + inline auto fallback(detail::null<>) -> bool { + std::tm* tm = std::gmtime(&time_); + if (tm) tm_ = *tm; + return tm != nullptr; + } +#endif + }; + auto gt = dispatcher(time); + // Too big time values may be unsupported. + if (!gt.run()) FMT_THROW(format_error("time_t value out of range")); + return gt.tm_; +} + +template +inline auto gmtime(sys_time time_point) -> std::tm { + return gmtime(detail::to_time_t(time_point)); +} + +namespace detail { + +// Writes two-digit numbers a, b and c separated by sep to buf. +// The method by Pavel Novikov based on +// https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/. +inline void write_digit2_separated(char* buf, unsigned a, unsigned b, + unsigned c, char sep) { + unsigned long long digits = + a | (b << 24) | (static_cast(c) << 48); + // Convert each value to BCD. + // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b. + // The difference is + // y - x = a * 6 + // a can be found from x: + // a = floor(x / 10) + // then + // y = x + a * 6 = x + floor(x / 10) * 6 + // floor(x / 10) is (x * 205) >> 11 (needs 16 bits). + digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6; + // Put low nibbles to high bytes and high nibbles to low bytes. + digits = ((digits & 0x00f00000f00000f0) >> 4) | + ((digits & 0x000f00000f00000f) << 8); + auto usep = static_cast(sep); + // Add ASCII '0' to each digit byte and insert separators. + digits |= 0x3030003030003030 | (usep << 16) | (usep << 40); + + constexpr size_t len = 8; + if (const_check(is_big_endian())) { + char tmp[len]; + std::memcpy(tmp, &digits, len); + std::reverse_copy(tmp, tmp + len, buf); + } else { + std::memcpy(buf, &digits, len); + } +} + +template +FMT_CONSTEXPR inline auto get_units() -> const char* { + if (std::is_same::value) return "as"; + if (std::is_same::value) return "fs"; + if (std::is_same::value) return "ps"; + if (std::is_same::value) return "ns"; + if (std::is_same::value) + return detail::use_utf8 ? "µs" : "us"; + if (std::is_same::value) return "ms"; + if (std::is_same::value) return "cs"; + if (std::is_same::value) return "ds"; + if (std::is_same>::value) return "s"; + if (std::is_same::value) return "das"; + if (std::is_same::value) return "hs"; + if (std::is_same::value) return "ks"; + if (std::is_same::value) return "Ms"; + if (std::is_same::value) return "Gs"; + if (std::is_same::value) return "Ts"; + if (std::is_same::value) return "Ps"; + if (std::is_same::value) return "Es"; + if (std::is_same>::value) return "min"; + if (std::is_same>::value) return "h"; + if (std::is_same>::value) return "d"; + return nullptr; +} + +enum class numeric_system { + standard, + // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale. + alternative +}; + +// Glibc extensions for formatting numeric values. +enum class pad_type { + // Pad a numeric result string with zeros (the default). + zero, + // Do not pad a numeric result string. + none, + // Pad a numeric result string with spaces. + space, +}; + +template +auto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt { + if (pad == pad_type::none) return out; + return detail::fill_n(out, width, pad == pad_type::space ? ' ' : '0'); +} + +template +auto write_padding(OutputIt out, pad_type pad) -> OutputIt { + if (pad != pad_type::none) *out++ = pad == pad_type::space ? ' ' : '0'; + return out; +} + +// Parses a put_time-like format string and invokes handler actions. +template +FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + if (begin == end || *begin == '}') return begin; + if (*begin != '%') FMT_THROW(format_error("invalid format")); + auto ptr = begin; + while (ptr != end) { + pad_type pad = pad_type::zero; + auto c = *ptr; + if (c == '}') break; + if (c != '%') { + ++ptr; + continue; + } + if (begin != ptr) handler.on_text(begin, ptr); + ++ptr; // consume '%' + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr; + switch (c) { + case '_': + pad = pad_type::space; + ++ptr; + break; + case '-': + pad = pad_type::none; + ++ptr; + break; + } + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case '%': handler.on_text(ptr - 1, ptr); break; + case 'n': { + const Char newline[] = {'\n'}; + handler.on_text(newline, newline + 1); + break; + } + case 't': { + const Char tab[] = {'\t'}; + handler.on_text(tab, tab + 1); + break; + } + // Year: + case 'Y': handler.on_year(numeric_system::standard, pad); break; + case 'y': handler.on_short_year(numeric_system::standard); break; + case 'C': handler.on_century(numeric_system::standard); break; + case 'G': handler.on_iso_week_based_year(); break; + case 'g': handler.on_iso_week_based_short_year(); break; + // Day of the week: + case 'a': handler.on_abbr_weekday(); break; + case 'A': handler.on_full_weekday(); break; + case 'w': handler.on_dec0_weekday(numeric_system::standard); break; + case 'u': handler.on_dec1_weekday(numeric_system::standard); break; + // Month: + case 'b': + case 'h': handler.on_abbr_month(); break; + case 'B': handler.on_full_month(); break; + case 'm': handler.on_dec_month(numeric_system::standard, pad); break; + // Day of the year/month: + case 'U': + handler.on_dec0_week_of_year(numeric_system::standard, pad); + break; + case 'W': + handler.on_dec1_week_of_year(numeric_system::standard, pad); + break; + case 'V': handler.on_iso_week_of_year(numeric_system::standard, pad); break; + case 'j': handler.on_day_of_year(pad); break; + case 'd': handler.on_day_of_month(numeric_system::standard, pad); break; + case 'e': + handler.on_day_of_month(numeric_system::standard, pad_type::space); + break; + // Hour, minute, second: + case 'H': handler.on_24_hour(numeric_system::standard, pad); break; + case 'I': handler.on_12_hour(numeric_system::standard, pad); break; + case 'M': handler.on_minute(numeric_system::standard, pad); break; + case 'S': handler.on_second(numeric_system::standard, pad); break; + // Other: + case 'c': handler.on_datetime(numeric_system::standard); break; + case 'x': handler.on_loc_date(numeric_system::standard); break; + case 'X': handler.on_loc_time(numeric_system::standard); break; + case 'D': handler.on_us_date(); break; + case 'F': handler.on_iso_date(); break; + case 'r': handler.on_12_hour_time(); break; + case 'R': handler.on_24_hour_time(); break; + case 'T': handler.on_iso_time(); break; + case 'p': handler.on_am_pm(); break; + case 'Q': handler.on_duration_value(); break; + case 'q': handler.on_duration_unit(); break; + case 'z': handler.on_utc_offset(numeric_system::standard); break; + case 'Z': handler.on_tz_name(); break; + // Alternative representation: + case 'E': { + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'Y': handler.on_year(numeric_system::alternative, pad); break; + case 'y': handler.on_offset_year(); break; + case 'C': handler.on_century(numeric_system::alternative); break; + case 'c': handler.on_datetime(numeric_system::alternative); break; + case 'x': handler.on_loc_date(numeric_system::alternative); break; + case 'X': handler.on_loc_time(numeric_system::alternative); break; + case 'z': handler.on_utc_offset(numeric_system::alternative); break; + default: FMT_THROW(format_error("invalid format")); + } + break; + } + case 'O': + if (ptr == end) FMT_THROW(format_error("invalid format")); + c = *ptr++; + switch (c) { + case 'y': handler.on_short_year(numeric_system::alternative); break; + case 'm': handler.on_dec_month(numeric_system::alternative, pad); break; + case 'U': + handler.on_dec0_week_of_year(numeric_system::alternative, pad); + break; + case 'W': + handler.on_dec1_week_of_year(numeric_system::alternative, pad); + break; + case 'V': + handler.on_iso_week_of_year(numeric_system::alternative, pad); + break; + case 'd': + handler.on_day_of_month(numeric_system::alternative, pad); + break; + case 'e': + handler.on_day_of_month(numeric_system::alternative, pad_type::space); + break; + case 'w': handler.on_dec0_weekday(numeric_system::alternative); break; + case 'u': handler.on_dec1_weekday(numeric_system::alternative); break; + case 'H': handler.on_24_hour(numeric_system::alternative, pad); break; + case 'I': handler.on_12_hour(numeric_system::alternative, pad); break; + case 'M': handler.on_minute(numeric_system::alternative, pad); break; + case 'S': handler.on_second(numeric_system::alternative, pad); break; + case 'z': handler.on_utc_offset(numeric_system::alternative); break; + default: FMT_THROW(format_error("invalid format")); + } + break; + default: FMT_THROW(format_error("invalid format")); + } + begin = ptr; + } + if (begin != ptr) handler.on_text(begin, ptr); + return ptr; +} + +template struct null_chrono_spec_handler { + FMT_CONSTEXPR void unsupported() { + static_cast(this)->unsupported(); + } + FMT_CONSTEXPR void on_year(numeric_system, pad_type) { unsupported(); } + FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_offset_year() { unsupported(); } + FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); } + FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); } + FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); } + FMT_CONSTEXPR void on_full_weekday() { unsupported(); } + FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_abbr_month() { unsupported(); } + FMT_CONSTEXPR void on_full_month() { unsupported(); } + FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) { unsupported(); } + FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) { + unsupported(); + } + FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) { + unsupported(); + } + FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) { + unsupported(); + } + FMT_CONSTEXPR void on_day_of_year(pad_type) { unsupported(); } + FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) { + unsupported(); + } + FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_us_date() { unsupported(); } + FMT_CONSTEXPR void on_iso_date() { unsupported(); } + FMT_CONSTEXPR void on_12_hour_time() { unsupported(); } + FMT_CONSTEXPR void on_24_hour_time() { unsupported(); } + FMT_CONSTEXPR void on_iso_time() { unsupported(); } + FMT_CONSTEXPR void on_am_pm() { unsupported(); } + FMT_CONSTEXPR void on_duration_value() { unsupported(); } + FMT_CONSTEXPR void on_duration_unit() { unsupported(); } + FMT_CONSTEXPR void on_utc_offset(numeric_system) { unsupported(); } + FMT_CONSTEXPR void on_tz_name() { unsupported(); } +}; + +class tm_format_checker : public null_chrono_spec_handler { + private: + bool has_timezone_ = false; + + public: + constexpr explicit tm_format_checker(bool has_timezone) + : has_timezone_(has_timezone) {} + + FMT_NORETURN inline void unsupported() { + FMT_THROW(format_error("no format")); + } + + template + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + FMT_CONSTEXPR void on_year(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_short_year(numeric_system) {} + FMT_CONSTEXPR void on_offset_year() {} + FMT_CONSTEXPR void on_century(numeric_system) {} + FMT_CONSTEXPR void on_iso_week_based_year() {} + FMT_CONSTEXPR void on_iso_week_based_short_year() {} + FMT_CONSTEXPR void on_abbr_weekday() {} + FMT_CONSTEXPR void on_full_weekday() {} + FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {} + FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {} + FMT_CONSTEXPR void on_abbr_month() {} + FMT_CONSTEXPR void on_full_month() {} + FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_day_of_year(pad_type) {} + FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_second(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_datetime(numeric_system) {} + FMT_CONSTEXPR void on_loc_date(numeric_system) {} + FMT_CONSTEXPR void on_loc_time(numeric_system) {} + FMT_CONSTEXPR void on_us_date() {} + FMT_CONSTEXPR void on_iso_date() {} + FMT_CONSTEXPR void on_12_hour_time() {} + FMT_CONSTEXPR void on_24_hour_time() {} + FMT_CONSTEXPR void on_iso_time() {} + FMT_CONSTEXPR void on_am_pm() {} + FMT_CONSTEXPR void on_utc_offset(numeric_system) { + if (!has_timezone_) FMT_THROW(format_error("no timezone")); + } + FMT_CONSTEXPR void on_tz_name() { + if (!has_timezone_) FMT_THROW(format_error("no timezone")); + } +}; + +inline auto tm_wday_full_name(int wday) -> const char* { + static constexpr const char* full_name_list[] = { + "Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday"}; + return wday >= 0 && wday <= 6 ? full_name_list[wday] : "?"; +} +inline auto tm_wday_short_name(int wday) -> const char* { + static constexpr const char* short_name_list[] = {"Sun", "Mon", "Tue", "Wed", + "Thu", "Fri", "Sat"}; + return wday >= 0 && wday <= 6 ? short_name_list[wday] : "???"; +} + +inline auto tm_mon_full_name(int mon) -> const char* { + static constexpr const char* full_name_list[] = { + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December"}; + return mon >= 0 && mon <= 11 ? full_name_list[mon] : "?"; +} +inline auto tm_mon_short_name(int mon) -> const char* { + static constexpr const char* short_name_list[] = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + }; + return mon >= 0 && mon <= 11 ? short_name_list[mon] : "???"; +} + +template +struct has_tm_gmtoff : std::false_type {}; +template +struct has_tm_gmtoff> : std::true_type {}; + +template struct has_tm_zone : std::false_type {}; +template +struct has_tm_zone> : std::true_type {}; + +template ::value)> +auto set_tm_zone(T& time, char* tz) -> bool { + time.tm_zone = tz; + return true; +} +template ::value)> +auto set_tm_zone(T&, char*) -> bool { + return false; +} + +inline auto utc() -> char* { + static char tz[] = "UTC"; + return tz; +} + +// Converts value to Int and checks that it's in the range [0, upper). +template ::value)> +inline auto to_nonnegative_int(T value, Int upper) -> Int { + if (!std::is_unsigned::value && + (value < 0 || to_unsigned(value) > to_unsigned(upper))) { + FMT_THROW(format_error("chrono value is out of range")); + } + return static_cast(value); +} +template ::value)> +inline auto to_nonnegative_int(T value, Int upper) -> Int { + auto int_value = static_cast(value); + if (int_value < 0 || value > static_cast(upper)) + FMT_THROW(format_error("invalid value")); + return int_value; +} + +constexpr auto pow10(std::uint32_t n) -> long long { + return n == 0 ? 1 : 10 * pow10(n - 1); +} + +// Counts the number of fractional digits in the range [0, 18] according to the +// C++20 spec. If more than 18 fractional digits are required then returns 6 for +// microseconds precision. +template () / 10)> +struct count_fractional_digits { + static constexpr int value = + Num % Den == 0 ? N : count_fractional_digits::value; +}; + +// Base case that doesn't instantiate any more templates +// in order to avoid overflow. +template +struct count_fractional_digits { + static constexpr int value = (Num % Den == 0) ? N : 6; +}; + +// Format subseconds which are given as an integer type with an appropriate +// number of digits. +template +void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) { + constexpr auto num_fractional_digits = + count_fractional_digits::value; + + using subsecond_precision = std::chrono::duration< + typename std::common_type::type, + std::ratio<1, pow10(num_fractional_digits)>>; + + const auto fractional = d - detail::duration_cast(d); + const auto subseconds = + std::chrono::treat_as_floating_point< + typename subsecond_precision::rep>::value + ? fractional.count() + : detail::duration_cast(fractional).count(); + auto n = static_cast>(subseconds); + const int num_digits = count_digits(n); + + int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits); + if (precision < 0) { + FMT_ASSERT(!std::is_floating_point::value, ""); + if (std::ratio_less::value) { + *out++ = '.'; + out = detail::fill_n(out, leading_zeroes, '0'); + out = format_decimal(out, n, num_digits); + } + } else if (precision > 0) { + *out++ = '.'; + leading_zeroes = min_of(leading_zeroes, precision); + int remaining = precision - leading_zeroes; + out = detail::fill_n(out, leading_zeroes, '0'); + if (remaining < num_digits) { + int num_truncated_digits = num_digits - remaining; + n /= to_unsigned(pow10(to_unsigned(num_truncated_digits))); + if (n != 0) out = format_decimal(out, n, remaining); + return; + } + if (n != 0) { + out = format_decimal(out, n, num_digits); + remaining -= num_digits; + } + out = detail::fill_n(out, remaining, '0'); + } +} + +// Format subseconds which are given as a floating point type with an +// appropriate number of digits. We cannot pass the Duration here, as we +// explicitly need to pass the Rep value in the duration_formatter. +template +void write_floating_seconds(memory_buffer& buf, Duration duration, + int num_fractional_digits = -1) { + using rep = typename Duration::rep; + FMT_ASSERT(std::is_floating_point::value, ""); + + auto val = duration.count(); + + if (num_fractional_digits < 0) { + // For `std::round` with fallback to `round`: + // On some toolchains `std::round` is not available (e.g. GCC 6). + using namespace std; + num_fractional_digits = + count_fractional_digits::value; + if (num_fractional_digits < 6 && static_cast(round(val)) != val) + num_fractional_digits = 6; + } + + fmt::format_to(std::back_inserter(buf), FMT_STRING("{:.{}f}"), + std::fmod(val * static_cast(Duration::period::num) / + static_cast(Duration::period::den), + static_cast(60)), + num_fractional_digits); +} + +template +class tm_writer { + private: + static constexpr int days_per_week = 7; + + const std::locale& loc_; + bool is_classic_; + OutputIt out_; + const Duration* subsecs_; + const std::tm& tm_; + + auto tm_sec() const noexcept -> int { + FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, ""); + return tm_.tm_sec; + } + auto tm_min() const noexcept -> int { + FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, ""); + return tm_.tm_min; + } + auto tm_hour() const noexcept -> int { + FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, ""); + return tm_.tm_hour; + } + auto tm_mday() const noexcept -> int { + FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, ""); + return tm_.tm_mday; + } + auto tm_mon() const noexcept -> int { + FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, ""); + return tm_.tm_mon; + } + auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; } + auto tm_wday() const noexcept -> int { + FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, ""); + return tm_.tm_wday; + } + auto tm_yday() const noexcept -> int { + FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, ""); + return tm_.tm_yday; + } + + auto tm_hour12() const noexcept -> int { + auto h = tm_hour(); + auto z = h < 12 ? h : h - 12; + return z == 0 ? 12 : z; + } + + // POSIX and the C Standard are unclear or inconsistent about what %C and %y + // do if the year is negative or exceeds 9999. Use the convention that %C + // concatenated with %y yields the same output as %Y, and that %Y contains at + // least 4 characters, with more only if necessary. + auto split_year_lower(long long year) const noexcept -> int { + auto l = year % 100; + if (l < 0) l = -l; // l in [0, 99] + return static_cast(l); + } + + // Algorithm: https://en.wikipedia.org/wiki/ISO_week_date. + auto iso_year_weeks(long long curr_year) const noexcept -> int { + auto prev_year = curr_year - 1; + auto curr_p = + (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) % + days_per_week; + auto prev_p = + (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) % + days_per_week; + return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0); + } + auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int { + return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) / + days_per_week; + } + auto tm_iso_week_year() const noexcept -> long long { + auto year = tm_year(); + auto w = iso_week_num(tm_yday(), tm_wday()); + if (w < 1) return year - 1; + if (w > iso_year_weeks(year)) return year + 1; + return year; + } + auto tm_iso_week_of_year() const noexcept -> int { + auto year = tm_year(); + auto w = iso_week_num(tm_yday(), tm_wday()); + if (w < 1) return iso_year_weeks(year - 1); + if (w > iso_year_weeks(year)) return 1; + return w; + } + + void write1(int value) { + *out_++ = static_cast('0' + to_unsigned(value) % 10); + } + void write2(int value) { + const char* d = digits2(to_unsigned(value) % 100); + *out_++ = *d++; + *out_++ = *d; + } + void write2(int value, pad_type pad) { + unsigned int v = to_unsigned(value) % 100; + if (v >= 10) { + const char* d = digits2(v); + *out_++ = *d++; + *out_++ = *d; + } else { + out_ = detail::write_padding(out_, pad); + *out_++ = static_cast('0' + v); + } + } + + void write_year_extended(long long year, pad_type pad) { + // At least 4 characters. + int width = 4; + bool negative = year < 0; + if (negative) { + year = 0 - year; + --width; + } + uint32_or_64_or_128_t n = to_unsigned(year); + const int num_digits = count_digits(n); + if (negative && pad == pad_type::zero) *out_++ = '-'; + if (width > num_digits) + out_ = detail::write_padding(out_, pad, width - num_digits); + if (negative && pad != pad_type::zero) *out_++ = '-'; + out_ = format_decimal(out_, n, num_digits); + } + void write_year(long long year, pad_type pad) { + write_year_extended(year, pad); + } + + void write_utc_offset(long long offset, numeric_system ns) { + if (offset < 0) { + *out_++ = '-'; + offset = -offset; + } else { + *out_++ = '+'; + } + offset /= 60; + write2(static_cast(offset / 60)); + if (ns != numeric_system::standard) *out_++ = ':'; + write2(static_cast(offset % 60)); + } + + template ::value)> + void format_utc_offset(const T& tm, numeric_system ns) { + write_utc_offset(tm.tm_gmtoff, ns); + } + template ::value)> + void format_utc_offset(const T&, numeric_system ns) { + write_utc_offset(0, ns); + } + + template ::value)> + void format_tz_name(const T& tm) { + out_ = write_tm_str(out_, tm.tm_zone, loc_); + } + template ::value)> + void format_tz_name(const T&) { + out_ = std::copy_n(utc(), 3, out_); + } + + void format_localized(char format, char modifier = 0) { + out_ = write(out_, tm_, loc_, format, modifier); + } + + public: + tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm, + const Duration* subsecs = nullptr) + : loc_(loc), + is_classic_(loc_ == get_classic_locale()), + out_(out), + subsecs_(subsecs), + tm_(tm) {} + + auto out() const -> OutputIt { return out_; } + + FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) { + out_ = copy(begin, end, out_); + } + + void on_abbr_weekday() { + if (is_classic_) + out_ = write(out_, tm_wday_short_name(tm_wday())); + else + format_localized('a'); + } + void on_full_weekday() { + if (is_classic_) + out_ = write(out_, tm_wday_full_name(tm_wday())); + else + format_localized('A'); + } + void on_dec0_weekday(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday()); + format_localized('w', 'O'); + } + void on_dec1_weekday(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) { + auto wday = tm_wday(); + write1(wday == 0 ? days_per_week : wday); + } else { + format_localized('u', 'O'); + } + } + + void on_abbr_month() { + if (is_classic_) + out_ = write(out_, tm_mon_short_name(tm_mon())); + else + format_localized('b'); + } + void on_full_month() { + if (is_classic_) + out_ = write(out_, tm_mon_full_name(tm_mon())); + else + format_localized('B'); + } + + void on_datetime(numeric_system ns) { + if (is_classic_) { + on_abbr_weekday(); + *out_++ = ' '; + on_abbr_month(); + *out_++ = ' '; + on_day_of_month(numeric_system::standard, pad_type::space); + *out_++ = ' '; + on_iso_time(); + *out_++ = ' '; + on_year(numeric_system::standard, pad_type::space); + } else { + format_localized('c', ns == numeric_system::standard ? '\0' : 'E'); + } + } + void on_loc_date(numeric_system ns) { + if (is_classic_) + on_us_date(); + else + format_localized('x', ns == numeric_system::standard ? '\0' : 'E'); + } + void on_loc_time(numeric_system ns) { + if (is_classic_) + on_iso_time(); + else + format_localized('X', ns == numeric_system::standard ? '\0' : 'E'); + } + void on_us_date() { + char buf[8]; + write_digit2_separated(buf, to_unsigned(tm_mon() + 1), + to_unsigned(tm_mday()), + to_unsigned(split_year_lower(tm_year())), '/'); + out_ = copy(std::begin(buf), std::end(buf), out_); + } + void on_iso_date() { + auto year = tm_year(); + char buf[10]; + size_t offset = 0; + if (year >= 0 && year < 10000) { + write2digits(buf, static_cast(year / 100)); + } else { + offset = 4; + write_year_extended(year, pad_type::zero); + year = 0; + } + write_digit2_separated(buf + 2, static_cast(year % 100), + to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()), + '-'); + out_ = copy(std::begin(buf) + offset, std::end(buf), out_); + } + + void on_utc_offset(numeric_system ns) { format_utc_offset(tm_, ns); } + void on_tz_name() { format_tz_name(tm_); } + + void on_year(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write_year(tm_year(), pad); + format_localized('Y', 'E'); + } + void on_short_year(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) + return write2(split_year_lower(tm_year())); + format_localized('y', 'O'); + } + void on_offset_year() { + if (is_classic_) return write2(split_year_lower(tm_year())); + format_localized('y', 'E'); + } + + void on_century(numeric_system ns) { + if (is_classic_ || ns == numeric_system::standard) { + auto year = tm_year(); + auto upper = year / 100; + if (year >= -99 && year < 0) { + // Zero upper on negative year. + *out_++ = '-'; + *out_++ = '0'; + } else if (upper >= 0 && upper < 100) { + write2(static_cast(upper)); + } else { + out_ = write(out_, upper); + } + } else { + format_localized('C', 'E'); + } + } + + void on_dec_month(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_mon() + 1, pad); + format_localized('m', 'O'); + } + + void on_dec0_week_of_year(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week, + pad); + format_localized('U', 'O'); + } + void on_dec1_week_of_year(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) { + auto wday = tm_wday(); + write2((tm_yday() + days_per_week - + (wday == 0 ? (days_per_week - 1) : (wday - 1))) / + days_per_week, + pad); + } else { + format_localized('W', 'O'); + } + } + void on_iso_week_of_year(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_iso_week_of_year(), pad); + format_localized('V', 'O'); + } + + void on_iso_week_based_year() { + write_year(tm_iso_week_year(), pad_type::zero); + } + void on_iso_week_based_short_year() { + write2(split_year_lower(tm_iso_week_year())); + } + + void on_day_of_year(pad_type pad) { + auto yday = tm_yday() + 1; + auto digit1 = yday / 100; + if (digit1 != 0) + write1(digit1); + else + out_ = detail::write_padding(out_, pad); + write2(yday % 100, pad); + } + + void on_day_of_month(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_mday(), pad); + format_localized('d', 'O'); + } + + void on_24_hour(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_hour(), pad); + format_localized('H', 'O'); + } + void on_12_hour(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_hour12(), pad); + format_localized('I', 'O'); + } + void on_minute(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) + return write2(tm_min(), pad); + format_localized('M', 'O'); + } + + void on_second(numeric_system ns, pad_type pad) { + if (is_classic_ || ns == numeric_system::standard) { + write2(tm_sec(), pad); + if (subsecs_) { + if (std::is_floating_point::value) { + auto buf = memory_buffer(); + write_floating_seconds(buf, *subsecs_); + if (buf.size() > 1) { + // Remove the leading "0", write something like ".123". + out_ = copy(buf.begin() + 1, buf.end(), out_); + } + } else { + write_fractional_seconds(out_, *subsecs_); + } + } + } else { + // Currently no formatting of subseconds when a locale is set. + format_localized('S', 'O'); + } + } + + void on_12_hour_time() { + if (is_classic_) { + char buf[8]; + write_digit2_separated(buf, to_unsigned(tm_hour12()), + to_unsigned(tm_min()), to_unsigned(tm_sec()), ':'); + out_ = copy(std::begin(buf), std::end(buf), out_); + *out_++ = ' '; + on_am_pm(); + } else { + format_localized('r'); + } + } + void on_24_hour_time() { + write2(tm_hour()); + *out_++ = ':'; + write2(tm_min()); + } + void on_iso_time() { + on_24_hour_time(); + *out_++ = ':'; + on_second(numeric_system::standard, pad_type::zero); + } + + void on_am_pm() { + if (is_classic_) { + *out_++ = tm_hour() < 12 ? 'A' : 'P'; + *out_++ = 'M'; + } else { + format_localized('p'); + } + } + + // These apply to chrono durations but not tm. + void on_duration_value() {} + void on_duration_unit() {} +}; + +struct chrono_format_checker : null_chrono_spec_handler { + bool has_precision_integral = false; + + FMT_NORETURN inline void unsupported() { FMT_THROW(format_error("no date")); } + + template + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + FMT_CONSTEXPR void on_day_of_year(pad_type) {} + FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_second(numeric_system, pad_type) {} + FMT_CONSTEXPR void on_12_hour_time() {} + FMT_CONSTEXPR void on_24_hour_time() {} + FMT_CONSTEXPR void on_iso_time() {} + FMT_CONSTEXPR void on_am_pm() {} + FMT_CONSTEXPR void on_duration_value() const { + if (has_precision_integral) + FMT_THROW(format_error("precision not allowed for this argument type")); + } + FMT_CONSTEXPR void on_duration_unit() {} +}; + +template ::value&& has_isfinite::value)> +inline auto isfinite(T) -> bool { + return true; +} + +template ::value)> +inline auto mod(T x, int y) -> T { + return x % static_cast(y); +} +template ::value)> +inline auto mod(T x, int y) -> T { + return std::fmod(x, static_cast(y)); +} + +// If T is an integral type, maps T to its unsigned counterpart, otherwise +// leaves it unchanged (unlike std::make_unsigned). +template ::value> +struct make_unsigned_or_unchanged { + using type = T; +}; + +template struct make_unsigned_or_unchanged { + using type = typename std::make_unsigned::type; +}; + +template ::value)> +inline auto get_milliseconds(std::chrono::duration d) + -> std::chrono::duration { + // This may overflow and/or the result may not fit in the target type. +#if FMT_SAFE_DURATION_CAST + using common_seconds_type = + typename std::common_type::type; + auto d_as_common = detail::duration_cast(d); + auto d_as_whole_seconds = + detail::duration_cast(d_as_common); + // This conversion should be nonproblematic. + auto diff = d_as_common - d_as_whole_seconds; + auto ms = detail::duration_cast>(diff); + return ms; +#else + auto s = detail::duration_cast(d); + return detail::duration_cast(d - s); +#endif +} + +template ::value)> +auto format_duration_value(OutputIt out, Rep val, int) -> OutputIt { + return write(out, val); +} + +template ::value)> +auto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt { + auto specs = format_specs(); + specs.precision = precision; + specs.set_type(precision >= 0 ? presentation_type::fixed + : presentation_type::general); + return write(out, val, specs); +} + +template +auto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt { + return copy(unit.begin(), unit.end(), out); +} + +template +auto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt { + // This works when wchar_t is UTF-32 because units only contain characters + // that have the same representation in UTF-16 and UTF-32. + utf8_to_utf16 u(unit); + return copy(u.c_str(), u.c_str() + u.size(), out); +} + +template +auto format_duration_unit(OutputIt out) -> OutputIt { + if (const char* unit = get_units()) + return copy_unit(string_view(unit), out, Char()); + *out++ = '['; + out = write(out, Period::num); + if (const_check(Period::den != 1)) { + *out++ = '/'; + out = write(out, Period::den); + } + *out++ = ']'; + *out++ = 's'; + return out; +} + +class get_locale { + private: + union { + std::locale locale_; + }; + bool has_locale_ = false; + + public: + inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) { + if (localized) + ::new (&locale_) std::locale(loc.template get()); + } + inline ~get_locale() { + if (has_locale_) locale_.~locale(); + } + inline operator const std::locale&() const { + return has_locale_ ? locale_ : get_classic_locale(); + } +}; + +template +struct duration_formatter { + using iterator = basic_appender; + iterator out; + // rep is unsigned to avoid overflow. + using rep = + conditional_t::value && sizeof(Rep) < sizeof(int), + unsigned, typename make_unsigned_or_unchanged::type>; + rep val; + int precision; + locale_ref locale; + bool localized = false; + using seconds = std::chrono::duration; + seconds s; + using milliseconds = std::chrono::duration; + bool negative; + + using tm_writer_type = tm_writer; + + duration_formatter(iterator o, std::chrono::duration d, + locale_ref loc) + : out(o), val(static_cast(d.count())), locale(loc), negative(false) { + if (d.count() < 0) { + val = 0 - val; + negative = true; + } + + // this may overflow and/or the result may not fit in the + // target type. + // might need checked conversion (rep!=Rep) + s = detail::duration_cast(std::chrono::duration(val)); + } + + // returns true if nan or inf, writes to out. + auto handle_nan_inf() -> bool { + if (isfinite(val)) return false; + if (isnan(val)) { + write_nan(); + return true; + } + // must be +-inf + if (val > 0) + std::copy_n("inf", 3, out); + else + std::copy_n("-inf", 4, out); + return true; + } + + auto days() const -> Rep { return static_cast(s.count() / 86400); } + auto hour() const -> Rep { + return static_cast(mod((s.count() / 3600), 24)); + } + + auto hour12() const -> Rep { + Rep hour = static_cast(mod((s.count() / 3600), 12)); + return hour <= 0 ? 12 : hour; + } + + auto minute() const -> Rep { + return static_cast(mod((s.count() / 60), 60)); + } + auto second() const -> Rep { return static_cast(mod(s.count(), 60)); } + + auto time() const -> std::tm { + auto time = std::tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + time.tm_min = to_nonnegative_int(minute(), 60); + time.tm_sec = to_nonnegative_int(second(), 60); + return time; + } + + void write_sign() { + if (!negative) return; + *out++ = '-'; + negative = false; + } + + void write(Rep value, int width, pad_type pad = pad_type::zero) { + write_sign(); + if (isnan(value)) return write_nan(); + uint32_or_64_or_128_t n = + to_unsigned(to_nonnegative_int(value, max_value())); + int num_digits = detail::count_digits(n); + if (width > num_digits) { + out = detail::write_padding(out, pad, width - num_digits); + } + out = format_decimal(out, n, num_digits); + } + + void write_nan() { std::copy_n("nan", 3, out); } + + template + void format_tm(const tm& time, Callback cb, Args... args) { + if (isnan(val)) return write_nan(); + get_locale loc(localized, locale); + auto w = tm_writer_type(loc, out, time); + (w.*cb)(args...); + out = w.out(); + } + + void on_text(const Char* begin, const Char* end) { + copy(begin, end, out); + } + + // These are not implemented because durations don't have date information. + void on_abbr_weekday() {} + void on_full_weekday() {} + void on_dec0_weekday(numeric_system) {} + void on_dec1_weekday(numeric_system) {} + void on_abbr_month() {} + void on_full_month() {} + void on_datetime(numeric_system) {} + void on_loc_date(numeric_system) {} + void on_loc_time(numeric_system) {} + void on_us_date() {} + void on_iso_date() {} + void on_utc_offset(numeric_system) {} + void on_tz_name() {} + void on_year(numeric_system, pad_type) {} + void on_short_year(numeric_system) {} + void on_offset_year() {} + void on_century(numeric_system) {} + void on_iso_week_based_year() {} + void on_iso_week_based_short_year() {} + void on_dec_month(numeric_system, pad_type) {} + void on_dec0_week_of_year(numeric_system, pad_type) {} + void on_dec1_week_of_year(numeric_system, pad_type) {} + void on_iso_week_of_year(numeric_system, pad_type) {} + void on_day_of_month(numeric_system, pad_type) {} + + void on_day_of_year(pad_type) { + if (handle_nan_inf()) return; + write(days(), 0); + } + + void on_24_hour(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour(), 2, pad); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour(), 24); + format_tm(time, &tm_writer_type::on_24_hour, ns, pad); + } + + void on_12_hour(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(hour12(), 2, pad); + auto time = tm(); + time.tm_hour = to_nonnegative_int(hour12(), 12); + format_tm(time, &tm_writer_type::on_12_hour, ns, pad); + } + + void on_minute(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) return write(minute(), 2, pad); + auto time = tm(); + time.tm_min = to_nonnegative_int(minute(), 60); + format_tm(time, &tm_writer_type::on_minute, ns, pad); + } + + void on_second(numeric_system ns, pad_type pad) { + if (handle_nan_inf()) return; + + if (ns == numeric_system::standard) { + if (std::is_floating_point::value) { + auto buf = memory_buffer(); + write_floating_seconds(buf, std::chrono::duration(val), + precision); + if (negative) *out++ = '-'; + if (buf.size() < 2 || buf[1] == '.') + out = detail::write_padding(out, pad); + out = copy(buf.begin(), buf.end(), out); + } else { + write(second(), 2, pad); + write_fractional_seconds( + out, std::chrono::duration(val), precision); + } + return; + } + auto time = tm(); + time.tm_sec = to_nonnegative_int(second(), 60); + format_tm(time, &tm_writer_type::on_second, ns, pad); + } + + void on_12_hour_time() { + if (handle_nan_inf()) return; + format_tm(time(), &tm_writer_type::on_12_hour_time); + } + + void on_24_hour_time() { + if (handle_nan_inf()) { + *out++ = ':'; + handle_nan_inf(); + return; + } + + write(hour(), 2); + *out++ = ':'; + write(minute(), 2); + } + + void on_iso_time() { + on_24_hour_time(); + *out++ = ':'; + if (handle_nan_inf()) return; + on_second(numeric_system::standard, pad_type::zero); + } + + void on_am_pm() { + if (handle_nan_inf()) return; + format_tm(time(), &tm_writer_type::on_am_pm); + } + + void on_duration_value() { + if (handle_nan_inf()) return; + write_sign(); + out = format_duration_value(out, val, precision); + } + + void on_duration_unit() { out = format_duration_unit(out); } +}; + +} // namespace detail + +#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907 +using weekday = std::chrono::weekday; +using day = std::chrono::day; +using month = std::chrono::month; +using year = std::chrono::year; +using year_month_day = std::chrono::year_month_day; +#else +// A fallback version of weekday. +class weekday { + private: + unsigned char value_; + + public: + weekday() = default; + constexpr explicit weekday(unsigned wd) noexcept + : value_(static_cast(wd != 7 ? wd : 0)) {} + constexpr auto c_encoding() const noexcept -> unsigned { return value_; } +}; + +class day { + private: + unsigned char value_; + + public: + day() = default; + constexpr explicit day(unsigned d) noexcept + : value_(static_cast(d)) {} + constexpr explicit operator unsigned() const noexcept { return value_; } +}; + +class month { + private: + unsigned char value_; + + public: + month() = default; + constexpr explicit month(unsigned m) noexcept + : value_(static_cast(m)) {} + constexpr explicit operator unsigned() const noexcept { return value_; } +}; + +class year { + private: + int value_; + + public: + year() = default; + constexpr explicit year(int y) noexcept : value_(y) {} + constexpr explicit operator int() const noexcept { return value_; } +}; + +class year_month_day { + private: + fmt::year year_; + fmt::month month_; + fmt::day day_; + + public: + year_month_day() = default; + constexpr year_month_day(const year& y, const month& m, const day& d) noexcept + : year_(y), month_(m), day_(d) {} + constexpr auto year() const noexcept -> fmt::year { return year_; } + constexpr auto month() const noexcept -> fmt::month { return month_; } + constexpr auto day() const noexcept -> fmt::day { return day_; } +}; +#endif // __cpp_lib_chrono >= 201907 + +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it != end && *it == 'L') { + ++it; + this->set_localized(); + } + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_wday = static_cast(wd.c_encoding()); + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(this->localized(), ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_abbr_weekday(); + return w.out(); + } +}; + +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(day d, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_mday = static_cast(static_cast(d)); + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(false, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_day_of_month(detail::numeric_system::standard, detail::pad_type::zero); + return w.out(); + } +}; + +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it != end && *it == 'L') { + ++it; + this->set_localized(); + } + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(month m, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_mon = static_cast(static_cast(m)) - 1; + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(this->localized(), ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_abbr_month(); + return w.out(); + } +}; + +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(year y, FormatContext& ctx) const -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_year = static_cast(y) - 1900; + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(false, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_year(detail::numeric_system::standard, detail::pad_type::zero); + return w.out(); + } +}; + +template +struct formatter : private formatter { + private: + bool use_tm_formatter_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + use_tm_formatter_ = it != end && *it != '}'; + return use_tm_formatter_ ? formatter::parse(ctx) : it; + } + + template + auto format(year_month_day val, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto time = std::tm(); + time.tm_year = static_cast(val.year()) - 1900; + time.tm_mon = static_cast(static_cast(val.month())) - 1; + time.tm_mday = static_cast(static_cast(val.day())); + if (use_tm_formatter_) return formatter::format(time, ctx); + detail::get_locale loc(true, ctx.locale()); + auto w = detail::tm_writer(loc, ctx.out(), time); + w.on_iso_date(); + return w.out(); + } +}; + +template +struct formatter, Char> { + private: + format_specs specs_; + detail::arg_ref width_ref_; + detail::arg_ref precision_ref_; + basic_string_view fmt_; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end || *it == '}') return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + Char c = *it; + if ((c >= '0' && c <= '9') || c == '{') { + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + if (it == end) return it; + } + + auto checker = detail::chrono_format_checker(); + if (*it == '.') { + checker.has_precision_integral = !std::is_floating_point::value; + it = detail::parse_precision(it, end, specs_, precision_ref_, ctx); + } + if (it != end && *it == 'L') { + specs_.set_localized(); + ++it; + } + end = detail::parse_chrono_format(it, end, checker); + fmt_ = {it, detail::to_unsigned(end - it)}; + return end; + } + + template + auto format(std::chrono::duration d, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto specs = specs_; + auto precision = specs.precision; + specs.precision = -1; + auto begin = fmt_.begin(), end = fmt_.end(); + // As a possible future optimization, we could avoid extra copying if width + // is not specified. + auto buf = basic_memory_buffer(); + auto out = basic_appender(buf); + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), precision, + precision_ref_, ctx); + if (begin == end || *begin == '}') { + out = detail::format_duration_value(out, d.count(), precision); + detail::format_duration_unit(out); + } else { + auto f = + detail::duration_formatter(out, d, ctx.locale()); + f.precision = precision; + f.localized = specs_.localized(); + detail::parse_chrono_format(begin, end, f); + } + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); + } +}; + +template struct formatter { + private: + format_specs specs_; + detail::arg_ref width_ref_; + basic_string_view fmt_ = + detail::string_literal(); + + protected: + auto localized() const -> bool { return specs_.localized(); } + FMT_CONSTEXPR void set_localized() { specs_.set_localized(); } + + FMT_CONSTEXPR auto do_parse(parse_context& ctx, bool has_timezone) + -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end || *it == '}') return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + Char c = *it; + if ((c >= '0' && c <= '9') || c == '{') { + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + if (it == end) return it; + } + + if (*it == 'L') { + specs_.set_localized(); + ++it; + } + + end = detail::parse_chrono_format(it, end, + detail::tm_format_checker(has_timezone)); + // Replace the default format string only if the new spec is not empty. + if (end != it) fmt_ = {it, detail::to_unsigned(end - it)}; + return end; + } + + template + auto do_format(const std::tm& tm, FormatContext& ctx, + const Duration* subsecs) const -> decltype(ctx.out()) { + auto specs = specs_; + auto buf = basic_memory_buffer(); + auto out = basic_appender(buf); + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); + + auto loc_ref = specs.localized() ? ctx.locale() : locale_ref(); + detail::get_locale loc(static_cast(loc_ref), loc_ref); + auto w = detail::tm_writer, Char, Duration>( + loc, out, tm, subsecs); + detail::parse_chrono_format(fmt_.begin(), fmt_.end(), w); + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); + } + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return do_parse(ctx, detail::has_tm_gmtoff::value); + } + + template + auto format(const std::tm& tm, FormatContext& ctx) const + -> decltype(ctx.out()) { + return do_format(tm, ctx, nullptr); + } +}; + +// DEPRECATED! Reversed order of template parameters. +template +struct formatter, Char> : private formatter { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return this->do_parse(ctx, true); + } + + template + auto format(sys_time val, FormatContext& ctx) const + -> decltype(ctx.out()) { + std::tm tm = gmtime(val); + using period = typename Duration::period; + if (detail::const_check( + period::num == 1 && period::den == 1 && + !std::is_floating_point::value)) { + detail::set_tm_zone(tm, detail::utc()); + return formatter::format(tm, ctx); + } + Duration epoch = val.time_since_epoch(); + Duration subsecs = detail::duration_cast( + epoch - detail::duration_cast(epoch)); + if (subsecs.count() < 0) { + auto second = detail::duration_cast(std::chrono::seconds(1)); + if (tm.tm_sec != 0) { + --tm.tm_sec; + } else { + tm = gmtime(val - second); + detail::set_tm_zone(tm, detail::utc()); + } + subsecs += second; + } + return formatter::do_format(tm, ctx, &subsecs); + } +}; + +template +struct formatter, Char> + : formatter, Char> { + template + auto format(utc_time val, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter, Char>::format( + detail::utc_clock::to_sys(val), ctx); + } +}; + +template +struct formatter, Char> + : private formatter { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return this->do_parse(ctx, false); + } + + template + auto format(local_time val, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto time_since_epoch = val.time_since_epoch(); + auto seconds_since_epoch = + detail::duration_cast(time_since_epoch); + // Use gmtime to prevent time zone conversion since local_time has an + // unspecified time zone. + std::tm t = gmtime(seconds_since_epoch.count()); + using period = typename Duration::period; + if (period::num == 1 && period::den == 1 && + !std::is_floating_point::value) { + return formatter::format(t, ctx); + } + auto subsecs = + detail::duration_cast(time_since_epoch - seconds_since_epoch); + return formatter::do_format(t, ctx, &subsecs); + } +}; + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_CHRONO_H_ diff --git a/vendor/btop/include/fmt/color.h b/vendor/btop/include/fmt/color.h new file mode 100644 index 000000000..b69c14886 --- /dev/null +++ b/vendor/btop/include/fmt/color.h @@ -0,0 +1,637 @@ +// Formatting library for C++ - color support +// +// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COLOR_H_ +#define FMT_COLOR_H_ + +#include "format.h" + +FMT_BEGIN_NAMESPACE +FMT_BEGIN_EXPORT + +enum class color : uint32_t { + alice_blue = 0xF0F8FF, // rgb(240,248,255) + antique_white = 0xFAEBD7, // rgb(250,235,215) + aqua = 0x00FFFF, // rgb(0,255,255) + aquamarine = 0x7FFFD4, // rgb(127,255,212) + azure = 0xF0FFFF, // rgb(240,255,255) + beige = 0xF5F5DC, // rgb(245,245,220) + bisque = 0xFFE4C4, // rgb(255,228,196) + black = 0x000000, // rgb(0,0,0) + blanched_almond = 0xFFEBCD, // rgb(255,235,205) + blue = 0x0000FF, // rgb(0,0,255) + blue_violet = 0x8A2BE2, // rgb(138,43,226) + brown = 0xA52A2A, // rgb(165,42,42) + burly_wood = 0xDEB887, // rgb(222,184,135) + cadet_blue = 0x5F9EA0, // rgb(95,158,160) + chartreuse = 0x7FFF00, // rgb(127,255,0) + chocolate = 0xD2691E, // rgb(210,105,30) + coral = 0xFF7F50, // rgb(255,127,80) + cornflower_blue = 0x6495ED, // rgb(100,149,237) + cornsilk = 0xFFF8DC, // rgb(255,248,220) + crimson = 0xDC143C, // rgb(220,20,60) + cyan = 0x00FFFF, // rgb(0,255,255) + dark_blue = 0x00008B, // rgb(0,0,139) + dark_cyan = 0x008B8B, // rgb(0,139,139) + dark_golden_rod = 0xB8860B, // rgb(184,134,11) + dark_gray = 0xA9A9A9, // rgb(169,169,169) + dark_green = 0x006400, // rgb(0,100,0) + dark_khaki = 0xBDB76B, // rgb(189,183,107) + dark_magenta = 0x8B008B, // rgb(139,0,139) + dark_olive_green = 0x556B2F, // rgb(85,107,47) + dark_orange = 0xFF8C00, // rgb(255,140,0) + dark_orchid = 0x9932CC, // rgb(153,50,204) + dark_red = 0x8B0000, // rgb(139,0,0) + dark_salmon = 0xE9967A, // rgb(233,150,122) + dark_sea_green = 0x8FBC8F, // rgb(143,188,143) + dark_slate_blue = 0x483D8B, // rgb(72,61,139) + dark_slate_gray = 0x2F4F4F, // rgb(47,79,79) + dark_turquoise = 0x00CED1, // rgb(0,206,209) + dark_violet = 0x9400D3, // rgb(148,0,211) + deep_pink = 0xFF1493, // rgb(255,20,147) + deep_sky_blue = 0x00BFFF, // rgb(0,191,255) + dim_gray = 0x696969, // rgb(105,105,105) + dodger_blue = 0x1E90FF, // rgb(30,144,255) + fire_brick = 0xB22222, // rgb(178,34,34) + floral_white = 0xFFFAF0, // rgb(255,250,240) + forest_green = 0x228B22, // rgb(34,139,34) + fuchsia = 0xFF00FF, // rgb(255,0,255) + gainsboro = 0xDCDCDC, // rgb(220,220,220) + ghost_white = 0xF8F8FF, // rgb(248,248,255) + gold = 0xFFD700, // rgb(255,215,0) + golden_rod = 0xDAA520, // rgb(218,165,32) + gray = 0x808080, // rgb(128,128,128) + green = 0x008000, // rgb(0,128,0) + green_yellow = 0xADFF2F, // rgb(173,255,47) + honey_dew = 0xF0FFF0, // rgb(240,255,240) + hot_pink = 0xFF69B4, // rgb(255,105,180) + indian_red = 0xCD5C5C, // rgb(205,92,92) + indigo = 0x4B0082, // rgb(75,0,130) + ivory = 0xFFFFF0, // rgb(255,255,240) + khaki = 0xF0E68C, // rgb(240,230,140) + lavender = 0xE6E6FA, // rgb(230,230,250) + lavender_blush = 0xFFF0F5, // rgb(255,240,245) + lawn_green = 0x7CFC00, // rgb(124,252,0) + lemon_chiffon = 0xFFFACD, // rgb(255,250,205) + light_blue = 0xADD8E6, // rgb(173,216,230) + light_coral = 0xF08080, // rgb(240,128,128) + light_cyan = 0xE0FFFF, // rgb(224,255,255) + light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210) + light_gray = 0xD3D3D3, // rgb(211,211,211) + light_green = 0x90EE90, // rgb(144,238,144) + light_pink = 0xFFB6C1, // rgb(255,182,193) + light_salmon = 0xFFA07A, // rgb(255,160,122) + light_sea_green = 0x20B2AA, // rgb(32,178,170) + light_sky_blue = 0x87CEFA, // rgb(135,206,250) + light_slate_gray = 0x778899, // rgb(119,136,153) + light_steel_blue = 0xB0C4DE, // rgb(176,196,222) + light_yellow = 0xFFFFE0, // rgb(255,255,224) + lime = 0x00FF00, // rgb(0,255,0) + lime_green = 0x32CD32, // rgb(50,205,50) + linen = 0xFAF0E6, // rgb(250,240,230) + magenta = 0xFF00FF, // rgb(255,0,255) + maroon = 0x800000, // rgb(128,0,0) + medium_aquamarine = 0x66CDAA, // rgb(102,205,170) + medium_blue = 0x0000CD, // rgb(0,0,205) + medium_orchid = 0xBA55D3, // rgb(186,85,211) + medium_purple = 0x9370DB, // rgb(147,112,219) + medium_sea_green = 0x3CB371, // rgb(60,179,113) + medium_slate_blue = 0x7B68EE, // rgb(123,104,238) + medium_spring_green = 0x00FA9A, // rgb(0,250,154) + medium_turquoise = 0x48D1CC, // rgb(72,209,204) + medium_violet_red = 0xC71585, // rgb(199,21,133) + midnight_blue = 0x191970, // rgb(25,25,112) + mint_cream = 0xF5FFFA, // rgb(245,255,250) + misty_rose = 0xFFE4E1, // rgb(255,228,225) + moccasin = 0xFFE4B5, // rgb(255,228,181) + navajo_white = 0xFFDEAD, // rgb(255,222,173) + navy = 0x000080, // rgb(0,0,128) + old_lace = 0xFDF5E6, // rgb(253,245,230) + olive = 0x808000, // rgb(128,128,0) + olive_drab = 0x6B8E23, // rgb(107,142,35) + orange = 0xFFA500, // rgb(255,165,0) + orange_red = 0xFF4500, // rgb(255,69,0) + orchid = 0xDA70D6, // rgb(218,112,214) + pale_golden_rod = 0xEEE8AA, // rgb(238,232,170) + pale_green = 0x98FB98, // rgb(152,251,152) + pale_turquoise = 0xAFEEEE, // rgb(175,238,238) + pale_violet_red = 0xDB7093, // rgb(219,112,147) + papaya_whip = 0xFFEFD5, // rgb(255,239,213) + peach_puff = 0xFFDAB9, // rgb(255,218,185) + peru = 0xCD853F, // rgb(205,133,63) + pink = 0xFFC0CB, // rgb(255,192,203) + plum = 0xDDA0DD, // rgb(221,160,221) + powder_blue = 0xB0E0E6, // rgb(176,224,230) + purple = 0x800080, // rgb(128,0,128) + rebecca_purple = 0x663399, // rgb(102,51,153) + red = 0xFF0000, // rgb(255,0,0) + rosy_brown = 0xBC8F8F, // rgb(188,143,143) + royal_blue = 0x4169E1, // rgb(65,105,225) + saddle_brown = 0x8B4513, // rgb(139,69,19) + salmon = 0xFA8072, // rgb(250,128,114) + sandy_brown = 0xF4A460, // rgb(244,164,96) + sea_green = 0x2E8B57, // rgb(46,139,87) + sea_shell = 0xFFF5EE, // rgb(255,245,238) + sienna = 0xA0522D, // rgb(160,82,45) + silver = 0xC0C0C0, // rgb(192,192,192) + sky_blue = 0x87CEEB, // rgb(135,206,235) + slate_blue = 0x6A5ACD, // rgb(106,90,205) + slate_gray = 0x708090, // rgb(112,128,144) + snow = 0xFFFAFA, // rgb(255,250,250) + spring_green = 0x00FF7F, // rgb(0,255,127) + steel_blue = 0x4682B4, // rgb(70,130,180) + tan = 0xD2B48C, // rgb(210,180,140) + teal = 0x008080, // rgb(0,128,128) + thistle = 0xD8BFD8, // rgb(216,191,216) + tomato = 0xFF6347, // rgb(255,99,71) + turquoise = 0x40E0D0, // rgb(64,224,208) + violet = 0xEE82EE, // rgb(238,130,238) + wheat = 0xF5DEB3, // rgb(245,222,179) + white = 0xFFFFFF, // rgb(255,255,255) + white_smoke = 0xF5F5F5, // rgb(245,245,245) + yellow = 0xFFFF00, // rgb(255,255,0) + yellow_green = 0x9ACD32 // rgb(154,205,50) +}; // enum class color + +enum class terminal_color : uint8_t { + black = 30, + red, + green, + yellow, + blue, + magenta, + cyan, + white, + bright_black = 90, + bright_red, + bright_green, + bright_yellow, + bright_blue, + bright_magenta, + bright_cyan, + bright_white +}; + +enum class emphasis : uint8_t { + bold = 1, + faint = 1 << 1, + italic = 1 << 2, + underline = 1 << 3, + blink = 1 << 4, + reverse = 1 << 5, + conceal = 1 << 6, + strikethrough = 1 << 7, +}; + +// rgb is a struct for red, green and blue colors. +// Using the name "rgb" makes some editors show the color in a tooltip. +struct rgb { + constexpr rgb() : r(0), g(0), b(0) {} + constexpr rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {} + constexpr rgb(uint32_t hex) + : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {} + constexpr rgb(color hex) + : r((uint32_t(hex) >> 16) & 0xFF), + g((uint32_t(hex) >> 8) & 0xFF), + b(uint32_t(hex) & 0xFF) {} + uint8_t r; + uint8_t g; + uint8_t b; +}; + +namespace detail { + +// A bit-packed variant of an RGB color, a terminal color, or unset color. +// see text_style for the bit-packing scheme. +struct color_type { + constexpr color_type() noexcept = default; + constexpr color_type(color rgb_color) noexcept + : value_(static_cast(rgb_color) | (1 << 24)) {} + constexpr color_type(rgb rgb_color) noexcept + : color_type(static_cast( + (static_cast(rgb_color.r) << 16) | + (static_cast(rgb_color.g) << 8) | rgb_color.b)) {} + constexpr color_type(terminal_color term_color) noexcept + : value_(static_cast(term_color) | (3 << 24)) {} + + constexpr auto is_terminal_color() const noexcept -> bool { + return (value_ & (1 << 25)) != 0; + } + + constexpr auto value() const noexcept -> uint32_t { + return value_ & 0xFFFFFF; + } + + constexpr color_type(uint32_t value) noexcept : value_(value) {} + + uint32_t value_ = 0; +}; +} // namespace detail + +/// A text style consisting of foreground and background colors and emphasis. +class text_style { + // The information is packed as follows: + // ┌──┐ + // │ 0│─┐ + // │..│ ├── foreground color value + // │23│─┘ + // ├──┤ + // │24│─┬── discriminator for the above value. 00 if unset, 01 if it's + // │25│─┘ an RGB color, or 11 if it's a terminal color (10 is unused) + // ├──┤ + // │26│──── overflow bit, always zero (see below) + // ├──┤ + // │27│─┐ + // │..│ │ + // │50│ │ + // ├──┤ │ + // │51│ ├── background color (same format as the foreground color) + // │52│ │ + // ├──┤ │ + // │53│─┘ + // ├──┤ + // │54│─┐ + // │..│ ├── emphases + // │61│─┘ + // ├──┤ + // │62│─┬── unused + // │63│─┘ + // └──┘ + // The overflow bits are there to make operator|= efficient. + // When ORing, we must throw if, for either the foreground or background, + // one style specifies a terminal color and the other specifies any color + // (terminal or RGB); in other words, if one discriminator is 11 and the + // other is 11 or 01. + // + // We do that check by adding the styles. Consider what adding does to each + // possible pair of discriminators: + // 00 + 00 = 000 + // 01 + 00 = 001 + // 11 + 00 = 011 + // 01 + 01 = 010 + // 11 + 01 = 100 (!!) + // 11 + 11 = 110 (!!) + // In the last two cases, the ones we want to catch, the third bit——the + // overflow bit——is set. Bingo. + // + // We must take into account the possible carry bit from the bits + // before the discriminator. The only potentially problematic case is + // 11 + 00 = 011 (a carry bit would make it 100, not good!), but a carry + // bit is impossible in that case, because 00 (unset color) means the + // 24 bits that precede the discriminator are all zero. + // + // This test can be applied to both colors simultaneously. + + public: + FMT_CONSTEXPR text_style(emphasis em = emphasis()) noexcept + : style_(static_cast(em) << 54) {} + + FMT_CONSTEXPR auto operator|=(text_style rhs) -> text_style& { + if (((style_ + rhs.style_) & ((1ULL << 26) | (1ULL << 53))) != 0) + report_error("can't OR a terminal color"); + style_ |= rhs.style_; + return *this; + } + + friend FMT_CONSTEXPR auto operator|(text_style lhs, text_style rhs) + -> text_style { + return lhs |= rhs; + } + + FMT_CONSTEXPR auto operator==(text_style rhs) const noexcept -> bool { + return style_ == rhs.style_; + } + + FMT_CONSTEXPR auto operator!=(text_style rhs) const noexcept -> bool { + return !(*this == rhs); + } + + FMT_CONSTEXPR auto has_foreground() const noexcept -> bool { + return (style_ & (1 << 24)) != 0; + } + FMT_CONSTEXPR auto has_background() const noexcept -> bool { + return (style_ & (1ULL << 51)) != 0; + } + FMT_CONSTEXPR auto has_emphasis() const noexcept -> bool { + return (style_ >> 54) != 0; + } + FMT_CONSTEXPR auto get_foreground() const noexcept -> detail::color_type { + FMT_ASSERT(has_foreground(), "no foreground specified for this style"); + return style_ & 0x3FFFFFF; + } + FMT_CONSTEXPR auto get_background() const noexcept -> detail::color_type { + FMT_ASSERT(has_background(), "no background specified for this style"); + return (style_ >> 27) & 0x3FFFFFF; + } + FMT_CONSTEXPR auto get_emphasis() const noexcept -> emphasis { + FMT_ASSERT(has_emphasis(), "no emphasis specified for this style"); + return static_cast(style_ >> 54); + } + + private: + FMT_CONSTEXPR text_style(uint64_t style) noexcept : style_(style) {} + + friend FMT_CONSTEXPR auto fg(detail::color_type foreground) noexcept + -> text_style; + + friend FMT_CONSTEXPR auto bg(detail::color_type background) noexcept + -> text_style; + + uint64_t style_ = 0; +}; + +/// Creates a text style from the foreground (text) color. +FMT_CONSTEXPR inline auto fg(detail::color_type foreground) noexcept + -> text_style { + return foreground.value_; +} + +/// Creates a text style from the background color. +FMT_CONSTEXPR inline auto bg(detail::color_type background) noexcept + -> text_style { + return static_cast(background.value_) << 27; +} + +FMT_CONSTEXPR inline auto operator|(emphasis lhs, emphasis rhs) noexcept + -> text_style { + return text_style(lhs) | rhs; +} + +namespace detail { + +template struct ansi_color_escape { + FMT_CONSTEXPR ansi_color_escape(color_type text_color, + const char* esc) noexcept { + // If we have a terminal color, we need to output another escape code + // sequence. + if (text_color.is_terminal_color()) { + bool is_background = esc == string_view("\x1b[48;2;"); + uint32_t value = text_color.value(); + // Background ASCII codes are the same as the foreground ones but with + // 10 more. + if (is_background) value += 10u; + + buffer[size++] = static_cast('\x1b'); + buffer[size++] = static_cast('['); + + if (value >= 100u) { + buffer[size++] = static_cast('1'); + value %= 100u; + } + buffer[size++] = static_cast('0' + value / 10u); + buffer[size++] = static_cast('0' + value % 10u); + + buffer[size++] = static_cast('m'); + return; + } + + for (int i = 0; i < 7; i++) { + buffer[i] = static_cast(esc[i]); + } + rgb color(text_color.value()); + to_esc(color.r, buffer + 7, ';'); + to_esc(color.g, buffer + 11, ';'); + to_esc(color.b, buffer + 15, 'm'); + size = 19; + } + FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept { + uint8_t em_codes[num_emphases] = {}; + if (has_emphasis(em, emphasis::bold)) em_codes[0] = 1; + if (has_emphasis(em, emphasis::faint)) em_codes[1] = 2; + if (has_emphasis(em, emphasis::italic)) em_codes[2] = 3; + if (has_emphasis(em, emphasis::underline)) em_codes[3] = 4; + if (has_emphasis(em, emphasis::blink)) em_codes[4] = 5; + if (has_emphasis(em, emphasis::reverse)) em_codes[5] = 7; + if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8; + if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9; + + buffer[size++] = static_cast('\x1b'); + buffer[size++] = static_cast('['); + + for (size_t i = 0; i < num_emphases; ++i) { + if (!em_codes[i]) continue; + buffer[size++] = static_cast('0' + em_codes[i]); + buffer[size++] = static_cast(';'); + } + + buffer[size - 1] = static_cast('m'); + } + FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; } + + FMT_CONSTEXPR auto begin() const noexcept -> const Char* { return buffer; } + FMT_CONSTEXPR auto end() const noexcept -> const Char* { + return buffer + size; + } + + private: + static constexpr size_t num_emphases = 8; + Char buffer[7u + 4u * num_emphases]; + size_t size = 0; + + static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out, + char delimiter) noexcept { + out[0] = static_cast('0' + c / 100); + out[1] = static_cast('0' + c / 10 % 10); + out[2] = static_cast('0' + c % 10); + out[3] = static_cast(delimiter); + } + static FMT_CONSTEXPR auto has_emphasis(emphasis em, emphasis mask) noexcept + -> bool { + return static_cast(em) & static_cast(mask); + } +}; + +template +FMT_CONSTEXPR auto make_foreground_color(color_type foreground) noexcept + -> ansi_color_escape { + return ansi_color_escape(foreground, "\x1b[38;2;"); +} + +template +FMT_CONSTEXPR auto make_background_color(color_type background) noexcept + -> ansi_color_escape { + return ansi_color_escape(background, "\x1b[48;2;"); +} + +template +FMT_CONSTEXPR auto make_emphasis(emphasis em) noexcept + -> ansi_color_escape { + return ansi_color_escape(em); +} + +template inline void reset_color(buffer& buffer) { + auto reset_color = string_view("\x1b[0m"); + buffer.append(reset_color.begin(), reset_color.end()); +} + +template struct styled_arg : view { + const T& value; + text_style style; + styled_arg(const T& v, text_style s) : value(v), style(s) {} +}; + +template +void vformat_to(buffer& buf, text_style ts, basic_string_view fmt, + basic_format_args> args) { + if (ts.has_emphasis()) { + auto emphasis = make_emphasis(ts.get_emphasis()); + buf.append(emphasis.begin(), emphasis.end()); + } + if (ts.has_foreground()) { + auto foreground = make_foreground_color(ts.get_foreground()); + buf.append(foreground.begin(), foreground.end()); + } + if (ts.has_background()) { + auto background = make_background_color(ts.get_background()); + buf.append(background.begin(), background.end()); + } + vformat_to(buf, fmt, args); + if (ts != text_style()) reset_color(buf); +} +} // namespace detail + +inline void vprint(FILE* f, text_style ts, string_view fmt, format_args args) { + auto buf = memory_buffer(); + detail::vformat_to(buf, ts, fmt, args); + print(f, FMT_STRING("{}"), string_view(buf.begin(), buf.size())); +} + +/** + * Formats a string and prints it to the specified file stream using ANSI + * escape sequences to specify text formatting. + * + * **Example**: + * + * fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + * "Elapsed time: {0:.2f} seconds", 1.23); + */ +template +void print(FILE* f, text_style ts, format_string fmt, T&&... args) { + vprint(f, ts, fmt.str, vargs{{args...}}); +} + +/** + * Formats a string and prints it to stdout using ANSI escape sequences to + * specify text formatting. + * + * **Example**: + * + * fmt::print(fmt::emphasis::bold | fg(fmt::color::red), + * "Elapsed time: {0:.2f} seconds", 1.23); + */ +template +void print(text_style ts, format_string fmt, T&&... args) { + return print(stdout, ts, fmt, std::forward(args)...); +} + +inline auto vformat(text_style ts, string_view fmt, format_args args) + -> std::string { + auto buf = memory_buffer(); + detail::vformat_to(buf, ts, fmt, args); + return fmt::to_string(buf); +} + +/** + * Formats arguments and returns the result as a string using ANSI escape + * sequences to specify text formatting. + * + * **Example**: + * + * ``` + * #include + * std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), + * "The answer is {}", 42); + * ``` + */ +template +inline auto format(text_style ts, format_string fmt, T&&... args) + -> std::string { + return fmt::vformat(ts, fmt.str, vargs{{args...}}); +} + +/// Formats a string with the given text_style and writes the output to `out`. +template ::value)> +auto vformat_to(OutputIt out, text_style ts, string_view fmt, format_args args) + -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, ts, fmt, args); + return detail::get_iterator(buf, out); +} + +/** + * Formats arguments with the given text style, writes the result to the output + * iterator `out` and returns the iterator past the end of the output range. + * + * **Example**: + * + * std::vector out; + * fmt::format_to(std::back_inserter(out), + * fmt::emphasis::bold | fg(fmt::color::red), "{}", 42); + */ +template ::value)> +inline auto format_to(OutputIt out, text_style ts, format_string fmt, + T&&... args) -> OutputIt { + return vformat_to(out, ts, fmt.str, vargs{{args...}}); +} + +template +struct formatter, Char> : formatter { + template + auto format(const detail::styled_arg& arg, FormatContext& ctx) const + -> decltype(ctx.out()) { + const auto& ts = arg.style; + auto out = ctx.out(); + + bool has_style = false; + if (ts.has_emphasis()) { + has_style = true; + auto emphasis = detail::make_emphasis(ts.get_emphasis()); + out = detail::copy(emphasis.begin(), emphasis.end(), out); + } + if (ts.has_foreground()) { + has_style = true; + auto foreground = + detail::make_foreground_color(ts.get_foreground()); + out = detail::copy(foreground.begin(), foreground.end(), out); + } + if (ts.has_background()) { + has_style = true; + auto background = + detail::make_background_color(ts.get_background()); + out = detail::copy(background.begin(), background.end(), out); + } + out = formatter::format(arg.value, ctx); + if (has_style) { + auto reset_color = string_view("\x1b[0m"); + out = detail::copy(reset_color.begin(), reset_color.end(), out); + } + return out; + } +}; + +/** + * Returns an argument that will be formatted using ANSI escape sequences, + * to be used in a formatting function. + * + * **Example**: + * + * fmt::print("Elapsed time: {0:.2f} seconds", + * fmt::styled(1.23, fmt::fg(fmt::color::green) | + * fmt::bg(fmt::color::blue))); + */ +template +FMT_CONSTEXPR auto styled(const T& value, text_style ts) + -> detail::styled_arg> { + return detail::styled_arg>{value, ts}; +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_COLOR_H_ diff --git a/vendor/btop/include/fmt/compile.h b/vendor/btop/include/fmt/compile.h new file mode 100644 index 000000000..f711ba41e --- /dev/null +++ b/vendor/btop/include/fmt/compile.h @@ -0,0 +1,585 @@ +// Formatting library for C++ - experimental format string compilation +// +// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_COMPILE_H_ +#define FMT_COMPILE_H_ + +#ifndef FMT_MODULE +# include // std::back_inserter +#endif + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +// A compile-time string which is compiled into fast formatting code. +FMT_EXPORT class compiled_string {}; + +template +struct is_compiled_string : std::is_base_of {}; + +/** + * Converts a string literal `s` into a format string that will be parsed at + * compile time and converted into efficient formatting code. Requires C++17 + * `constexpr if` compiler support. + * + * **Example**: + * + * // Converts 42 into std::string using the most efficient method and no + * // runtime format string processing. + * std::string s = fmt::format(FMT_COMPILE("{}"), 42); + */ +#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) +# define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::compiled_string) +#else +# define FMT_COMPILE(s) FMT_STRING(s) +#endif + +/** + * Converts a string literal into a format string that will be parsed at + * compile time and converted into efficient formatting code. Requires support + * for class types in constant template parameters (a C++20 feature). + * + * **Example**: + * + * // Converts 42 into std::string using the most efficient method and no + * // runtime format string processing. + * using namespace fmt::literals; + * std::string s = fmt::format("{}"_cf, 42); + */ +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +inline namespace literals { +template constexpr auto operator""_cf() { + return FMT_COMPILE(Str.data); +} +} // namespace literals +#endif + +namespace detail { + +template +constexpr auto first(const T& value, const Tail&...) -> const T& { + return value; +} + +#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) +template struct type_list {}; + +// Returns a reference to the argument at index N from [first, rest...]. +template +constexpr auto get([[maybe_unused]] const T& first, + [[maybe_unused]] const Args&... rest) -> const auto& { + static_assert(N < 1 + sizeof...(Args), "index is out of bounds"); + if constexpr (N == 0) + return first; + else + return detail::get(rest...); +} + +# if FMT_USE_NONTYPE_TEMPLATE_ARGS +template +constexpr auto get_arg_index_by_name(basic_string_view name) -> int { + if constexpr (is_static_named_arg()) { + if (name == T::name) return N; + } + if constexpr (sizeof...(Args) > 0) + return get_arg_index_by_name(name); + (void)name; // Workaround an MSVC bug about "unused" parameter. + return -1; +} +# endif + +template +FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view name) -> int { +# if FMT_USE_NONTYPE_TEMPLATE_ARGS + if constexpr (sizeof...(Args) > 0) + return get_arg_index_by_name<0, Args...>(name); +# endif + (void)name; + return -1; +} + +template +constexpr auto get_arg_index_by_name(basic_string_view name, + type_list) -> int { + return get_arg_index_by_name(name); +} + +template struct get_type_impl; + +template struct get_type_impl> { + using type = + remove_cvref_t(std::declval()...))>; +}; + +template +using get_type = typename get_type_impl::type; + +template struct is_compiled_format : std::false_type {}; + +template struct text { + basic_string_view data; + using char_type = Char; + + template + constexpr auto format(OutputIt out, const T&...) const -> OutputIt { + return write(out, data); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template +constexpr auto make_text(basic_string_view s, size_t pos, size_t size) + -> text { + return {{&s[pos], size}}; +} + +template struct code_unit { + Char value; + using char_type = Char; + + template + constexpr auto format(OutputIt out, const T&...) const -> OutputIt { + *out++ = value; + return out; + } +}; + +// This ensures that the argument type is convertible to `const T&`. +template +constexpr auto get_arg_checked(const Args&... args) -> const T& { + const auto& arg = detail::get(args...); + if constexpr (detail::is_named_arg>()) { + return arg.value; + } else { + return arg; + } +} + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument N. +template struct field { + using char_type = Char; + + template + constexpr auto format(OutputIt out, const T&... args) const -> OutputIt { + const V& arg = get_arg_checked(args...); + if constexpr (std::is_convertible>::value) { + auto s = basic_string_view(arg); + return copy(s.begin(), s.end(), out); + } else { + return write(out, arg); + } + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument with name. +template struct runtime_named_field { + using char_type = Char; + basic_string_view name; + + template + constexpr static auto try_format_argument( + OutputIt& out, + // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9 + [[maybe_unused]] basic_string_view arg_name, const T& arg) -> bool { + if constexpr (is_named_arg::type>::value) { + if (arg_name == arg.name) { + out = write(out, arg.value); + return true; + } + } + return false; + } + + template + constexpr auto format(OutputIt out, const T&... args) const -> OutputIt { + bool found = (try_format_argument(out, name, args) || ...); + if (!found) { + FMT_THROW(format_error("argument with specified name is not found")); + } + return out; + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +// A replacement field that refers to argument N and has format specifiers. +template struct spec_field { + using char_type = Char; + formatter fmt; + + template + constexpr FMT_INLINE auto format(OutputIt out, const T&... args) const + -> OutputIt { + const auto& vargs = + fmt::make_format_args>(args...); + basic_format_context ctx(out, vargs); + return fmt.format(get_arg_checked(args...), ctx); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template struct concat { + L lhs; + R rhs; + using char_type = typename L::char_type; + + template + constexpr auto format(OutputIt out, const T&... args) const -> OutputIt { + out = lhs.format(out, args...); + return rhs.format(out, args...); + } +}; + +template +struct is_compiled_format> : std::true_type {}; + +template +constexpr auto make_concat(L lhs, R rhs) -> concat { + return {lhs, rhs}; +} + +struct unknown_format {}; + +template +constexpr auto parse_text(basic_string_view str, size_t pos) -> size_t { + for (size_t size = str.size(); pos != size; ++pos) { + if (str[pos] == '{' || str[pos] == '}') break; + } + return pos; +} + +template +constexpr auto compile_format_string(S fmt); + +template +constexpr auto parse_tail(T head, S fmt) { + if constexpr (POS != basic_string_view(fmt).size()) { + constexpr auto tail = compile_format_string(fmt); + if constexpr (std::is_same, + unknown_format>()) + return tail; + else + return make_concat(head, tail); + } else { + return head; + } +} + +template struct parse_specs_result { + formatter fmt; + size_t end; + int next_arg_id; +}; + +enum { manual_indexing_id = -1 }; + +template +constexpr auto parse_specs(basic_string_view str, size_t pos, + int next_arg_id) -> parse_specs_result { + str.remove_prefix(pos); + auto ctx = + compile_parse_context(str, max_value(), nullptr, next_arg_id); + auto f = formatter(); + auto end = f.parse(ctx); + return {f, pos + fmt::detail::to_unsigned(end - str.data()), + next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()}; +} + +template struct arg_id_handler { + arg_id_kind kind; + arg_ref arg_id; + + constexpr auto on_auto() -> int { + FMT_ASSERT(false, "handler cannot be used with automatic indexing"); + return 0; + } + constexpr auto on_index(int id) -> int { + kind = arg_id_kind::index; + arg_id = arg_ref(id); + return 0; + } + constexpr auto on_name(basic_string_view id) -> int { + kind = arg_id_kind::name; + arg_id = arg_ref(id); + return 0; + } +}; + +template struct parse_arg_id_result { + arg_id_kind kind; + arg_ref arg_id; + const Char* arg_id_end; +}; + +template +constexpr auto parse_arg_id(const Char* begin, const Char* end) { + auto handler = arg_id_handler{arg_id_kind::none, arg_ref{}}; + auto arg_id_end = parse_arg_id(begin, end, handler); + return parse_arg_id_result{handler.kind, handler.arg_id, arg_id_end}; +} + +template struct field_type { + using type = remove_cvref_t; +}; + +template +struct field_type::value>> { + using type = remove_cvref_t; +}; + +template +constexpr auto parse_replacement_field_then_tail(S fmt) { + using char_type = typename S::char_type; + constexpr auto str = basic_string_view(fmt); + constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type(); + if constexpr (c == '}') { + return parse_tail( + field::type, ARG_INDEX>(), fmt); + } else if constexpr (c != ':') { + FMT_THROW(format_error("expected ':'")); + } else { + constexpr auto result = parse_specs::type>( + str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID); + if constexpr (result.end >= str.size() || str[result.end] != '}') { + FMT_THROW(format_error("expected '}'")); + return 0; + } else { + return parse_tail( + spec_field::type, ARG_INDEX>{ + result.fmt}, + fmt); + } + } +} + +// Compiles a non-empty format string and returns the compiled representation +// or unknown_format() on unrecognized input. +template +constexpr auto compile_format_string(S fmt) { + using char_type = typename S::char_type; + constexpr auto str = basic_string_view(fmt); + if constexpr (str[POS] == '{') { + if constexpr (POS + 1 == str.size()) + FMT_THROW(format_error("unmatched '{' in format string")); + if constexpr (str[POS + 1] == '{') { + return parse_tail(make_text(str, POS, 1), fmt); + } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') { + static_assert(ID != manual_indexing_id, + "cannot switch from manual to automatic argument indexing"); + constexpr auto next_id = + ID != manual_indexing_id ? ID + 1 : manual_indexing_id; + return parse_replacement_field_then_tail, Args, + POS + 1, ID, next_id>(fmt); + } else { + constexpr auto arg_id_result = + parse_arg_id(str.data() + POS + 1, str.data() + str.size()); + constexpr auto arg_id_end_pos = arg_id_result.arg_id_end - str.data(); + constexpr char_type c = + arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type(); + static_assert(c == '}' || c == ':', "missing '}' in format string"); + if constexpr (arg_id_result.kind == arg_id_kind::index) { + static_assert( + ID == manual_indexing_id || ID == 0, + "cannot switch from automatic to manual argument indexing"); + constexpr auto arg_index = arg_id_result.arg_id.index; + return parse_replacement_field_then_tail, + Args, arg_id_end_pos, + arg_index, manual_indexing_id>( + fmt); + } else if constexpr (arg_id_result.kind == arg_id_kind::name) { + constexpr auto arg_index = + get_arg_index_by_name(arg_id_result.arg_id.name, Args{}); + if constexpr (arg_index >= 0) { + constexpr auto next_id = + ID != manual_indexing_id ? ID + 1 : manual_indexing_id; + return parse_replacement_field_then_tail< + decltype(get_type::value), Args, arg_id_end_pos, + arg_index, next_id>(fmt); + } else if constexpr (c == '}') { + return parse_tail( + runtime_named_field{arg_id_result.arg_id.name}, fmt); + } else if constexpr (c == ':') { + return unknown_format(); // no type info for specs parsing + } + } + } + } else if constexpr (str[POS] == '}') { + if constexpr (POS + 1 == str.size()) + FMT_THROW(format_error("unmatched '}' in format string")); + return parse_tail(make_text(str, POS, 1), fmt); + } else { + constexpr auto end = parse_text(str, POS + 1); + if constexpr (end - POS > 1) { + return parse_tail(make_text(str, POS, end - POS), fmt); + } else { + return parse_tail(code_unit{str[POS]}, fmt); + } + } +} + +template ::value)> +constexpr auto compile(S fmt) { + constexpr auto str = basic_string_view(fmt); + if constexpr (str.size() == 0) { + return detail::make_text(str, 0, 0); + } else { + constexpr auto result = + detail::compile_format_string, 0, 0>(fmt); + return result; + } +} +#endif // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) +} // namespace detail + +FMT_BEGIN_EXPORT + +#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction) + +template ::value)> +FMT_INLINE FMT_CONSTEXPR_STRING auto format(const CompiledFormat& cf, + const T&... args) + -> std::basic_string { + auto s = std::basic_string(); + cf.format(std::back_inserter(s), args...); + return s; +} + +template ::value)> +constexpr FMT_INLINE auto format_to(OutputIt out, const CompiledFormat& cf, + const T&... args) -> OutputIt { + return cf.format(out, args...); +} + +template ::value)> +FMT_INLINE FMT_CONSTEXPR_STRING auto format(const S&, T&&... args) + -> std::basic_string { + if constexpr (std::is_same::value) { + constexpr auto str = basic_string_view(S()); + if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') { + const auto& first = detail::first(args...); + if constexpr (detail::is_named_arg< + remove_cvref_t>::value) { + return fmt::to_string(first.value); + } else { + return fmt::to_string(first); + } + } + } + constexpr auto compiled = detail::compile(S()); + if constexpr (std::is_same, + detail::unknown_format>()) { + return fmt::format( + static_cast>(S()), + std::forward(args)...); + } else { + return fmt::format(compiled, std::forward(args)...); + } +} + +template ::value)> +FMT_CONSTEXPR auto format_to(OutputIt out, const S&, T&&... args) -> OutputIt { + constexpr auto compiled = detail::compile(S()); + if constexpr (std::is_same, + detail::unknown_format>()) { + return fmt::format_to( + out, static_cast>(S()), + std::forward(args)...); + } else { + return fmt::format_to(out, compiled, std::forward(args)...); + } +} +#endif + +template ::value)> +auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + fmt::format_to(std::back_inserter(buf), fmt, std::forward(args)...); + return {buf.out(), buf.count()}; +} + +template ::value)> +FMT_CONSTEXPR20 auto formatted_size(const S& fmt, T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + fmt::format_to(appender(buf), fmt, std::forward(args)...); + return buf.count(); +} + +template ::value)> +void print(std::FILE* f, const S& fmt, T&&... args) { + auto buf = memory_buffer(); + fmt::format_to(appender(buf), fmt, std::forward(args)...); + detail::print(f, {buf.data(), buf.size()}); +} + +template ::value)> +void print(const S& fmt, T&&... args) { + print(stdout, fmt, std::forward(args)...); +} + +template class static_format_result { + private: + char data[N]; + + public: + template ::value)> + explicit FMT_CONSTEXPR static_format_result(const S& fmt, T&&... args) { + *fmt::format_to(data, fmt, std::forward(args)...) = '\0'; + } + + auto str() const -> fmt::string_view { return {data, N - 1}; } + auto c_str() const -> const char* { return data; } +}; + +/** + * Formats arguments according to the format string `fmt_str` and produces + * a string of the exact required size at compile time. Both the format string + * and the arguments must be compile-time expressions. + * + * The resulting string can be accessed as a C string via `c_str()` or as + * a `fmt::string_view` via `str()`. + * + * **Example**: + * + * // Produces the static string "42" at compile time. + * static constexpr auto result = FMT_STATIC_FORMAT("{}", 42); + * const char* s = result.c_str(); + */ +#define FMT_STATIC_FORMAT(fmt_str, ...) \ + fmt::static_format_result< \ + fmt::formatted_size(FMT_COMPILE(fmt_str), __VA_ARGS__) + 1>( \ + FMT_COMPILE(fmt_str), __VA_ARGS__) + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_COMPILE_H_ diff --git a/vendor/btop/include/fmt/core.h b/vendor/btop/include/fmt/core.h new file mode 100644 index 000000000..8ca735f0c --- /dev/null +++ b/vendor/btop/include/fmt/core.h @@ -0,0 +1,5 @@ +// This file is only provided for compatibility and may be removed in future +// versions. Use fmt/base.h if you don't need fmt::format and fmt/format.h +// otherwise. + +#include "format.h" diff --git a/vendor/btop/include/fmt/format-inl.h b/vendor/btop/include/fmt/format-inl.h new file mode 100644 index 000000000..9d568dca1 --- /dev/null +++ b/vendor/btop/include/fmt/format-inl.h @@ -0,0 +1,1953 @@ +// Formatting library for C++ - implementation +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_FORMAT_INL_H_ +#define FMT_FORMAT_INL_H_ + +#ifndef FMT_MODULE +# include +# include // errno +# include +# include +# include +#endif + +#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) +# include // _isatty +#endif + +#include "format.h" + +#if FMT_USE_LOCALE && !defined(FMT_MODULE) +# include +#endif + +#ifndef FMT_FUNC +# define FMT_FUNC +#endif + +FMT_BEGIN_NAMESPACE + +#ifndef FMT_CUSTOM_ASSERT_FAIL +FMT_FUNC void assert_fail(const char* file, int line, const char* message) { + // Use unchecked std::fprintf to avoid triggering another assertion when + // writing to stderr fails. + fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message); + abort(); +} +#endif + +#if FMT_USE_LOCALE +namespace detail { +using std::locale; +using std::numpunct; +using std::use_facet; +} // namespace detail + +template > +locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} +#else +namespace detail { +struct locale {}; +template struct numpunct { + auto grouping() const -> std::string { return "\03"; } + auto thousands_sep() const -> Char { return ','; } + auto decimal_point() const -> Char { return '.'; } +}; +template Facet use_facet(locale) { return {}; } +} // namespace detail +#endif // FMT_USE_LOCALE + +template auto locale_ref::get() const -> Locale { + using namespace detail; + static_assert(std::is_same::value, ""); +#if FMT_USE_LOCALE + if (locale_) return *static_cast(locale_); +#endif + return locale(); +} + +namespace detail { + +FMT_FUNC void format_error_code(detail::buffer& out, int error_code, + string_view message) noexcept { + // Report error code making sure that the output fits into + // inline_buffer_size to avoid dynamic memory allocation and potential + // bad_alloc. + out.try_resize(0); + static const char SEP[] = ": "; + static const char ERROR_STR[] = "error "; + // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. + size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; + auto abs_value = static_cast>(error_code); + if (detail::is_negative(error_code)) { + abs_value = 0 - abs_value; + ++error_code_size; + } + error_code_size += detail::to_unsigned(detail::count_digits(abs_value)); + auto it = appender(out); + if (message.size() <= inline_buffer_size - error_code_size) + fmt::format_to(it, FMT_STRING("{}{}"), message, SEP); + fmt::format_to(it, FMT_STRING("{}{}"), ERROR_STR, error_code); + FMT_ASSERT(out.size() <= inline_buffer_size, ""); +} + +FMT_FUNC void do_report_error(format_func func, int error_code, + const char* message) noexcept { + memory_buffer full_message; + func(full_message, error_code, message); + // Don't use fwrite_all because the latter may throw. + if (std::fwrite(full_message.data(), full_message.size(), 1, stderr) > 0) + std::fputc('\n', stderr); +} + +// A wrapper around fwrite that throws on error. +inline void fwrite_all(const void* ptr, size_t count, FILE* stream) { + size_t written = std::fwrite(ptr, 1, count, stream); + if (written < count) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); +} + +template +FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result { + auto&& facet = use_facet>(loc.get()); + auto grouping = facet.grouping(); + auto thousands_sep = grouping.empty() ? Char() : facet.thousands_sep(); + return {std::move(grouping), thousands_sep}; +} +template +FMT_FUNC auto decimal_point_impl(locale_ref loc) -> Char { + return use_facet>(loc.get()).decimal_point(); +} + +#if FMT_USE_LOCALE +FMT_FUNC auto write_loc(appender out, loc_value value, + const format_specs& specs, locale_ref loc) -> bool { + auto locale = loc.get(); + // We cannot use the num_put facet because it may produce output in + // a wrong encoding. + using facet = format_facet; + if (std::has_facet(locale)) + return use_facet(locale).put(out, value, specs); + return facet(locale).put(out, value, specs); +} +#endif +} // namespace detail + +FMT_FUNC void report_error(const char* message) { +#if FMT_MSC_VERSION || defined(__NVCC__) + // Silence unreachable code warnings in MSVC and NVCC because these + // are nearly impossible to fix in a generic code. + volatile bool b = true; + if (!b) return; +#endif + FMT_THROW(format_error(message)); +} + +template typename Locale::id format_facet::id; + +template format_facet::format_facet(Locale& loc) { + auto& np = detail::use_facet>(loc); + grouping_ = np.grouping(); + if (!grouping_.empty()) separator_ = std::string(1, np.thousands_sep()); +} + +#if FMT_USE_LOCALE +template <> +FMT_API FMT_FUNC auto format_facet::do_put( + appender out, loc_value val, const format_specs& specs) const -> bool { + return val.visit( + detail::loc_writer<>{out, specs, separator_, grouping_, decimal_point_}); +} +#endif + +FMT_FUNC auto vsystem_error(int error_code, string_view fmt, format_args args) + -> std::system_error { + auto ec = std::error_code(error_code, std::generic_category()); + return std::system_error(ec, vformat(fmt, args)); +} + +namespace detail { + +template +inline auto operator==(basic_fp x, basic_fp y) -> bool { + return x.f == y.f && x.e == y.e; +} + +// Compilers should be able to optimize this into the ror instruction. +FMT_INLINE auto rotr(uint32_t n, uint32_t r) noexcept -> uint32_t { + r &= 31; + return (n >> r) | (n << (32 - r)); +} +FMT_INLINE auto rotr(uint64_t n, uint32_t r) noexcept -> uint64_t { + r &= 63; + return (n >> r) | (n << (64 - r)); +} + +// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox. +namespace dragonbox { +// Computes upper 64 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline auto umul96_upper64(uint32_t x, uint64_t y) noexcept -> uint64_t { + return umul128_upper64(static_cast(x) << 32, y); +} + +// Computes lower 128 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +inline auto umul192_lower128(uint64_t x, uint128_fallback y) noexcept + -> uint128_fallback { + uint64_t high = x * y.high(); + uint128_fallback high_low = umul128(x, y.low()); + return {high + high_low.high(), high_low.low()}; +} + +// Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline auto umul96_lower64(uint32_t x, uint64_t y) noexcept -> uint64_t { + return x * y; +} + +// Various fast log computations. +inline auto floor_log10_pow2_minus_log10_4_over_3(int e) noexcept -> int { + FMT_ASSERT(e <= 2936 && e >= -2985, "too large exponent"); + return (e * 631305 - 261663) >> 21; +} + +FMT_INLINE_VARIABLE constexpr struct div_small_pow10_infos_struct { + uint32_t divisor; + int shift_amount; +} div_small_pow10_infos[] = {{10, 16}, {100, 16}}; + +// Replaces n by floor(n / pow(10, N)) returning true if and only if n is +// divisible by pow(10, N). +// Precondition: n <= pow(10, N + 1). +template +auto check_divisibility_and_divide_by_pow10(uint32_t& n) noexcept -> bool { + // The numbers below are chosen such that: + // 1. floor(n/d) = floor(nm / 2^k) where d=10 or d=100, + // 2. nm mod 2^k < m if and only if n is divisible by d, + // where m is magic_number, k is shift_amount + // and d is divisor. + // + // Item 1 is a common technique of replacing division by a constant with + // multiplication, see e.g. "Division by Invariant Integers Using + // Multiplication" by Granlund and Montgomery (1994). magic_number (m) is set + // to ceil(2^k/d) for large enough k. + // The idea for item 2 originates from Schubfach. + constexpr auto info = div_small_pow10_infos[N - 1]; + FMT_ASSERT(n <= info.divisor * 10, "n is too large"); + constexpr uint32_t magic_number = + (1u << info.shift_amount) / info.divisor + 1; + n *= magic_number; + const uint32_t comparison_mask = (1u << info.shift_amount) - 1; + bool result = (n & comparison_mask) < magic_number; + n >>= info.shift_amount; + return result; +} + +// Computes floor(n / pow(10, N)) for small n and N. +// Precondition: n <= pow(10, N + 1). +template auto small_division_by_pow10(uint32_t n) noexcept -> uint32_t { + constexpr auto info = div_small_pow10_infos[N - 1]; + FMT_ASSERT(n <= info.divisor * 10, "n is too large"); + constexpr uint32_t magic_number = + (1u << info.shift_amount) / info.divisor + 1; + return (n * magic_number) >> info.shift_amount; +} + +// Computes floor(n / 10^(kappa + 1)) (float) +inline auto divide_by_10_to_kappa_plus_1(uint32_t n) noexcept -> uint32_t { + // 1374389535 = ceil(2^37/100) + return static_cast((static_cast(n) * 1374389535) >> 37); +} +// Computes floor(n / 10^(kappa + 1)) (double) +inline auto divide_by_10_to_kappa_plus_1(uint64_t n) noexcept -> uint64_t { + // 2361183241434822607 = ceil(2^(64+7)/1000) + return umul128_upper64(n, 2361183241434822607ull) >> 7; +} + +// Various subroutines using pow10 cache +template struct cache_accessor; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint64_t; + + static auto get_cached_power(int k) noexcept -> uint64_t { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + static constexpr uint64_t pow10_significands[] = { + 0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f, + 0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb, + 0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28, + 0xf1c90080baf72cb2, 0x971da05074da7bef, 0xbce5086492111aeb, + 0xec1e4a7db69561a6, 0x9392ee8e921d5d08, 0xb877aa3236a4b44a, + 0xe69594bec44de15c, 0x901d7cf73ab0acda, 0xb424dc35095cd810, + 0xe12e13424bb40e14, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff, + 0xdbe6fecebdedd5bf, 0x89705f4136b4a598, 0xabcc77118461cefd, + 0xd6bf94d5e57a42bd, 0x8637bd05af6c69b6, 0xa7c5ac471b478424, + 0xd1b71758e219652c, 0x83126e978d4fdf3c, 0xa3d70a3d70a3d70b, + 0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000, + 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000, + 0xc350000000000000, 0xf424000000000000, 0x9896800000000000, + 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000, + 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000, + 0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000, + 0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000, + 0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000, + 0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0, + 0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940985, + 0xa18f07d736b90be6, 0xc9f2c9cd04674edf, 0xfc6f7c4045812297, + 0x9dc5ada82b70b59e, 0xc5371912364ce306, 0xf684df56c3e01bc7, + 0x9a130b963a6c115d, 0xc097ce7bc90715b4, 0xf0bdc21abb48db21, + 0x96769950b50d88f5, 0xbc143fa4e250eb32, 0xeb194f8e1ae525fe, + 0x92efd1b8d0cf37bf, 0xb7abc627050305ae, 0xe596b7b0c643c71a, + 0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f}; + return pow10_significands[k - float_info::min_k]; + } + + struct compute_mul_result { + carrier_uint result; + bool is_integer; + }; + struct compute_mul_parity_result { + bool parity; + bool is_integer; + }; + + static auto compute_mul(carrier_uint u, + const cache_entry_type& cache) noexcept + -> compute_mul_result { + auto r = umul96_upper64(u, cache); + return {static_cast(r >> 32), + static_cast(r) == 0}; + } + + static auto compute_delta(const cache_entry_type& cache, int beta) noexcept + -> uint32_t { + return static_cast(cache >> (64 - 1 - beta)); + } + + static auto compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta) noexcept + -> compute_mul_parity_result { + FMT_ASSERT(beta >= 1, ""); + FMT_ASSERT(beta < 64, ""); + + auto r = umul96_lower64(two_f, cache); + return {((r >> (64 - beta)) & 1) != 0, + static_cast(r >> (32 - beta)) == 0}; + } + + static auto compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return static_cast( + (cache - (cache >> (num_significand_bits() + 2))) >> + (64 - num_significand_bits() - 1 - beta)); + } + + static auto compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return static_cast( + (cache + (cache >> (num_significand_bits() + 1))) >> + (64 - num_significand_bits() - 1 - beta)); + } + + static auto compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (static_cast( + cache >> (64 - num_significand_bits() - 2 - beta)) + + 1) / + 2; + } +}; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint128_fallback; + + static auto get_cached_power(int k) noexcept -> uint128_fallback { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + + static constexpr uint128_fallback pow10_significands[] = { +#if FMT_USE_FULL_CACHE_DRAGONBOX + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, + {0x9faacf3df73609b1, 0x77b191618c54e9ad}, + {0xc795830d75038c1d, 0xd59df5b9ef6a2418}, + {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e}, + {0x9becce62836ac577, 0x4ee367f9430aec33}, + {0xc2e801fb244576d5, 0x229c41f793cda740}, + {0xf3a20279ed56d48a, 0x6b43527578c11110}, + {0x9845418c345644d6, 0x830a13896b78aaaa}, + {0xbe5691ef416bd60c, 0x23cc986bc656d554}, + {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9}, + {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa}, + {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54}, + {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69}, + {0x91376c36d99995be, 0x23100809b9c21fa2}, + {0xb58547448ffffb2d, 0xabd40a0c2832a78b}, + {0xe2e69915b3fff9f9, 0x16c90c8f323f516d}, + {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4}, + {0xb1442798f49ffb4a, 0x99cd11cfdf41779d}, + {0xdd95317f31c7fa1d, 0x40405643d711d584}, + {0x8a7d3eef7f1cfc52, 0x482835ea666b2573}, + {0xad1c8eab5ee43b66, 0xda3243650005eed0}, + {0xd863b256369d4a40, 0x90bed43e40076a83}, + {0x873e4f75e2224e68, 0x5a7744a6e804a292}, + {0xa90de3535aaae202, 0x711515d0a205cb37}, + {0xd3515c2831559a83, 0x0d5a5b44ca873e04}, + {0x8412d9991ed58091, 0xe858790afe9486c3}, + {0xa5178fff668ae0b6, 0x626e974dbe39a873}, + {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, + {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a}, + {0xa139029f6a239f72, 0x1c1fffc1ebc44e81}, + {0xc987434744ac874e, 0xa327ffb266b56221}, + {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9}, + {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa}, + {0xc4ce17b399107c22, 0xcb550fb4384d21d4}, + {0xf6019da07f549b2b, 0x7e2a53a146606a49}, + {0x99c102844f94e0fb, 0x2eda7444cbfc426e}, + {0xc0314325637a1939, 0xfa911155fefb5309}, + {0xf03d93eebc589f88, 0x793555ab7eba27cb}, + {0x96267c7535b763b5, 0x4bc1558b2f3458df}, + {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17}, + {0xea9c227723ee8bcb, 0x465e15a979c1cadd}, + {0x92a1958a7675175f, 0x0bfacd89ec191eca}, + {0xb749faed14125d36, 0xcef980ec671f667c}, + {0xe51c79a85916f484, 0x82b7e12780e7401b}, + {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811}, + {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16}, + {0xdfbdcece67006ac9, 0x67a791e093e1d49b}, + {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1}, + {0xaecc49914078536d, 0x58fae9f773886e19}, + {0xda7f5bf590966848, 0xaf39a475506a899f}, + {0x888f99797a5e012d, 0x6d8406c952429604}, + {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84}, + {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65}, + {0x855c3be0a17fcd26, 0x5cf2eea09a550680}, + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f}, + {0xd0601d8efc57b08b, 0xf13b94daf124da27}, + {0x823c12795db6ce57, 0x76c53d08d6b70859}, + {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f}, + {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a}, + {0xfe5d54150b090b02, 0xd3f93b35435d7c4d}, + {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0}, + {0xc6b8e9b0709f109a, 0x359ab6419ca1091c}, + {0xf867241c8cc6d4c0, 0xc30163d203c94b63}, + {0x9b407691d7fc44f8, 0x79e0de63425dcf1e}, + {0xc21094364dfb5636, 0x985915fc12f542e5}, + {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e}, + {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43}, + {0xbd8430bd08277231, 0x50c6ff782a838354}, + {0xece53cec4a314ebd, 0xa4f8bf5635246429}, + {0x940f4613ae5ed136, 0x871b7795e136be9a}, + {0xb913179899f68584, 0x28e2557b59846e40}, + {0xe757dd7ec07426e5, 0x331aeada2fe589d0}, + {0x9096ea6f3848984f, 0x3ff0d2c85def7622}, + {0xb4bca50b065abe63, 0x0fed077a756b53aa}, + {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895}, + {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d}, + {0xb080392cc4349dec, 0xbd8d794d96aacfb4}, + {0xdca04777f541c567, 0xecf0d7a0fc5583a1}, + {0x89e42caaf9491b60, 0xf41686c49db57245}, + {0xac5d37d5b79b6239, 0x311c2875c522ced6}, + {0xd77485cb25823ac7, 0x7d633293366b828c}, + {0x86a8d39ef77164bc, 0xae5dff9c02033198}, + {0xa8530886b54dbdeb, 0xd9f57f830283fdfd}, + {0xd267caa862a12d66, 0xd072df63c324fd7c}, + {0x8380dea93da4bc60, 0x4247cb9e59f71e6e}, + {0xa46116538d0deb78, 0x52d9be85f074e609}, + {0xcd795be870516656, 0x67902e276c921f8c}, + {0x806bd9714632dff6, 0x00ba1cd8a3db53b7}, + {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5}, + {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce}, + {0xfad2a4b13d1b5d6c, 0x796b805720085f82}, + {0x9cc3a6eec6311a63, 0xcbe3303674053bb1}, + {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d}, + {0xf4f1b4d515acb93b, 0xee92fb5515482d45}, + {0x991711052d8bf3c5, 0x751bdd152d4d1c4b}, + {0xbf5cd54678eef0b6, 0xd262d45a78a0635e}, + {0xef340a98172aace4, 0x86fb897116c87c35}, + {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1}, + {0xbae0a846d2195712, 0x8974836059cca10a}, + {0xe998d258869facd7, 0x2bd1a438703fc94c}, + {0x91ff83775423cc06, 0x7b6306a34627ddd0}, + {0xb67f6455292cbf08, 0x1a3bc84c17b1d543}, + {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94}, + {0x8e938662882af53e, 0x547eb47b7282ee9d}, + {0xb23867fb2a35b28d, 0xe99e619a4f23aa44}, + {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5}, + {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05}, + {0xae0b158b4738705e, 0x9624ab50b148d446}, + {0xd98ddaee19068c76, 0x3badd624dd9b0958}, + {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7}, + {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d}, + {0xd47487cc8470652b, 0x7647c32000696720}, + {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074}, + {0xa5fb0a17c777cf09, 0xf468107100525891}, + {0xcf79cc9db955c2cc, 0x7182148d4066eeb5}, + {0x81ac1fe293d599bf, 0xc6f14cd848405531}, + {0xa21727db38cb002f, 0xb8ada00e5a506a7d}, + {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d}, + {0xfd442e4688bd304a, 0x908f4a166d1da664}, + {0x9e4a9cec15763e2e, 0x9a598e4e043287ff}, + {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe}, + {0xf7549530e188c128, 0xd12bee59e68ef47d}, + {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf}, + {0xc13a148e3032d6e7, 0xe36a52363c1faf02}, + {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2}, + {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba}, + {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8}, + {0xebdf661791d60f56, 0x111b495b3464ad22}, + {0x936b9fcebb25c995, 0xcab10dd900beec35}, + {0xb84687c269ef3bfb, 0x3d5d514f40eea743}, + {0xe65829b3046b0afa, 0x0cb4a5a3112a5113}, + {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac}, + {0xb3f4e093db73a093, 0x59ed216765690f57}, + {0xe0f218b8d25088b8, 0x306869c13ec3532d}, + {0x8c974f7383725573, 0x1e414218c73a13fc}, + {0xafbd2350644eeacf, 0xe5d1929ef90898fb}, + {0xdbac6c247d62a583, 0xdf45f746b74abf3a}, + {0x894bc396ce5da772, 0x6b8bba8c328eb784}, + {0xab9eb47c81f5114f, 0x066ea92f3f326565}, + {0xd686619ba27255a2, 0xc80a537b0efefebe}, + {0x8613fd0145877585, 0xbd06742ce95f5f37}, + {0xa798fc4196e952e7, 0x2c48113823b73705}, + {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6}, + {0x82ef85133de648c4, 0x9a984d73dbe722fc}, + {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb}, + {0xcc963fee10b7d1b3, 0x318df905079926a9}, + {0xffbbcfe994e5c61f, 0xfdf17746497f7053}, + {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634}, + {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1}, + {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1}, + {0x9c1661a651213e2d, 0x06bea10ca65c084f}, + {0xc31bfa0fe5698db8, 0x486e494fcff30a63}, + {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb}, + {0x986ddb5c6b3a76b7, 0xf89629465a75e01d}, + {0xbe89523386091465, 0xf6bbb397f1135824}, + {0xee2ba6c0678b597f, 0x746aa07ded582e2d}, + {0x94db483840b717ef, 0xa8c2a44eb4571cdd}, + {0xba121a4650e4ddeb, 0x92f34d62616ce414}, + {0xe896a0d7e51e1566, 0x77b020baf9c81d18}, + {0x915e2486ef32cd60, 0x0ace1474dc1d122f}, + {0xb5b5ada8aaff80b8, 0x0d819992132456bb}, + {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a}, + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2}, + {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3}, + {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf}, + {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c}, + {0xad4ab7112eb3929d, 0x86c16c98d2c953c7}, + {0xd89d64d57a607744, 0xe871c7bf077ba8b8}, + {0x87625f056c7c4a8b, 0x11471cd764ad4973}, + {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0}, + {0xd389b47879823479, 0x4aff1d108d4ec2c4}, + {0x843610cb4bf160cb, 0xcedf722a585139bb}, + {0xa54394fe1eedb8fe, 0xc2974eb4ee658829}, + {0xce947a3da6a9273e, 0x733d226229feea33}, + {0x811ccc668829b887, 0x0806357d5a3f5260}, + {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8}, + {0xc9bcff6034c13052, 0xfc89b393dd02f0b6}, + {0xfc2c3f3841f17c67, 0xbbac2078d443ace3}, + {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e}, + {0xc5029163f384a931, 0x0a9e795e65d4df12}, + {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6}, + {0x99ea0196163fa42e, 0x504bced1bf8e4e46}, + {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7}, + {0xf07da27a82c37088, 0x5d767327bb4e5a4d}, + {0x964e858c91ba2655, 0x3a6a07f8d510f870}, + {0xbbe226efb628afea, 0x890489f70a55368c}, + {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f}, + {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e}, + {0xb77ada0617e3bbcb, 0x09ce6ebb40173745}, + {0xe55990879ddcaabd, 0xcc420a6a101d0516}, + {0x8f57fa54c2a9eab6, 0x9fa946824a12232e}, + {0xb32df8e9f3546564, 0x47939822dc96abfa}, + {0xdff9772470297ebd, 0x59787e2b93bc56f8}, + {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b}, + {0xaefae51477a06b03, 0xede622920b6b23f2}, + {0xdab99e59958885c4, 0xe95fab368e45ecee}, + {0x88b402f7fd75539b, 0x11dbcb0218ebb415}, + {0xaae103b5fcd2a881, 0xd652bdc29f26a11a}, + {0xd59944a37c0752a2, 0x4be76d3346f04960}, + {0x857fcae62d8493a5, 0x6f70a4400c562ddc}, + {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953}, + {0xd097ad07a71f26b2, 0x7e2000a41346a7a8}, + {0x825ecc24c873782f, 0x8ed400668c0c28c9}, + {0xa2f67f2dfa90563b, 0x728900802f0f32fb}, + {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba}, + {0xfea126b7d78186bc, 0xe2f610c84987bfa9}, + {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca}, + {0xc6ede63fa05d3143, 0x91503d1c79720dbc}, + {0xf8a95fcf88747d94, 0x75a44c6397ce912b}, + {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb}, + {0xc24452da229b021b, 0xfbe85badce996169}, + {0xf2d56790ab41c2a2, 0xfae27299423fb9c4}, + {0x97c560ba6b0919a5, 0xdccd879fc967d41b}, + {0xbdb6b8e905cb600f, 0x5400e987bbc1c921}, + {0xed246723473e3813, 0x290123e9aab23b69}, + {0x9436c0760c86e30b, 0xf9a0b6720aaf6522}, + {0xb94470938fa89bce, 0xf808e40e8d5b3e6a}, + {0xe7958cb87392c2c2, 0xb60b1d1230b20e05}, + {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3}, + {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4}, + {0xe2280b6c20dd5232, 0x25c6da63c38de1b1}, + {0x8d590723948a535f, 0x579c487e5a38ad0f}, + {0xb0af48ec79ace837, 0x2d835a9df0c6d852}, + {0xdcdb1b2798182244, 0xf8e431456cf88e66}, + {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900}, + {0xac8b2d36eed2dac5, 0xe272467e3d222f40}, + {0xd7adf884aa879177, 0x5b0ed81dcc6abb10}, + {0x86ccbb52ea94baea, 0x98e947129fc2b4ea}, + {0xa87fea27a539e9a5, 0x3f2398d747b36225}, + {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae}, + {0x83a3eeeef9153e89, 0x1953cf68300424ad}, + {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8}, + {0xcdb02555653131b6, 0x3792f412cb06794e}, + {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1}, + {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5}, + {0xc8de047564d20a8b, 0xf245825a5a445276}, + {0xfb158592be068d2e, 0xeed6e2f0f0d56713}, + {0x9ced737bb6c4183d, 0x55464dd69685606c}, + {0xc428d05aa4751e4c, 0xaa97e14c3c26b887}, + {0xf53304714d9265df, 0xd53dd99f4b3066a9}, + {0x993fe2c6d07b7fab, 0xe546a8038efe402a}, + {0xbf8fdb78849a5f96, 0xde98520472bdd034}, + {0xef73d256a5c0f77c, 0x963e66858f6d4441}, + {0x95a8637627989aad, 0xdde7001379a44aa9}, + {0xbb127c53b17ec159, 0x5560c018580d5d53}, + {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7}, + {0x9226712162ab070d, 0xcab3961304ca70e9}, + {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23}, + {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b}, + {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243}, + {0xb267ed1940f1c61c, 0x55f038b237591ed4}, + {0xdf01e85f912e37a3, 0x6b6c46dec52f6689}, + {0x8b61313bbabce2c6, 0x2323ac4b3b3da016}, + {0xae397d8aa96c1b77, 0xabec975e0a0d081b}, + {0xd9c7dced53c72255, 0x96e7bd358c904a22}, + {0x881cea14545c7575, 0x7e50d64177da2e55}, + {0xaa242499697392d2, 0xdde50bd1d5d0b9ea}, + {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865}, + {0x84ec3c97da624ab4, 0xbd5af13bef0b113f}, + {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f}, + {0xcfb11ead453994ba, 0x67de18eda5814af3}, + {0x81ceb32c4b43fcf4, 0x80eacf948770ced8}, + {0xa2425ff75e14fc31, 0xa1258379a94d028e}, + {0xcad2f7f5359a3b3e, 0x096ee45813a04331}, + {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd}, + {0x9e74d1b791e07e48, 0x775ea264cf55347e}, + {0xc612062576589dda, 0x95364afe032a819e}, + {0xf79687aed3eec551, 0x3a83ddbd83f52205}, + {0x9abe14cd44753b52, 0xc4926a9672793543}, + {0xc16d9a0095928a27, 0x75b7053c0f178294}, + {0xf1c90080baf72cb1, 0x5324c68b12dd6339}, + {0x971da05074da7bee, 0xd3f6fc16ebca5e04}, + {0xbce5086492111aea, 0x88f4bb1ca6bcf585}, + {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6}, + {0x9392ee8e921d5d07, 0x3aff322e62439fd0}, + {0xb877aa3236a4b449, 0x09befeb9fad487c3}, + {0xe69594bec44de15b, 0x4c2ebe687989a9b4}, + {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11}, + {0xb424dc35095cd80f, 0x538484c19ef38c95}, + {0xe12e13424bb40e13, 0x2865a5f206b06fba}, + {0x8cbccc096f5088cb, 0xf93f87b7442e45d4}, + {0xafebff0bcb24aafe, 0xf78f69a51539d749}, + {0xdbe6fecebdedd5be, 0xb573440e5a884d1c}, + {0x89705f4136b4a597, 0x31680a88f8953031}, + {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e}, + {0xd6bf94d5e57a42bc, 0x3d32907604691b4d}, + {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110}, + {0xa7c5ac471b478423, 0x0fcf80dc33721d54}, + {0xd1b71758e219652b, 0xd3c36113404ea4a9}, + {0x83126e978d4fdf3b, 0x645a1cac083126ea}, + {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4}, + {0xcccccccccccccccc, 0xcccccccccccccccd}, + {0x8000000000000000, 0x0000000000000000}, + {0xa000000000000000, 0x0000000000000000}, + {0xc800000000000000, 0x0000000000000000}, + {0xfa00000000000000, 0x0000000000000000}, + {0x9c40000000000000, 0x0000000000000000}, + {0xc350000000000000, 0x0000000000000000}, + {0xf424000000000000, 0x0000000000000000}, + {0x9896800000000000, 0x0000000000000000}, + {0xbebc200000000000, 0x0000000000000000}, + {0xee6b280000000000, 0x0000000000000000}, + {0x9502f90000000000, 0x0000000000000000}, + {0xba43b74000000000, 0x0000000000000000}, + {0xe8d4a51000000000, 0x0000000000000000}, + {0x9184e72a00000000, 0x0000000000000000}, + {0xb5e620f480000000, 0x0000000000000000}, + {0xe35fa931a0000000, 0x0000000000000000}, + {0x8e1bc9bf04000000, 0x0000000000000000}, + {0xb1a2bc2ec5000000, 0x0000000000000000}, + {0xde0b6b3a76400000, 0x0000000000000000}, + {0x8ac7230489e80000, 0x0000000000000000}, + {0xad78ebc5ac620000, 0x0000000000000000}, + {0xd8d726b7177a8000, 0x0000000000000000}, + {0x878678326eac9000, 0x0000000000000000}, + {0xa968163f0a57b400, 0x0000000000000000}, + {0xd3c21bcecceda100, 0x0000000000000000}, + {0x84595161401484a0, 0x0000000000000000}, + {0xa56fa5b99019a5c8, 0x0000000000000000}, + {0xcecb8f27f4200f3a, 0x0000000000000000}, + {0x813f3978f8940984, 0x4000000000000000}, + {0xa18f07d736b90be5, 0x5000000000000000}, + {0xc9f2c9cd04674ede, 0xa400000000000000}, + {0xfc6f7c4045812296, 0x4d00000000000000}, + {0x9dc5ada82b70b59d, 0xf020000000000000}, + {0xc5371912364ce305, 0x6c28000000000000}, + {0xf684df56c3e01bc6, 0xc732000000000000}, + {0x9a130b963a6c115c, 0x3c7f400000000000}, + {0xc097ce7bc90715b3, 0x4b9f100000000000}, + {0xf0bdc21abb48db20, 0x1e86d40000000000}, + {0x96769950b50d88f4, 0x1314448000000000}, + {0xbc143fa4e250eb31, 0x17d955a000000000}, + {0xeb194f8e1ae525fd, 0x5dcfab0800000000}, + {0x92efd1b8d0cf37be, 0x5aa1cae500000000}, + {0xb7abc627050305ad, 0xf14a3d9e40000000}, + {0xe596b7b0c643c719, 0x6d9ccd05d0000000}, + {0x8f7e32ce7bea5c6f, 0xe4820023a2000000}, + {0xb35dbf821ae4f38b, 0xdda2802c8a800000}, + {0xe0352f62a19e306e, 0xd50b2037ad200000}, + {0x8c213d9da502de45, 0x4526f422cc340000}, + {0xaf298d050e4395d6, 0x9670b12b7f410000}, + {0xdaf3f04651d47b4c, 0x3c0cdd765f114000}, + {0x88d8762bf324cd0f, 0xa5880a69fb6ac800}, + {0xab0e93b6efee0053, 0x8eea0d047a457a00}, + {0xd5d238a4abe98068, 0x72a4904598d6d880}, + {0x85a36366eb71f041, 0x47a6da2b7f864750}, + {0xa70c3c40a64e6c51, 0x999090b65f67d924}, + {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d}, + {0x82818f1281ed449f, 0xbff8f10e7a8921a5}, + {0xa321f2d7226895c7, 0xaff72d52192b6a0e}, + {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764491}, + {0xfee50b7025c36a08, 0x02f236d04753d5b5}, + {0x9f4f2726179a2245, 0x01d762422c946591}, + {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef6}, + {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb3}, + {0x9b934c3b330c8577, 0x63cc55f49f88eb30}, + {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fc}, + {0xf316271c7fc3908a, 0x8bef464e3945ef7b}, + {0x97edd871cfda3a56, 0x97758bf0e3cbb5ad}, + {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea318}, + {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bde}, + {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6b}, + {0xb975d6b6ee39e436, 0xb3e2fd538e122b45}, + {0xe7d34c64a9c85d44, 0x60dbbca87196b617}, + {0x90e40fbeea1d3a4a, 0xbc8955e946fe31ce}, + {0xb51d13aea4a488dd, 0x6babab6398bdbe42}, + {0xe264589a4dcdab14, 0xc696963c7eed2dd2}, + {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca3}, + {0xb0de65388cc8ada8, 0x3b25a55f43294bcc}, + {0xdd15fe86affad912, 0x49ef0eb713f39ebf}, + {0x8a2dbf142dfcc7ab, 0x6e3569326c784338}, + {0xacb92ed9397bf996, 0x49c2c37f07965405}, + {0xd7e77a8f87daf7fb, 0xdc33745ec97be907}, + {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a4}, + {0xa8acd7c0222311bc, 0xc40832ea0d68ce0d}, + {0xd2d80db02aabd62b, 0xf50a3fa490c30191}, + {0x83c7088e1aab65db, 0x792667c6da79e0fb}, + {0xa4b8cab1a1563f52, 0x577001b891185939}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87}, + {0x80b05e5ac60b6178, 0x544f8158315b05b5}, + {0xa0dc75f1778e39d6, 0x696361ae3db1c722}, + {0xc913936dd571c84c, 0x03bc3a19cd1e38ea}, + {0xfb5878494ace3a5f, 0x04ab48a04065c724}, + {0x9d174b2dcec0e47b, 0x62eb0d64283f9c77}, + {0xc45d1df942711d9a, 0x3ba5d0bd324f8395}, + {0xf5746577930d6500, 0xca8f44ec7ee3647a}, + {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecc}, + {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67f}, + {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101f}, + {0x95d04aee3b80ece5, 0xbba1f1d158724a13}, + {0xbb445da9ca61281f, 0x2a8a6e45ae8edc98}, + {0xea1575143cf97226, 0xf52d09d71a3293be}, + {0x924d692ca61be758, 0x593c2626705f9c57}, + {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836d}, + {0xe498f455c38b997a, 0x0b6dfb9c0f956448}, + {0x8edf98b59a373fec, 0x4724bd4189bd5ead}, + {0xb2977ee300c50fe7, 0x58edec91ec2cb658}, + {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ee}, + {0x8b865b215899f46c, 0xbd79e0d20082ee75}, + {0xae67f1e9aec07187, 0xecd8590680a3aa12}, + {0xda01ee641a708de9, 0xe80e6f4820cc9496}, + {0x884134fe908658b2, 0x3109058d147fdcde}, + {0xaa51823e34a7eede, 0xbd4b46f0599fd416}, + {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91b}, + {0x850fadc09923329e, 0x03e2cf6bc604ddb1}, + {0xa6539930bf6bff45, 0x84db8346b786151d}, + {0xcfe87f7cef46ff16, 0xe612641865679a64}, + {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07f}, + {0xa26da3999aef7749, 0xe3be5e330f38f09e}, + {0xcb090c8001ab551c, 0x5cadf5bfd3072cc6}, + {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f7}, + {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afb}, + {0xc646d63501a1511d, 0xb281e1fd541501b9}, + {0xf7d88bc24209a565, 0x1f225a7ca91a4227}, + {0x9ae757596946075f, 0x3375788de9b06959}, + {0xc1a12d2fc3978937, 0x0052d6b1641c83af}, + {0xf209787bb47d6b84, 0xc0678c5dbd23a49b}, + {0x9745eb4d50ce6332, 0xf840b7ba963646e1}, + {0xbd176620a501fbff, 0xb650e5a93bc3d899}, + {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebf}, + {0x93ba47c980e98cdf, 0xc66f336c36b10138}, + {0xb8a8d9bbe123f017, 0xb80b0047445d4185}, + {0xe6d3102ad96cec1d, 0xa60dc059157491e6}, + {0x9043ea1ac7e41392, 0x87c89837ad68db30}, + {0xb454e4a179dd1877, 0x29babe4598c311fc}, + {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67b}, + {0x8ce2529e2734bb1d, 0x1899e4a65f58660d}, + {0xb01ae745b101e9e4, 0x5ec05dcff72e7f90}, + {0xdc21a1171d42645d, 0x76707543f4fa1f74}, + {0x899504ae72497eba, 0x6a06494a791c53a9}, + {0xabfa45da0edbde69, 0x0487db9d17636893}, + {0xd6f8d7509292d603, 0x45a9d2845d3c42b7}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3}, + {0xa7f26836f282b732, 0x8e6cac7768d7141f}, + {0xd1ef0244af2364ff, 0x3207d795430cd927}, + {0x8335616aed761f1f, 0x7f44e6bd49e807b9}, + {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a7}, + {0xcd036837130890a1, 0x36dba887c37a8c10}, + {0x802221226be55a64, 0xc2494954da2c978a}, + {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6d}, + {0xc83553c5c8965d3d, 0x6f92829494e5acc8}, + {0xfa42a8b73abbf48c, 0xcb772339ba1f17fa}, + {0x9c69a97284b578d7, 0xff2a760414536efc}, + {0xc38413cf25e2d70d, 0xfef5138519684abb}, + {0xf46518c2ef5b8cd1, 0x7eb258665fc25d6a}, + {0x98bf2f79d5993802, 0xef2f773ffbd97a62}, + {0xbeeefb584aff8603, 0xaafb550ffacfd8fb}, + {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf39}, + {0x952ab45cfa97a0b2, 0xdd945a747bf26184}, + {0xba756174393d88df, 0x94f971119aeef9e5}, + {0xe912b9d1478ceb17, 0x7a37cd5601aab85e}, + {0x91abb422ccb812ee, 0xac62e055c10ab33b}, + {0xb616a12b7fe617aa, 0x577b986b314d600a}, + {0xe39c49765fdf9d94, 0xed5a7e85fda0b80c}, + {0x8e41ade9fbebc27d, 0x14588f13be847308}, + {0xb1d219647ae6b31c, 0x596eb2d8ae258fc9}, + {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bc}, + {0x8aec23d680043bee, 0x25de7bb9480d5855}, + {0xada72ccc20054ae9, 0xaf561aa79a10ae6b}, + {0xd910f7ff28069da4, 0x1b2ba1518094da05}, + {0x87aa9aff79042286, 0x90fb44d2f05d0843}, + {0xa99541bf57452b28, 0x353a1607ac744a54}, + {0xd3fa922f2d1675f2, 0x42889b8997915ce9}, + {0x847c9b5d7c2e09b7, 0x69956135febada12}, + {0xa59bc234db398c25, 0x43fab9837e699096}, + {0xcf02b2c21207ef2e, 0x94f967e45e03f4bc}, + {0x8161afb94b44f57d, 0x1d1be0eebac278f6}, + {0xa1ba1ba79e1632dc, 0x6462d92a69731733}, + {0xca28a291859bbf93, 0x7d7b8f7503cfdcff}, + {0xfcb2cb35e702af78, 0x5cda735244c3d43f}, + {0x9defbf01b061adab, 0x3a0888136afa64a8}, + {0xc56baec21c7a1916, 0x088aaa1845b8fdd1}, + {0xf6c69a72a3989f5b, 0x8aad549e57273d46}, + {0x9a3c2087a63f6399, 0x36ac54e2f678864c}, + {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7de}, + {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d6}, + {0x969eb7c47859e743, 0x9f644ae5a4b1b326}, + {0xbc4665b596706114, 0x873d5d9f0dde1fef}, + {0xeb57ff22fc0c7959, 0xa90cb506d155a7eb}, + {0x9316ff75dd87cbd8, 0x09a7f12442d588f3}, + {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb30}, + {0xe5d3ef282a242e81, 0x8f1668c8a86da5fb}, + {0x8fa475791a569d10, 0xf96e017d694487bd}, + {0xb38d92d760ec4455, 0x37c981dcc395a9ad}, + {0xe070f78d3927556a, 0x85bbe253f47b1418}, + {0x8c469ab843b89562, 0x93956d7478ccec8f}, + {0xaf58416654a6babb, 0x387ac8d1970027b3}, + {0xdb2e51bfe9d0696a, 0x06997b05fcc0319f}, + {0x88fcf317f22241e2, 0x441fece3bdf81f04}, + {0xab3c2fddeeaad25a, 0xd527e81cad7626c4}, + {0xd60b3bd56a5586f1, 0x8a71e223d8d3b075}, + {0x85c7056562757456, 0xf6872d5667844e4a}, + {0xa738c6bebb12d16c, 0xb428f8ac016561dc}, + {0xd106f86e69d785c7, 0xe13336d701beba53}, + {0x82a45b450226b39c, 0xecc0024661173474}, + {0xa34d721642b06084, 0x27f002d7f95d0191}, + {0xcc20ce9bd35c78a5, 0x31ec038df7b441f5}, + {0xff290242c83396ce, 0x7e67047175a15272}, + {0x9f79a169bd203e41, 0x0f0062c6e984d387}, + {0xc75809c42c684dd1, 0x52c07b78a3e60869}, + {0xf92e0c3537826145, 0xa7709a56ccdf8a83}, + {0x9bbcc7a142b17ccb, 0x88a66076400bb692}, + {0xc2abf989935ddbfe, 0x6acff893d00ea436}, + {0xf356f7ebf83552fe, 0x0583f6b8c4124d44}, + {0x98165af37b2153de, 0xc3727a337a8b704b}, + {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5d}, + {0xeda2ee1c7064130c, 0x1162def06f79df74}, + {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba9}, + {0xb9a74a0637ce2ee1, 0x6d953e2bd7173693}, + {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0438}, + {0x910ab1d4db9914a0, 0x1d9c9892400a22a3}, + {0xb54d5e4a127f59c8, 0x2503beb6d00cab4c}, + {0xe2a0b5dc971f303a, 0x2e44ae64840fd61e}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d3}, + {0xb10d8e1456105dad, 0x7425a83e872c5f48}, + {0xdd50f1996b947518, 0xd12f124e28f7771a}, + {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa70}, + {0xace73cbfdc0bfb7b, 0x636cc64d1001550c}, + {0xd8210befd30efa5a, 0x3c47f7e05401aa4f}, + {0x8714a775e3e95c78, 0x65acfaec34810a72}, + {0xa8d9d1535ce3b396, 0x7f1839a741a14d0e}, + {0xd31045a8341ca07c, 0x1ede48111209a051}, + {0x83ea2b892091e44d, 0x934aed0aab460433}, + {0xa4e4b66b68b65d60, 0xf81da84d56178540}, + {0xce1de40642e3f4b9, 0x36251260ab9d668f}, + {0x80d2ae83e9ce78f3, 0xc1d72b7c6b42601a}, + {0xa1075a24e4421730, 0xb24cf65b8612f820}, + {0xc94930ae1d529cfc, 0xdee033f26797b628}, + {0xfb9b7cd9a4a7443c, 0x169840ef017da3b2}, + {0x9d412e0806e88aa5, 0x8e1f289560ee864f}, + {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e3}, + {0xf5b5d7ec8acb58a2, 0xae10af696774b1dc}, + {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef2a}, + {0xbff610b0cc6edd3f, 0x17fd090a58d32af4}, + {0xeff394dcff8a948e, 0xddfc4b4cef07f5b1}, + {0x95f83d0a1fb69cd9, 0x4abdaf101564f98f}, + {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f2}, + {0xea53df5fd18d5513, 0x84c86189216dc5ee}, + {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb5}, + {0xb7118682dbb66a77, 0x3fbc8c33221dc2a2}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334b}, + {0x8f05b1163ba6832d, 0x29cb4d87f2a7400f}, + {0xb2c71d5bca9023f8, 0x743e20e9ef511013}, + {0xdf78e4b2bd342cf6, 0x914da9246b255417}, + {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548f}, + {0xae9672aba3d0c320, 0xa184ac2473b529b2}, + {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741f}, + {0x8865899617fb1871, 0x7e2fa67c7a658893}, + {0xaa7eebfb9df9de8d, 0xddbb901b98feeab8}, + {0xd51ea6fa85785631, 0x552a74227f3ea566}, + {0x8533285c936b35de, 0xd53a88958f872760}, + {0xa67ff273b8460356, 0x8a892abaf368f138}, + {0xd01fef10a657842c, 0x2d2b7569b0432d86}, + {0x8213f56a67f6b29b, 0x9c3b29620e29fc74}, + {0xa298f2c501f45f42, 0x8349f3ba91b47b90}, + {0xcb3f2f7642717713, 0x241c70a936219a74}, + {0xfe0efb53d30dd4d7, 0xed238cd383aa0111}, + {0x9ec95d1463e8a506, 0xf4363804324a40ab}, + {0xc67bb4597ce2ce48, 0xb143c6053edcd0d6}, + {0xf81aa16fdc1b81da, 0xdd94b7868e94050b}, + {0x9b10a4e5e9913128, 0xca7cf2b4191c8327}, + {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f1}, + {0xf24a01a73cf2dccf, 0xbc633b39673c8ced}, + {0x976e41088617ca01, 0xd5be0503e085d814}, + {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e19}, + {0xec9c459d51852ba2, 0xddf8e7d60ed1219f}, + {0x93e1ab8252f33b45, 0xcabb90e5c942b504}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936244}, + {0xe7109bfba19c0c9d, 0x0cc512670a783ad5}, + {0x906a617d450187e2, 0x27fb2b80668b24c6}, + {0xb484f9dc9641e9da, 0xb1f9f660802dedf7}, + {0xe1a63853bbd26451, 0x5e7873f8a0396974}, + {0x8d07e33455637eb2, 0xdb0b487b6423e1e9}, + {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda63}, + {0xdc5c5301c56b75f7, 0x7641a140cc7810fc}, + {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9e}, + {0xac2820d9623bf429, 0x546345fa9fbdcd45}, + {0xd732290fbacaf133, 0xa97c177947ad4096}, + {0x867f59a9d4bed6c0, 0x49ed8eabcccc485e}, + {0xa81f301449ee8c70, 0x5c68f256bfff5a75}, + {0xd226fc195c6a2f8c, 0x73832eec6fff3112}, + {0x83585d8fd9c25db7, 0xc831fd53c5ff7eac}, + {0xa42e74f3d032f525, 0xba3e7ca8b77f5e56}, + {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35ec}, + {0x80444b5e7aa7cf85, 0x7980d163cf5b81b4}, + {0xa0555e361951c366, 0xd7e105bcc3326220}, + {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa8}, + {0xfa856334878fc150, 0xb14f98f6f0feb952}, + {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d4}, + {0xc3b8358109e84f07, 0x0a862f80ec4700c9}, + {0xf4a642e14c6262c8, 0xcd27bb612758c0fb}, + {0x98e7e9cccfbd7dbd, 0x8038d51cb897789d}, + {0xbf21e44003acdd2c, 0xe0470a63e6bd56c4}, + {0xeeea5d5004981478, 0x1858ccfce06cac75}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc9}, + {0xbaa718e68396cffd, 0xd30560258f54e6bb}, + {0xe950df20247c83fd, 0x47c6b82ef32a206a}, + {0x91d28b7416cdd27e, 0x4cdc331d57fa5442}, + {0xb6472e511c81471d, 0xe0133fe4adf8e953}, + {0xe3d8f9e563a198e5, 0x58180fddd97723a7}, + {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7649}, + {0xb201833b35d63f73, 0x2cd2cc6551e513db}, + {0xde81e40a034bcf4f, 0xf8077f7ea65e58d2}, + {0x8b112e86420f6191, 0xfb04afaf27faf783}, + {0xadd57a27d29339f6, 0x79c5db9af1f9b564}, + {0xd94ad8b1c7380874, 0x18375281ae7822bd}, + {0x87cec76f1c830548, 0x8f2293910d0b15b6}, + {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb23}, + {0xd433179d9c8cb841, 0x5fa60692a46151ec}, + {0x849feec281d7f328, 0xdbc7c41ba6bcd334}, + {0xa5c7ea73224deff3, 0x12b9b522906c0801}, + {0xcf39e50feae16bef, 0xd768226b34870a01}, + {0x81842f29f2cce375, 0xe6a1158300d46641}, + {0xa1e53af46f801c53, 0x60495ae3c1097fd1}, + {0xca5e89b18b602368, 0x385bb19cb14bdfc5}, + {0xfcf62c1dee382c42, 0x46729e03dd9ed7b6}, + {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d2}, + {0xc5a05277621be293, 0xc7098b7305241886}, + {0xf70867153aa2db38, 0xb8cbee4fc66d1ea8}, + {0x9a65406d44a5c903, 0x737f74f1dc043329}, + {0xc0fe908895cf3b44, 0x505f522e53053ff3}, + {0xf13e34aabb430a15, 0x647726b9e7c68ff0}, + {0x96c6e0eab509e64d, 0x5eca783430dc19f6}, + {0xbc789925624c5fe0, 0xb67d16413d132073}, + {0xeb96bf6ebadf77d8, 0xe41c5bd18c57e890}, + {0x933e37a534cbaae7, 0x8e91b962f7b6f15a}, + {0xb80dc58e81fe95a1, 0x723627bbb5a4adb1}, + {0xe61136f2227e3b09, 0xcec3b1aaa30dd91d}, + {0x8fcac257558ee4e6, 0x213a4f0aa5e8a7b2}, + {0xb3bd72ed2af29e1f, 0xa988e2cd4f62d19e}, + {0xe0accfa875af45a7, 0x93eb1b80a33b8606}, + {0x8c6c01c9498d8b88, 0xbc72f130660533c4}, + {0xaf87023b9bf0ee6a, 0xeb8fad7c7f8680b5}, + {0xdb68c2ca82ed2a05, 0xa67398db9f6820e2}, +#else + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, + {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f}, + {0x86a8d39ef77164bc, 0xae5dff9c02033198}, + {0xd98ddaee19068c76, 0x3badd624dd9b0958}, + {0xafbd2350644eeacf, 0xe5d1929ef90898fb}, + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2}, + {0xe55990879ddcaabd, 0xcc420a6a101d0516}, + {0xb94470938fa89bce, 0xf808e40e8d5b3e6a}, + {0x95a8637627989aad, 0xdde7001379a44aa9}, + {0xf1c90080baf72cb1, 0x5324c68b12dd6339}, + {0xc350000000000000, 0x0000000000000000}, + {0x9dc5ada82b70b59d, 0xf020000000000000}, + {0xfee50b7025c36a08, 0x02f236d04753d5b5}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87}, + {0xa6539930bf6bff45, 0x84db8346b786151d}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3}, + {0xd910f7ff28069da4, 0x1b2ba1518094da05}, + {0xaf58416654a6babb, 0x387ac8d1970027b3}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d3}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334b}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936244}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc9}, + {0xf13e34aabb430a15, 0x647726b9e7c68ff0} +#endif + }; + +#if FMT_USE_FULL_CACHE_DRAGONBOX + return pow10_significands[k - float_info::min_k]; +#else + static constexpr uint64_t powers_of_5_64[] = { + 0x0000000000000001, 0x0000000000000005, 0x0000000000000019, + 0x000000000000007d, 0x0000000000000271, 0x0000000000000c35, + 0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1, + 0x00000000001dcd65, 0x00000000009502f9, 0x0000000002e90edd, + 0x000000000e8d4a51, 0x0000000048c27395, 0x000000016bcc41e9, + 0x000000071afd498d, 0x0000002386f26fc1, 0x000000b1a2bc2ec5, + 0x000003782dace9d9, 0x00001158e460913d, 0x000056bc75e2d631, + 0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed, + 0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9}; + + static const int compression_ratio = 27; + + // Compute base index. + int cache_index = (k - float_info::min_k) / compression_ratio; + int kb = cache_index * compression_ratio + float_info::min_k; + int offset = k - kb; + + // Get base cache. + uint128_fallback base_cache = pow10_significands[cache_index]; + if (offset == 0) return base_cache; + + // Compute the required amount of bit-shift. + int alpha = floor_log2_pow10(kb + offset) - floor_log2_pow10(kb) - offset; + FMT_ASSERT(alpha > 0 && alpha < 64, "shifting error detected"); + + // Try to recover the real cache. + uint64_t pow5 = powers_of_5_64[offset]; + uint128_fallback recovered_cache = umul128(base_cache.high(), pow5); + uint128_fallback middle_low = umul128(base_cache.low(), pow5); + + recovered_cache += middle_low.high(); + + uint64_t high_to_middle = recovered_cache.high() << (64 - alpha); + uint64_t middle_to_low = recovered_cache.low() << (64 - alpha); + + recovered_cache = + uint128_fallback{(recovered_cache.low() >> alpha) | high_to_middle, + ((middle_low.low() >> alpha) | middle_to_low)}; + FMT_ASSERT(recovered_cache.low() + 1 != 0, ""); + return {recovered_cache.high(), recovered_cache.low() + 1}; +#endif + } + + struct compute_mul_result { + carrier_uint result; + bool is_integer; + }; + struct compute_mul_parity_result { + bool parity; + bool is_integer; + }; + + static auto compute_mul(carrier_uint u, + const cache_entry_type& cache) noexcept + -> compute_mul_result { + auto r = umul192_upper128(u, cache); + return {r.high(), r.low() == 0}; + } + + static auto compute_delta(const cache_entry_type& cache, int beta) noexcept + -> uint32_t { + return static_cast(cache.high() >> (64 - 1 - beta)); + } + + static auto compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta) noexcept + -> compute_mul_parity_result { + FMT_ASSERT(beta >= 1, ""); + FMT_ASSERT(beta < 64, ""); + + auto r = umul192_lower128(two_f, cache); + return {((r.high() >> (64 - beta)) & 1) != 0, + ((r.high() << beta) | (r.low() >> (64 - beta))) == 0}; + } + + static auto compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (cache.high() - + (cache.high() >> (num_significand_bits() + 2))) >> + (64 - num_significand_bits() - 1 - beta); + } + + static auto compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (cache.high() + + (cache.high() >> (num_significand_bits() + 1))) >> + (64 - num_significand_bits() - 1 - beta); + } + + static auto compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return ((cache.high() >> (64 - num_significand_bits() - 2 - beta)) + + 1) / + 2; + } +}; + +FMT_FUNC auto get_cached_power(int k) noexcept -> uint128_fallback { + return cache_accessor::get_cached_power(k); +} + +// Various integer checks +template +auto is_left_endpoint_integer_shorter_interval(int exponent) noexcept -> bool { + const int case_shorter_interval_left_endpoint_lower_threshold = 2; + const int case_shorter_interval_left_endpoint_upper_threshold = 3; + return exponent >= case_shorter_interval_left_endpoint_lower_threshold && + exponent <= case_shorter_interval_left_endpoint_upper_threshold; +} + +// Remove trailing zeros from n and return the number of zeros removed (float). +FMT_INLINE auto remove_trailing_zeros(uint32_t& n, int s = 0) noexcept -> int { + FMT_ASSERT(n != 0, ""); + // Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1. + constexpr uint32_t mod_inv_5 = 0xcccccccd; + constexpr uint32_t mod_inv_25 = 0xc28f5c29; // = mod_inv_5 * mod_inv_5 + + while (true) { + auto q = rotr(n * mod_inv_25, 2); + if (q > max_value() / 100) break; + n = q; + s += 2; + } + auto q = rotr(n * mod_inv_5, 1); + if (q <= max_value() / 10) { + n = q; + s |= 1; + } + return s; +} + +// Removes trailing zeros and returns the number of zeros removed (double). +FMT_INLINE auto remove_trailing_zeros(uint64_t& n) noexcept -> int { + FMT_ASSERT(n != 0, ""); + + // Is n is divisible by 10^8? + constexpr uint32_t ten_pow_8 = 100000000u; + if ((n % ten_pow_8) == 0) { + // If yes, work with the quotient... + auto n32 = static_cast(n / ten_pow_8); + // ... and use the 32 bit variant of the function + int num_zeros = remove_trailing_zeros(n32, 8); + n = n32; + return num_zeros; + } + + // If n is not divisible by 10^8, work with n itself. + constexpr uint64_t mod_inv_5 = 0xcccccccccccccccd; + constexpr uint64_t mod_inv_25 = 0x8f5c28f5c28f5c29; // mod_inv_5 * mod_inv_5 + + int s = 0; + while (true) { + auto q = rotr(n * mod_inv_25, 2); + if (q > max_value() / 100) break; + n = q; + s += 2; + } + auto q = rotr(n * mod_inv_5, 1); + if (q <= max_value() / 10) { + n = q; + s |= 1; + } + + return s; +} + +// The main algorithm for shorter interval case +template +FMT_INLINE auto shorter_interval_case(int exponent) noexcept -> decimal_fp { + decimal_fp ret_value; + // Compute k and beta + const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent); + const int beta = exponent + floor_log2_pow10(-minus_k); + + // Compute xi and zi + using cache_entry_type = typename cache_accessor::cache_entry_type; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + + auto xi = cache_accessor::compute_left_endpoint_for_shorter_interval_case( + cache, beta); + auto zi = cache_accessor::compute_right_endpoint_for_shorter_interval_case( + cache, beta); + + // If the left endpoint is not an integer, increase it + if (!is_left_endpoint_integer_shorter_interval(exponent)) ++xi; + + // Try bigger divisor + ret_value.significand = zi / 10; + + // If succeed, remove trailing zeros if necessary and return + if (ret_value.significand * 10 >= xi) { + ret_value.exponent = minus_k + 1; + ret_value.exponent += remove_trailing_zeros(ret_value.significand); + return ret_value; + } + + // Otherwise, compute the round-up of y + ret_value.significand = + cache_accessor::compute_round_up_for_shorter_interval_case(cache, + beta); + ret_value.exponent = minus_k; + + // When tie occurs, choose one of them according to the rule + if (exponent >= float_info::shorter_interval_tie_lower_threshold && + exponent <= float_info::shorter_interval_tie_upper_threshold) { + ret_value.significand = ret_value.significand % 2 == 0 + ? ret_value.significand + : ret_value.significand - 1; + } else if (ret_value.significand < xi) { + ++ret_value.significand; + } + return ret_value; +} + +template auto to_decimal(T x) noexcept -> decimal_fp { + // Step 1: integer promotion & Schubfach multiplier calculation. + + using carrier_uint = typename float_info::carrier_uint; + using cache_entry_type = typename cache_accessor::cache_entry_type; + auto br = bit_cast(x); + + // Extract significand bits and exponent bits. + const carrier_uint significand_mask = + (static_cast(1) << num_significand_bits()) - 1; + carrier_uint significand = (br & significand_mask); + int exponent = + static_cast((br & exponent_mask()) >> num_significand_bits()); + + if (exponent != 0) { // Check if normal. + exponent -= exponent_bias() + num_significand_bits(); + + // Shorter interval case; proceed like Schubfach. + // In fact, when exponent == 1 and significand == 0, the interval is + // regular. However, it can be shown that the end-results are anyway same. + if (significand == 0) return shorter_interval_case(exponent); + + significand |= (static_cast(1) << num_significand_bits()); + } else { + // Subnormal case; the interval is always regular. + if (significand == 0) return {0, 0}; + exponent = + std::numeric_limits::min_exponent - num_significand_bits() - 1; + } + + const bool include_left_endpoint = (significand % 2 == 0); + const bool include_right_endpoint = include_left_endpoint; + + // Compute k and beta. + const int minus_k = floor_log10_pow2(exponent) - float_info::kappa; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + const int beta = exponent + floor_log2_pow10(-minus_k); + + // Compute zi and deltai. + // 10^kappa <= deltai < 10^(kappa + 1) + const uint32_t deltai = cache_accessor::compute_delta(cache, beta); + const carrier_uint two_fc = significand << 1; + + // For the case of binary32, the result of integer check is not correct for + // 29711844 * 2^-82 + // = 6.1442653300000000008655037797566933477355632930994033813476... * 10^-18 + // and 29711844 * 2^-81 + // = 1.2288530660000000001731007559513386695471126586198806762695... * 10^-17, + // and they are the unique counterexamples. However, since 29711844 is even, + // this does not cause any problem for the endpoints calculations; it can only + // cause a problem when we need to perform integer check for the center. + // Fortunately, with these inputs, that branch is never executed, so we are + // fine. + const typename cache_accessor::compute_mul_result z_mul = + cache_accessor::compute_mul((two_fc | 1) << beta, cache); + + // Step 2: Try larger divisor; remove trailing zeros if necessary. + + // Using an upper bound on zi, we might be able to optimize the division + // better than the compiler; we are computing zi / big_divisor here. + decimal_fp ret_value; + ret_value.significand = divide_by_10_to_kappa_plus_1(z_mul.result); + uint32_t r = static_cast(z_mul.result - float_info::big_divisor * + ret_value.significand); + + if (r < deltai) { + // Exclude the right endpoint if necessary. + if (r == 0 && (z_mul.is_integer & !include_right_endpoint)) { + --ret_value.significand; + r = float_info::big_divisor; + goto small_divisor_case_label; + } + } else if (r > deltai) { + goto small_divisor_case_label; + } else { + // r == deltai; compare fractional parts. + const typename cache_accessor::compute_mul_parity_result x_mul = + cache_accessor::compute_mul_parity(two_fc - 1, cache, beta); + + if (!(x_mul.parity | (x_mul.is_integer & include_left_endpoint))) + goto small_divisor_case_label; + } + ret_value.exponent = minus_k + float_info::kappa + 1; + + // We may need to remove trailing zeros. + ret_value.exponent += remove_trailing_zeros(ret_value.significand); + return ret_value; + + // Step 3: Find the significand with the smaller divisor. + +small_divisor_case_label: + ret_value.significand *= 10; + ret_value.exponent = minus_k + float_info::kappa; + + uint32_t dist = r - (deltai / 2) + (float_info::small_divisor / 2); + const bool approx_y_parity = + ((dist ^ (float_info::small_divisor / 2)) & 1) != 0; + + // Is dist divisible by 10^kappa? + const bool divisible_by_small_divisor = + check_divisibility_and_divide_by_pow10::kappa>(dist); + + // Add dist / 10^kappa to the significand. + ret_value.significand += dist; + + if (!divisible_by_small_divisor) return ret_value; + + // Check z^(f) >= epsilon^(f). + // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1, + // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f). + // Since there are only 2 possibilities, we only need to care about the + // parity. Also, zi and r should have the same parity since the divisor + // is an even number. + const auto y_mul = cache_accessor::compute_mul_parity(two_fc, cache, beta); + + // If z^(f) >= epsilon^(f), we might have a tie when z^(f) == epsilon^(f), + // or equivalently, when y is an integer. + if (y_mul.parity != approx_y_parity) + --ret_value.significand; + else if (y_mul.is_integer & (ret_value.significand % 2 != 0)) + --ret_value.significand; + return ret_value; +} +} // namespace dragonbox +} // namespace detail + +template <> struct formatter { + FMT_CONSTEXPR auto parse(format_parse_context& ctx) + -> format_parse_context::iterator { + return ctx.begin(); + } + + auto format(const detail::bigint& n, format_context& ctx) const + -> format_context::iterator { + auto out = ctx.out(); + bool first = true; + for (auto i = n.bigits_.size(); i > 0; --i) { + auto value = n.bigits_[i - 1u]; + if (first) { + out = fmt::format_to(out, FMT_STRING("{:x}"), value); + first = false; + continue; + } + out = fmt::format_to(out, FMT_STRING("{:08x}"), value); + } + if (n.exp_ > 0) + out = fmt::format_to(out, FMT_STRING("p{}"), + n.exp_ * detail::bigint::bigit_bits); + return out; + } +}; + +FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) { + for_each_codepoint(s, [this](uint32_t cp, string_view) { + if (cp == invalid_code_point) FMT_THROW(std::runtime_error("invalid utf8")); + if (cp <= 0xFFFF) { + buffer_.push_back(static_cast(cp)); + } else { + cp -= 0x10000; + buffer_.push_back(static_cast(0xD800 + (cp >> 10))); + buffer_.push_back(static_cast(0xDC00 + (cp & 0x3FF))); + } + return true; + }); + buffer_.push_back(0); +} + +FMT_FUNC void format_system_error(detail::buffer& out, int error_code, + const char* message) noexcept { + FMT_TRY { + auto ec = std::error_code(error_code, std::generic_category()); + detail::write(appender(out), std::system_error(ec, message).what()); + return; + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +FMT_FUNC void report_system_error(int error_code, + const char* message) noexcept { + do_report_error(format_system_error, error_code, message); +} + +FMT_FUNC auto vformat(string_view fmt, format_args args) -> std::string { + // Don't optimize the "{}" case to keep the binary size small and because it + // can be better optimized in fmt::format anyway. + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + return to_string(buffer); +} + +namespace detail { + +FMT_FUNC void vformat_to(buffer& buf, string_view fmt, format_args args, + locale_ref loc) { + auto out = appender(buf); + if (fmt.size() == 2 && equal2(fmt.data(), "{}")) + return args.get(0).visit(default_arg_formatter{out}); + parse_format_string(fmt, + format_handler<>{parse_context<>(fmt), {out, args, loc}}); +} + +template struct span { + T* data; + size_t size; +}; + +template auto flockfile(F* f) -> decltype(_lock_file(f)) { + _lock_file(f); +} +template auto funlockfile(F* f) -> decltype(_unlock_file(f)) { + _unlock_file(f); +} + +#ifndef getc_unlocked +template auto getc_unlocked(F* f) -> decltype(_fgetc_nolock(f)) { + return _fgetc_nolock(f); +} +#endif + +template +struct has_flockfile : std::false_type {}; + +template +struct has_flockfile()))>> + : std::true_type {}; + +// A FILE wrapper. F is FILE defined as a template parameter to make system API +// detection work. +template class file_base { + public: + F* file_; + + public: + file_base(F* file) : file_(file) {} + operator F*() const { return file_; } + + // Reads a code unit from the stream. + auto get() -> int { + int result = getc_unlocked(file_); + if (result == EOF && ferror(file_) != 0) + FMT_THROW(system_error(errno, FMT_STRING("getc failed"))); + return result; + } + + // Puts the code unit back into the stream buffer. + void unget(char c) { + if (ungetc(c, file_) == EOF) + FMT_THROW(system_error(errno, FMT_STRING("ungetc failed"))); + } + + void flush() { fflush(this->file_); } +}; + +// A FILE wrapper for glibc. +template class glibc_file : public file_base { + private: + enum { + line_buffered = 0x200, // _IO_LINE_BUF + unbuffered = 2 // _IO_UNBUFFERED + }; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { + return (this->file_->_flags & unbuffered) == 0; + } + + void init_buffer() { + if (this->file_->_IO_write_ptr < this->file_->_IO_write_end) return; + // Force buffer initialization by placing and removing a char in a buffer. + putc_unlocked(0, this->file_); + --this->file_->_IO_write_ptr; + } + + // Returns the file's read buffer. + auto get_read_buffer() const -> span { + auto ptr = this->file_->_IO_read_ptr; + return {ptr, to_unsigned(this->file_->_IO_read_end - ptr)}; + } + + // Returns the file's write buffer. + auto get_write_buffer() const -> span { + auto ptr = this->file_->_IO_write_ptr; + return {ptr, to_unsigned(this->file_->_IO_buf_end - ptr)}; + } + + void advance_write_buffer(size_t size) { this->file_->_IO_write_ptr += size; } + + auto needs_flush() const -> bool { + if ((this->file_->_flags & line_buffered) == 0) return false; + char* end = this->file_->_IO_write_end; + auto size = max_of(this->file_->_IO_write_ptr - end, 0); + return memchr(end, '\n', static_cast(size)); + } + + void flush() { fflush_unlocked(this->file_); } +}; + +// A FILE wrapper for Apple's libc. +template class apple_file : public file_base { + private: + enum { + line_buffered = 1, // __SNBF + unbuffered = 2 // __SLBF + }; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { + return (this->file_->_flags & unbuffered) == 0; + } + + void init_buffer() { + if (this->file_->_p) return; + // Force buffer initialization by placing and removing a char in a buffer. + if (!FMT_CLANG_ANALYZER) putc_unlocked(0, this->file_); + --this->file_->_p; + ++this->file_->_w; + } + + auto get_read_buffer() const -> span { + return {reinterpret_cast(this->file_->_p), + to_unsigned(this->file_->_r)}; + } + + auto get_write_buffer() const -> span { + return {reinterpret_cast(this->file_->_p), + to_unsigned(this->file_->_bf._base + this->file_->_bf._size - + this->file_->_p)}; + } + + void advance_write_buffer(size_t size) { + this->file_->_p += size; + this->file_->_w -= size; + } + + auto needs_flush() const -> bool { + if ((this->file_->_flags & line_buffered) == 0) return false; + return memchr(this->file_->_p + this->file_->_w, '\n', + to_unsigned(-this->file_->_w)); + } +}; + +// A fallback FILE wrapper. +template class fallback_file : public file_base { + private: + char next_; // The next unconsumed character in the buffer. + bool has_next_ = false; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { return false; } + auto needs_flush() const -> bool { return false; } + void init_buffer() {} + + auto get_read_buffer() const -> span { + return {&next_, has_next_ ? 1u : 0u}; + } + + auto get_write_buffer() const -> span { return {nullptr, 0}; } + + void advance_write_buffer(size_t) {} + + auto get() -> int { + has_next_ = false; + return file_base::get(); + } + + void unget(char c) { + file_base::unget(c); + next_ = c; + has_next_ = true; + } +}; + +#ifndef FMT_USE_FALLBACK_FILE +# define FMT_USE_FALLBACK_FILE 0 +#endif + +template +auto get_file(F* f, int) -> apple_file { + return f; +} +template +inline auto get_file(F* f, int) -> glibc_file { + return f; +} + +inline auto get_file(FILE* f, ...) -> fallback_file { return f; } + +using file_ref = decltype(get_file(static_cast(nullptr), 0)); + +template +class file_print_buffer : public buffer { + public: + explicit file_print_buffer(F*) : buffer(nullptr, size_t()) {} +}; + +template +class file_print_buffer::value>> + : public buffer { + private: + file_ref file_; + + static void grow(buffer& base, size_t) { + auto& self = static_cast(base); + self.file_.advance_write_buffer(self.size()); + if (self.file_.get_write_buffer().size == 0) self.file_.flush(); + auto buf = self.file_.get_write_buffer(); + FMT_ASSERT(buf.size > 0, ""); + self.set(buf.data, buf.size); + self.clear(); + } + + public: + explicit file_print_buffer(F* f) : buffer(grow, size_t()), file_(f) { + flockfile(f); + file_.init_buffer(); + auto buf = file_.get_write_buffer(); + set(buf.data, buf.size); + } + ~file_print_buffer() { + file_.advance_write_buffer(size()); + bool flush = file_.needs_flush(); + F* f = file_; // Make funlockfile depend on the template parameter F + funlockfile(f); // for the system API detection to work. + if (flush) fflush(file_); + } +}; + +#if !defined(_WIN32) || defined(FMT_USE_WRITE_CONSOLE) +FMT_FUNC auto write_console(int, string_view) -> bool { return false; } +#else +using dword = conditional_t; +extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( // + void*, const void*, dword, dword*, void*); + +FMT_FUNC bool write_console(int fd, string_view text) { + auto u16 = utf8_to_utf16(text); + return WriteConsoleW(reinterpret_cast(_get_osfhandle(fd)), u16.c_str(), + static_cast(u16.size()), nullptr, nullptr) != 0; +} +#endif + +#ifdef _WIN32 +// Print assuming legacy (non-Unicode) encoding. +FMT_FUNC void vprint_mojibake(std::FILE* f, string_view fmt, format_args args, + bool newline) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + if (newline) buffer.push_back('\n'); + fwrite_all(buffer.data(), buffer.size(), f); +} +#endif + +FMT_FUNC void print(std::FILE* f, string_view text) { +#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) + int fd = _fileno(f); + if (_isatty(fd)) { + std::fflush(f); + if (write_console(fd, text)) return; + } +#endif + fwrite_all(text.data(), text.size(), f); +} +} // namespace detail + +FMT_FUNC void vprint_buffered(std::FILE* f, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + detail::print(f, {buffer.data(), buffer.size()}); +} + +FMT_FUNC void vprint(std::FILE* f, string_view fmt, format_args args) { + if (!detail::file_ref(f).is_buffered() || !detail::has_flockfile<>()) + return vprint_buffered(f, fmt, args); + auto&& buffer = detail::file_print_buffer<>(f); + return detail::vformat_to(buffer, fmt, args); +} + +FMT_FUNC void vprintln(std::FILE* f, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + buffer.push_back('\n'); + detail::print(f, {buffer.data(), buffer.size()}); +} + +FMT_FUNC void vprint(string_view fmt, format_args args) { + vprint(stdout, fmt, args); +} + +namespace detail { + +struct singleton { + unsigned char upper; + unsigned char lower_count; +}; + +inline auto is_printable(uint16_t x, const singleton* singletons, + size_t singletons_size, + const unsigned char* singleton_lowers, + const unsigned char* normal, size_t normal_size) + -> bool { + auto upper = x >> 8; + auto lower_start = 0; + for (size_t i = 0; i < singletons_size; ++i) { + auto s = singletons[i]; + auto lower_end = lower_start + s.lower_count; + if (upper < s.upper) break; + if (upper == s.upper) { + for (auto j = lower_start; j < lower_end; ++j) { + if (singleton_lowers[j] == (x & 0xff)) return false; + } + } + lower_start = lower_end; + } + + auto xsigned = static_cast(x); + auto current = true; + for (size_t i = 0; i < normal_size; ++i) { + auto v = static_cast(normal[i]); + auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v; + xsigned -= len; + if (xsigned < 0) break; + current = !current; + } + return current; +} + +// This code is generated by support/printable.py. +FMT_FUNC auto is_printable(uint32_t cp) -> bool { + static constexpr singleton singletons0[] = { + {0x00, 1}, {0x03, 5}, {0x05, 6}, {0x06, 3}, {0x07, 6}, {0x08, 8}, + {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13}, + {0x0f, 4}, {0x10, 3}, {0x12, 18}, {0x13, 9}, {0x16, 1}, {0x17, 5}, + {0x18, 2}, {0x19, 3}, {0x1a, 7}, {0x1c, 2}, {0x1d, 1}, {0x1f, 22}, + {0x20, 3}, {0x2b, 3}, {0x2c, 2}, {0x2d, 11}, {0x2e, 1}, {0x30, 3}, + {0x31, 2}, {0x32, 1}, {0xa7, 2}, {0xa9, 2}, {0xaa, 4}, {0xab, 8}, + {0xfa, 2}, {0xfb, 5}, {0xfd, 4}, {0xfe, 3}, {0xff, 9}, + }; + static constexpr unsigned char singletons0_lower[] = { + 0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90, + 0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f, + 0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1, + 0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04, + 0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d, + 0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf, + 0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a, + 0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d, + 0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d, + 0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d, + 0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5, + 0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7, + 0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49, + 0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7, + 0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7, + 0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e, + 0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16, + 0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e, + 0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f, + 0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf, + 0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0, + 0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27, + 0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91, + 0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7, + 0xfe, 0xff, + }; + static constexpr singleton singletons1[] = { + {0x00, 6}, {0x01, 1}, {0x03, 1}, {0x04, 2}, {0x08, 8}, {0x09, 2}, + {0x0a, 5}, {0x0b, 2}, {0x0e, 4}, {0x10, 1}, {0x11, 2}, {0x12, 5}, + {0x13, 17}, {0x14, 1}, {0x15, 2}, {0x17, 2}, {0x19, 13}, {0x1c, 5}, + {0x1d, 8}, {0x24, 1}, {0x6a, 3}, {0x6b, 2}, {0xbc, 2}, {0xd1, 2}, + {0xd4, 12}, {0xd5, 9}, {0xd6, 2}, {0xd7, 2}, {0xda, 1}, {0xe0, 5}, + {0xe1, 2}, {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2}, {0xf9, 2}, + {0xfa, 2}, {0xfb, 1}, + }; + static constexpr unsigned char singletons1_lower[] = { + 0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07, + 0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36, + 0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87, + 0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a, + 0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b, + 0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9, + 0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66, + 0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27, + 0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc, + 0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7, + 0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6, + 0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c, + 0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66, + 0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0, + 0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93, + }; + static constexpr unsigned char normal0[] = { + 0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04, + 0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0, + 0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01, + 0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03, + 0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03, + 0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a, + 0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15, + 0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f, + 0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80, + 0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07, + 0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06, + 0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04, + 0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac, + 0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c, + 0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11, + 0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c, + 0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b, + 0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6, + 0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03, + 0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80, + 0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06, + 0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c, + 0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17, + 0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80, + 0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80, + 0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d, + }; + static constexpr unsigned char normal1[] = { + 0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f, + 0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e, + 0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04, + 0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09, + 0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16, + 0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f, + 0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36, + 0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33, + 0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08, + 0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e, + 0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41, + 0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03, + 0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22, + 0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04, + 0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45, + 0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03, + 0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81, + 0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75, + 0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1, + 0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a, + 0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11, + 0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09, + 0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89, + 0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6, + 0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09, + 0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50, + 0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05, + 0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83, + 0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05, + 0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80, + 0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80, + 0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07, + 0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e, + 0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07, + 0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06, + }; + auto lower = static_cast(cp); + if (cp < 0x10000) { + return is_printable(lower, singletons0, + sizeof(singletons0) / sizeof(*singletons0), + singletons0_lower, normal0, sizeof(normal0)); + } + if (cp < 0x20000) { + return is_printable(lower, singletons1, + sizeof(singletons1) / sizeof(*singletons1), + singletons1_lower, normal1, sizeof(normal1)); + } + if (0x2a6de <= cp && cp < 0x2a700) return false; + if (0x2b735 <= cp && cp < 0x2b740) return false; + if (0x2b81e <= cp && cp < 0x2b820) return false; + if (0x2cea2 <= cp && cp < 0x2ceb0) return false; + if (0x2ebe1 <= cp && cp < 0x2f800) return false; + if (0x2fa1e <= cp && cp < 0x30000) return false; + if (0x3134b <= cp && cp < 0xe0100) return false; + if (0xe01f0 <= cp && cp < 0x110000) return false; + return cp < 0x110000; +} + +} // namespace detail + +FMT_END_NAMESPACE + +#endif // FMT_FORMAT_INL_H_ diff --git a/vendor/btop/include/fmt/format.h b/vendor/btop/include/fmt/format.h new file mode 100644 index 000000000..c3a1bda09 --- /dev/null +++ b/vendor/btop/include/fmt/format.h @@ -0,0 +1,4383 @@ +/* + Formatting library for C++ + + Copyright (c) 2012 - present, Victor Zverovich + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + --- Optional exception to the license --- + + As an exception, if, as a result of your compiling your source code, portions + of this Software are embedded into a machine-executable object form of such + source code, you may redistribute such embedded portions in such object form + without including the above copyright and permission notices. + */ + +#ifndef FMT_FORMAT_H_ +#define FMT_FORMAT_H_ + +#ifndef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +# define _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +# define FMT_REMOVE_TRANSITIVE_INCLUDES +#endif + +#include "base.h" + +#ifndef FMT_MODULE +# include // std::signbit +# include // std::byte +# include // uint32_t +# include // std::malloc, std::free +# include // std::memcpy +# include // std::numeric_limits +# include // std::bad_alloc +# if defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI) +// Workaround for pre gcc 5 libstdc++. +# include // std::allocator_traits +# endif +# include // std::runtime_error +# include // std::string +# include // std::system_error + +// Check FMT_CPLUSPLUS to avoid a warning in MSVC. +# if FMT_HAS_INCLUDE() && FMT_CPLUSPLUS > 201703L +# include // std::bit_cast +# endif + +// libc++ supports string_view in pre-c++17. +# if FMT_HAS_INCLUDE() && \ + (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION)) +# include +# define FMT_USE_STRING_VIEW +# endif + +# if FMT_MSC_VERSION +# include // _BitScanReverse[64], _umul128 +# endif +#endif // FMT_MODULE + +#if defined(FMT_USE_NONTYPE_TEMPLATE_ARGS) +// Use the provided definition. +#elif defined(__NVCOMPILER) +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 +#elif FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#elif defined(__cpp_nontype_template_args) && \ + __cpp_nontype_template_args >= 201911L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#elif FMT_CLANG_VERSION >= 1200 && FMT_CPLUSPLUS >= 202002L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#else +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 +#endif + +#if defined __cpp_inline_variables && __cpp_inline_variables >= 201606L +# define FMT_INLINE_VARIABLE inline +#else +# define FMT_INLINE_VARIABLE +#endif + +// Check if RTTI is disabled. +#ifdef FMT_USE_RTTI +// Use the provided definition. +#elif defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || defined(_CPPRTTI) || \ + defined(__INTEL_RTTI__) || defined(__RTTI) +// __RTTI is for EDG compilers. _CPPRTTI is for MSVC. +# define FMT_USE_RTTI 1 +#else +# define FMT_USE_RTTI 0 +#endif + +// Visibility when compiled as a shared library/object. +#if defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) +# define FMT_SO_VISIBILITY(value) FMT_VISIBILITY(value) +#else +# define FMT_SO_VISIBILITY(value) +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_NOINLINE __attribute__((noinline)) +#else +# define FMT_NOINLINE +#endif + +#ifdef FMT_DEPRECATED +// Use the provided definition. +#elif FMT_HAS_CPP14_ATTRIBUTE(deprecated) +# define FMT_DEPRECATED [[deprecated]] +#else +# define FMT_DEPRECATED /* deprecated */ +#endif + +// Detect constexpr std::string. +#if !FMT_USE_CONSTEVAL +# define FMT_USE_CONSTEXPR_STRING 0 +#elif defined(__cpp_lib_constexpr_string) && \ + __cpp_lib_constexpr_string >= 201907L +# if FMT_CLANG_VERSION && FMT_GLIBCXX_RELEASE +// clang + libstdc++ are able to work only starting with gcc13.3 +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113294 +# if FMT_GLIBCXX_RELEASE < 13 +# define FMT_USE_CONSTEXPR_STRING 0 +# elif FMT_GLIBCXX_RELEASE == 13 && __GLIBCXX__ < 20240521 +# define FMT_USE_CONSTEXPR_STRING 0 +# else +# define FMT_USE_CONSTEXPR_STRING 1 +# endif +# else +# define FMT_USE_CONSTEXPR_STRING 1 +# endif +#else +# define FMT_USE_CONSTEXPR_STRING 0 +#endif +#if FMT_USE_CONSTEXPR_STRING +# define FMT_CONSTEXPR_STRING constexpr +#else +# define FMT_CONSTEXPR_STRING +#endif + +// GCC 4.9 doesn't support qualified names in specializations. +namespace std { +template struct iterator_traits> { + using iterator_category = output_iterator_tag; + using value_type = T; + using difference_type = + decltype(static_cast(nullptr) - static_cast(nullptr)); + using pointer = void; + using reference = void; +}; +} // namespace std + +#ifdef FMT_THROW +// Use the provided definition. +#elif FMT_USE_EXCEPTIONS +# define FMT_THROW(x) throw x +#else +# define FMT_THROW(x) ::fmt::assert_fail(__FILE__, __LINE__, (x).what()) +#endif + +#ifdef __clang_analyzer__ +# define FMT_CLANG_ANALYZER 1 +#else +# define FMT_CLANG_ANALYZER 0 +#endif + +// Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of +// integer formatter template instantiations to just one by only using the +// largest integer type. This results in a reduction in binary size but will +// cause a decrease in integer formatting performance. +#if !defined(FMT_REDUCE_INT_INSTANTIATIONS) +# define FMT_REDUCE_INT_INSTANTIATIONS 0 +#endif + +FMT_BEGIN_NAMESPACE + +template +struct is_contiguous> + : std::true_type {}; + +namespace detail { + +// __builtin_clz is broken in clang with Microsoft codegen: +// https://github.com/fmtlib/fmt/issues/519. +#if !FMT_MSC_VERSION +# if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION +# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +# endif +# if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION +# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +# endif +#endif + +// Some compilers masquerade as both MSVC and GCC but otherwise support +// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the +// MSVC intrinsics if the clz and clzll builtins are not available. +#if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) +// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. +# ifndef __clang__ +# pragma intrinsic(_BitScanReverse) +# ifdef _WIN64 +# pragma intrinsic(_BitScanReverse64) +# endif +# endif + +inline auto clz(uint32_t x) -> int { + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. + unsigned long r = 0; + _BitScanReverse(&r, x); + return 31 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZ(n) detail::clz(n) + +inline auto clzll(uint64_t x) -> int { + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. + unsigned long r = 0; +# ifdef _WIN64 + _BitScanReverse64(&r, x); +# else + // Scan the high 32 bits. + if (_BitScanReverse(&r, static_cast(x >> 32))) + return 63 ^ static_cast(r + 32); + // Scan the low 32 bits. + _BitScanReverse(&r, static_cast(x)); +# endif + return 63 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZLL(n) detail::clzll(n) +#endif // FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) + +FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) { + ignore_unused(condition); +#ifdef FMT_FUZZ + if (condition) throw std::runtime_error("fuzzing limit reached"); +#endif +} + +#if defined(FMT_USE_STRING_VIEW) +template using std_string_view = std::basic_string_view; +#else +template struct std_string_view { + operator basic_string_view() const; +}; +#endif + +template struct string_literal { + static constexpr Char value[sizeof...(C)] = {C...}; + constexpr operator basic_string_view() const { + return {value, sizeof...(C)}; + } +}; +#if FMT_CPLUSPLUS < 201703L +template +constexpr Char string_literal::value[sizeof...(C)]; +#endif + +// Implementation of std::bit_cast for pre-C++20. +template +FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To { +#ifdef __cpp_lib_bit_cast + if (is_constant_evaluated()) return std::bit_cast(from); +#endif + auto to = To(); + // The cast suppresses a bogus -Wclass-memaccess on GCC. + std::memcpy(static_cast(&to), &from, sizeof(to)); + return to; +} + +inline auto is_big_endian() -> bool { +#ifdef _WIN32 + return false; +#elif defined(__BIG_ENDIAN__) + return true; +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) + return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__; +#else + struct bytes { + char data[sizeof(int)]; + }; + return bit_cast(1).data[0] == 0; +#endif +} + +class uint128_fallback { + private: + uint64_t lo_, hi_; + + public: + constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {} + constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {} + + constexpr auto high() const noexcept -> uint64_t { return hi_; } + constexpr auto low() const noexcept -> uint64_t { return lo_; } + + template ::value)> + constexpr explicit operator T() const { + return static_cast(lo_); + } + + friend constexpr auto operator==(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_; + } + friend constexpr auto operator!=(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return !(lhs == rhs); + } + friend constexpr auto operator>(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_; + } + friend constexpr auto operator|(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_}; + } + friend constexpr auto operator&(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_}; + } + friend constexpr auto operator~(const uint128_fallback& n) + -> uint128_fallback { + return {~n.hi_, ~n.lo_}; + } + friend FMT_CONSTEXPR auto operator+(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + auto result = uint128_fallback(lhs); + result += rhs; + return result; + } + friend FMT_CONSTEXPR auto operator*(const uint128_fallback& lhs, uint32_t rhs) + -> uint128_fallback { + FMT_ASSERT(lhs.hi_ == 0, ""); + uint64_t hi = (lhs.lo_ >> 32) * rhs; + uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs; + uint64_t new_lo = (hi << 32) + lo; + return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo}; + } + friend constexpr auto operator-(const uint128_fallback& lhs, uint64_t rhs) + -> uint128_fallback { + return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs}; + } + FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback { + if (shift == 64) return {0, hi_}; + if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64); + return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)}; + } + FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback { + if (shift == 64) return {lo_, 0}; + if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64); + return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)}; + } + FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& { + return *this = *this >> shift; + } + FMT_CONSTEXPR void operator+=(uint128_fallback n) { + uint64_t new_lo = lo_ + n.lo_; + uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0); + FMT_ASSERT(new_hi >= hi_, ""); + lo_ = new_lo; + hi_ = new_hi; + } + FMT_CONSTEXPR void operator&=(uint128_fallback n) { + lo_ &= n.lo_; + hi_ &= n.hi_; + } + + FMT_CONSTEXPR20 auto operator+=(uint64_t n) noexcept -> uint128_fallback& { + if (is_constant_evaluated()) { + lo_ += n; + hi_ += (lo_ < n ? 1 : 0); + return *this; + } +#if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__) + unsigned long long carry; + lo_ = __builtin_addcll(lo_, n, 0, &carry); + hi_ += carry; +#elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__) + unsigned long long result; + auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result); + lo_ = result; + hi_ += carry; +#elif defined(_MSC_VER) && defined(_M_X64) + auto carry = _addcarry_u64(0, lo_, n, &lo_); + _addcarry_u64(carry, hi_, 0, &hi_); +#else + lo_ += n; + hi_ += (lo_ < n ? 1 : 0); +#endif + return *this; + } +}; + +using uint128_t = conditional_t; + +#ifdef UINTPTR_MAX +using uintptr_t = ::uintptr_t; +#else +using uintptr_t = uint128_t; +#endif + +// Returns the largest possible value for type T. Same as +// std::numeric_limits::max() but shorter and not affected by the max macro. +template constexpr auto max_value() -> T { + return (std::numeric_limits::max)(); +} +template constexpr auto num_bits() -> int { + return std::numeric_limits::digits; +} +// std::numeric_limits::digits may return 0 for 128-bit ints. +template <> constexpr auto num_bits() -> int { return 128; } +template <> constexpr auto num_bits() -> int { return 128; } +template <> constexpr auto num_bits() -> int { return 128; } + +// A heterogeneous bit_cast used for converting 96-bit long double to uint128_t +// and 128-bit pointers to uint128_fallback. +template sizeof(From))> +inline auto bit_cast(const From& from) -> To { + constexpr auto size = static_cast(sizeof(From) / sizeof(unsigned short)); + struct data_t { + unsigned short value[static_cast(size)]; + } data = bit_cast(from); + auto result = To(); + if (const_check(is_big_endian())) { + for (int i = 0; i < size; ++i) + result = (result << num_bits()) | data.value[i]; + } else { + for (int i = size - 1; i >= 0; --i) + result = (result << num_bits()) | data.value[i]; + } + return result; +} + +template +FMT_CONSTEXPR20 inline auto countl_zero_fallback(UInt n) -> int { + int lz = 0; + constexpr UInt msb_mask = static_cast(1) << (num_bits() - 1); + for (; (n & msb_mask) == 0; n <<= 1) lz++; + return lz; +} + +FMT_CONSTEXPR20 inline auto countl_zero(uint32_t n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated()) return FMT_BUILTIN_CLZ(n); +#endif + return countl_zero_fallback(n); +} + +FMT_CONSTEXPR20 inline auto countl_zero(uint64_t n) -> int { +#ifdef FMT_BUILTIN_CLZLL + if (!is_constant_evaluated()) return FMT_BUILTIN_CLZLL(n); +#endif + return countl_zero_fallback(n); +} + +FMT_INLINE void assume(bool condition) { + (void)condition; +#if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION + __builtin_assume(condition); +#elif FMT_GCC_VERSION + if (!condition) __builtin_unreachable(); +#endif +} + +// Attempts to reserve space for n extra characters in the output range. +// Returns a pointer to the reserved range or a reference to it. +template ::value&& + is_contiguous::value)> +#if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION +__attribute__((no_sanitize("undefined"))) +#endif +FMT_CONSTEXPR20 inline auto +reserve(OutputIt it, size_t n) -> typename OutputIt::value_type* { + auto& c = get_container(it); + size_t size = c.size(); + c.resize(size + n); + return &c[size]; +} + +template +FMT_CONSTEXPR20 inline auto reserve(basic_appender it, size_t n) + -> basic_appender { + buffer& buf = get_container(it); + buf.try_reserve(buf.size() + n); + return it; +} + +template +constexpr auto reserve(Iterator& it, size_t) -> Iterator& { + return it; +} + +template +using reserve_iterator = + remove_reference_t(), 0))>; + +template +constexpr auto to_pointer(OutputIt, size_t) -> T* { + return nullptr; +} +template FMT_CONSTEXPR auto to_pointer(T*& ptr, size_t n) -> T* { + T* begin = ptr; + ptr += n; + return begin; +} +template +FMT_CONSTEXPR20 auto to_pointer(basic_appender it, size_t n) -> T* { + buffer& buf = get_container(it); + buf.try_reserve(buf.size() + n); + auto size = buf.size(); + if (buf.capacity() < size + n) return nullptr; + buf.try_resize(size + n); + return buf.data() + size; +} + +template ::value&& + is_contiguous::value)> +inline auto base_iterator(OutputIt it, + typename OutputIt::container_type::value_type*) + -> OutputIt { + return it; +} + +template +constexpr auto base_iterator(Iterator, Iterator it) -> Iterator { + return it; +} + +// is spectacularly slow to compile in C++20 so use a simple fill_n +// instead (#1998). +template +FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value) + -> OutputIt { + for (Size i = 0; i < count; ++i) *out++ = value; + return out; +} +template +FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* { + if (is_constant_evaluated()) return fill_n(out, count, value); + static_assert(sizeof(T) == 1, + "sizeof(T) must be 1 to use char for initialization"); + std::memset(out, value, to_unsigned(count)); + return out + count; +} + +template +FMT_CONSTEXPR FMT_NOINLINE auto copy_noinline(InputIt begin, InputIt end, + OutputIt out) -> OutputIt { + return copy(begin, end, out); +} + +// A public domain branchless UTF-8 decoder by Christopher Wellons: +// https://github.com/skeeto/branchless-utf8 +/* Decode the next character, c, from s, reporting errors in e. + * + * Since this is a branchless decoder, four bytes will be read from the + * buffer regardless of the actual length of the next character. This + * means the buffer _must_ have at least three bytes of zero padding + * following the end of the data stream. + * + * Errors are reported in e, which will be non-zero if the parsed + * character was somehow invalid: invalid byte sequence, non-canonical + * encoding, or a surrogate half. + * + * The function returns a pointer to the next character. When an error + * occurs, this pointer will be a guess that depends on the particular + * error, but it will always advance at least one byte. + */ +FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e) + -> const char* { + constexpr int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; + constexpr uint32_t mins[] = {4194304, 0, 128, 2048, 65536}; + constexpr int shiftc[] = {0, 18, 12, 6, 0}; + constexpr int shifte[] = {0, 6, 4, 2, 0}; + + int len = "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4" + [static_cast(*s) >> 3]; + // Compute the pointer to the next character early so that the next + // iteration can start working on the next character. Neither Clang + // nor GCC figure out this reordering on their own. + const char* next = s + len + !len; + + using uchar = unsigned char; + + // Assume a four-byte character and load four bytes. Unused bits are + // shifted out. + *c = uint32_t(uchar(s[0]) & masks[len]) << 18; + *c |= uint32_t(uchar(s[1]) & 0x3f) << 12; + *c |= uint32_t(uchar(s[2]) & 0x3f) << 6; + *c |= uint32_t(uchar(s[3]) & 0x3f) << 0; + *c >>= shiftc[len]; + + // Accumulate the various error conditions. + *e = (*c < mins[len]) << 6; // non-canonical encoding + *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? + *e |= (*c > 0x10FFFF) << 8; // out of range? + *e |= (uchar(s[1]) & 0xc0) >> 2; + *e |= (uchar(s[2]) & 0xc0) >> 4; + *e |= uchar(s[3]) >> 6; + *e ^= 0x2a; // top two bits of each tail byte correct? + *e >>= shifte[len]; + + return next; +} + +constexpr FMT_INLINE_VARIABLE uint32_t invalid_code_point = ~uint32_t(); + +// Invokes f(cp, sv) for every code point cp in s with sv being the string view +// corresponding to the code point. cp is invalid_code_point on error. +template +FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) { + auto decode = [f](const char* buf_ptr, const char* ptr) { + auto cp = uint32_t(); + auto error = 0; + auto end = utf8_decode(buf_ptr, &cp, &error); + bool result = f(error ? invalid_code_point : cp, + string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr))); + return result ? (error ? buf_ptr + 1 : end) : nullptr; + }; + + auto p = s.data(); + const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars. + if (s.size() >= block_size) { + for (auto end = p + s.size() - block_size + 1; p < end;) { + p = decode(p, p); + if (!p) return; + } + } + auto num_chars_left = to_unsigned(s.data() + s.size() - p); + if (num_chars_left == 0) return; + + // Suppress bogus -Wstringop-overflow. + if (FMT_GCC_VERSION) num_chars_left &= 3; + char buf[2 * block_size - 1] = {}; + copy(p, p + num_chars_left, buf); + const char* buf_ptr = buf; + do { + auto end = decode(buf_ptr, p); + if (!end) return; + p += end - buf_ptr; + buf_ptr = end; + } while (buf_ptr < buf + num_chars_left); +} + +FMT_CONSTEXPR inline auto display_width_of(uint32_t cp) noexcept -> size_t { + return to_unsigned( + 1 + (cp >= 0x1100 && + (cp <= 0x115f || // Hangul Jamo init. consonants + cp == 0x2329 || // LEFT-POINTING ANGLE BRACKET + cp == 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE: + (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) || + (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables + (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs + (cp >= 0xfe10 && cp <= 0xfe19) || // Vertical Forms + (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK Compatibility Forms + (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth Forms + (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth Forms + (cp >= 0x20000 && cp <= 0x2fffd) || // CJK + (cp >= 0x30000 && cp <= 0x3fffd) || + // Miscellaneous Symbols and Pictographs + Emoticons: + (cp >= 0x1f300 && cp <= 0x1f64f) || + // Supplemental Symbols and Pictographs: + (cp >= 0x1f900 && cp <= 0x1f9ff)))); +} + +template struct is_integral : std::is_integral {}; +template <> struct is_integral : std::true_type {}; +template <> struct is_integral : std::true_type {}; + +template +using is_signed = + std::integral_constant::is_signed || + std::is_same::value>; + +template +using is_integer = + bool_constant::value && !std::is_same::value && + !std::is_same::value && + !std::is_same::value>; + +#if defined(FMT_USE_FLOAT128) +// Use the provided definition. +#elif FMT_CLANG_VERSION >= 309 && FMT_HAS_INCLUDE() +# define FMT_USE_FLOAT128 1 +#elif FMT_GCC_VERSION && defined(_GLIBCXX_USE_FLOAT128) && \ + !defined(__STRICT_ANSI__) +# define FMT_USE_FLOAT128 1 +#else +# define FMT_USE_FLOAT128 0 +#endif +#if FMT_USE_FLOAT128 +using float128 = __float128; +#else +struct float128 {}; +#endif + +template using is_float128 = std::is_same; + +template struct is_floating_point : std::is_floating_point {}; +template <> struct is_floating_point : std::true_type {}; + +template ::value> +struct is_fast_float : bool_constant::is_iec559 && + sizeof(T) <= sizeof(double)> {}; +template struct is_fast_float : std::false_type {}; + +template +using fast_float_t = conditional_t; + +template +using is_double_double = bool_constant::digits == 106>; + +#ifndef FMT_USE_FULL_CACHE_DRAGONBOX +# define FMT_USE_FULL_CACHE_DRAGONBOX 0 +#endif + +// An allocator that uses malloc/free to allow removing dependency on the C++ +// standard libary runtime. std::decay is used for back_inserter to be found by +// ADL when applied to memory_buffer. +template struct allocator : private std::decay { + using value_type = T; + + auto allocate(size_t n) -> T* { + FMT_ASSERT(n <= max_value() / sizeof(T), ""); + T* p = static_cast(std::malloc(n * sizeof(T))); + if (!p) FMT_THROW(std::bad_alloc()); + return p; + } + + void deallocate(T* p, size_t) { std::free(p); } + + constexpr friend auto operator==(allocator, allocator) noexcept -> bool { + return true; // All instances of this allocator are equivalent. + } + constexpr friend auto operator!=(allocator, allocator) noexcept -> bool { + return false; + } +}; + +} // namespace detail + +FMT_BEGIN_EXPORT + +// The number of characters to store in the basic_memory_buffer object itself +// to avoid dynamic memory allocation. +enum { inline_buffer_size = 500 }; + +/** + * A dynamically growing memory buffer for trivially copyable/constructible + * types with the first `SIZE` elements stored in the object itself. Most + * commonly used via the `memory_buffer` alias for `char`. + * + * **Example**: + * + * auto out = fmt::memory_buffer(); + * fmt::format_to(std::back_inserter(out), "The answer is {}.", 42); + * + * This will append "The answer is 42." to `out`. The buffer content can be + * converted to `std::string` with `to_string(out)`. + */ +template > +class basic_memory_buffer : public detail::buffer { + private: + T store_[SIZE]; + + // Don't inherit from Allocator to avoid generating type_info for it. + FMT_NO_UNIQUE_ADDRESS Allocator alloc_; + + // Deallocate memory allocated by the buffer. + FMT_CONSTEXPR20 void deallocate() { + T* data = this->data(); + if (data != store_) alloc_.deallocate(data, this->capacity()); + } + + static FMT_CONSTEXPR20 void grow(detail::buffer& buf, size_t size) { + detail::abort_fuzzing_if(size > 5000); + auto& self = static_cast(buf); + const size_t max_size = + std::allocator_traits::max_size(self.alloc_); + size_t old_capacity = buf.capacity(); + size_t new_capacity = old_capacity + old_capacity / 2; + if (size > new_capacity) + new_capacity = size; + else if (new_capacity > max_size) + new_capacity = max_of(size, max_size); + T* old_data = buf.data(); + T* new_data = self.alloc_.allocate(new_capacity); + // Suppress a bogus -Wstringop-overflow in gcc 13.1 (#3481). + detail::assume(buf.size() <= new_capacity); + // The following code doesn't throw, so the raw pointer above doesn't leak. + memcpy(new_data, old_data, buf.size() * sizeof(T)); + self.set(new_data, new_capacity); + // deallocate must not throw according to the standard, but even if it does, + // the buffer already uses the new storage and will deallocate it in + // destructor. + if (old_data != self.store_) self.alloc_.deallocate(old_data, old_capacity); + } + + public: + using value_type = T; + using const_reference = const T&; + + FMT_CONSTEXPR explicit basic_memory_buffer( + const Allocator& alloc = Allocator()) + : detail::buffer(grow), alloc_(alloc) { + this->set(store_, SIZE); + if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T()); + } + FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); } + + private: + template :: + propagate_on_container_move_assignment::value)> + FMT_CONSTEXPR20 auto move_alloc(basic_memory_buffer& other) -> bool { + alloc_ = std::move(other.alloc_); + return true; + } + // If the allocator does not propagate then copy the data from other. + template :: + propagate_on_container_move_assignment::value)> + FMT_CONSTEXPR20 auto move_alloc(basic_memory_buffer& other) -> bool { + T* data = other.data(); + if (alloc_ == other.alloc_ || data == other.store_) return true; + size_t size = other.size(); + // Perform copy operation, allocators are different. + this->resize(size); + detail::copy(data, data + size, this->data()); + return false; + } + + // Move data from other to this buffer. + FMT_CONSTEXPR20 void move(basic_memory_buffer& other) { + T* data = other.data(); + size_t size = other.size(), capacity = other.capacity(); + if (!move_alloc(other)) return; + if (data == other.store_) { + this->set(store_, capacity); + detail::copy(other.store_, other.store_ + size, store_); + } else { + this->set(data, capacity); + // Set pointer to the inline array so that delete is not called + // when deallocating. + other.set(other.store_, 0); + other.clear(); + } + this->resize(size); + } + + public: + /// Constructs a `basic_memory_buffer` object moving the content of the other + /// object to it. + FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept + : detail::buffer(grow) { + move(other); + } + + /// Moves the content of the other `basic_memory_buffer` object to this one. + auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& { + FMT_ASSERT(this != &other, ""); + deallocate(); + move(other); + return *this; + } + + // Returns a copy of the allocator associated with this buffer. + auto get_allocator() const -> Allocator { return alloc_; } + + /// Resizes the buffer to contain `count` elements. If T is a POD type new + /// elements may not be initialized. + FMT_CONSTEXPR void resize(size_t count) { this->try_resize(count); } + + /// Increases the buffer capacity to `new_capacity`. + void reserve(size_t new_capacity) { this->try_reserve(new_capacity); } + + using detail::buffer::append; + template + FMT_CONSTEXPR20 void append(const ContiguousRange& range) { + append(range.data(), range.data() + range.size()); + } +}; + +using memory_buffer = basic_memory_buffer; + +template +FMT_NODISCARD auto to_string(const basic_memory_buffer& buf) + -> std::string { + auto size = buf.size(); + detail::assume(size < std::string().max_size()); + return {buf.data(), size}; +} + +// A writer to a buffered stream. It doesn't own the underlying stream. +class writer { + private: + detail::buffer* buf_; + + // We cannot create a file buffer in advance because any write to a FILE may + // invalidate it. + FILE* file_; + + public: + inline writer(FILE* f) : buf_(nullptr), file_(f) {} + inline writer(detail::buffer& buf) : buf_(&buf) {} + + /// Formats `args` according to specifications in `fmt` and writes the + /// output to the file. + template void print(format_string fmt, T&&... args) { + if (buf_) + fmt::format_to(appender(*buf_), fmt, std::forward(args)...); + else + fmt::print(file_, fmt, std::forward(args)...); + } +}; + +class string_buffer { + private: + std::string str_; + detail::container_buffer buf_; + + public: + inline string_buffer() : buf_(str_) {} + + inline operator writer() { return buf_; } + inline auto str() -> std::string& { return str_; } +}; + +template +struct is_contiguous> : std::true_type { +}; + +// Suppress a misleading warning in older versions of clang. +FMT_PRAGMA_CLANG(diagnostic ignored "-Wweak-vtables") + +/// An error reported from a formatting function. +class FMT_SO_VISIBILITY("default") format_error : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +class loc_value; + +FMT_END_EXPORT +namespace detail { +FMT_API auto write_console(int fd, string_view text) -> bool; +FMT_API void print(FILE*, string_view); +} // namespace detail + +namespace detail { +template struct fixed_string { + FMT_CONSTEXPR20 fixed_string(const Char (&s)[N]) { + detail::copy(static_cast(s), s + N, + data); + } + Char data[N] = {}; +}; + +// Converts a compile-time string to basic_string_view. +FMT_EXPORT template +constexpr auto compile_string_to_view(const Char (&s)[N]) + -> basic_string_view { + // Remove trailing NUL character if needed. Won't be present if this is used + // with a raw character array (i.e. not defined as a string). + return {s, N - (std::char_traits::to_int_type(s[N - 1]) == 0 ? 1 : 0)}; +} +FMT_EXPORT template +constexpr auto compile_string_to_view(basic_string_view s) + -> basic_string_view { + return s; +} + +// Returns true if value is negative, false otherwise. +// Same as `value < 0` but doesn't produce warnings if T is an unsigned type. +template ::value)> +constexpr auto is_negative(T value) -> bool { + return value < 0; +} +template ::value)> +constexpr auto is_negative(T) -> bool { + return false; +} + +// Smallest of uint32_t, uint64_t, uint128_t that is large enough to +// represent all values of an integral type T. +template +using uint32_or_64_or_128_t = + conditional_t() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS, + uint32_t, + conditional_t() <= 64, uint64_t, uint128_t>>; +template +using uint64_or_128_t = conditional_t() <= 64, uint64_t, uint128_t>; + +#define FMT_POWERS_OF_10(factor) \ + factor * 10, (factor) * 100, (factor) * 1000, (factor) * 10000, \ + (factor) * 100000, (factor) * 1000000, (factor) * 10000000, \ + (factor) * 100000000, (factor) * 1000000000 + +// Converts value in the range [0, 100) to a string. +// GCC generates slightly better code when value is pointer-size. +inline auto digits2(size_t value) -> const char* { + // Align data since unaligned access may be slower when crossing a + // hardware-specific boundary. + alignas(2) static const char data[] = + "0001020304050607080910111213141516171819" + "2021222324252627282930313233343536373839" + "4041424344454647484950515253545556575859" + "6061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"; + return &data[value * 2]; +} + +template constexpr auto getsign(sign s) -> Char { + return static_cast(((' ' << 24) | ('+' << 16) | ('-' << 8)) >> + (static_cast(s) * 8)); +} + +template FMT_CONSTEXPR auto count_digits_fallback(T n) -> int { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000u; + count += 4; + } +} +#if FMT_USE_INT128 +FMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int { + return count_digits_fallback(n); +} +#endif + +#ifdef FMT_BUILTIN_CLZLL +// It is a separate function rather than a part of count_digits to workaround +// the lack of static constexpr in constexpr functions. +inline auto do_count_digits(uint64_t n) -> int { + // This has comparable performance to the version by Kendall Willets + // (https://github.com/fmtlib/format-benchmark/blob/master/digits10) + // but uses smaller tables. + // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)). + static constexpr uint8_t bsr2log10[] = { + 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, + 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, + 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15, + 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20}; + auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63]; + static constexpr uint64_t zero_or_powers_of_10[] = { + 0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; + return t - (n < zero_or_powers_of_10[t]); +} +#endif + +// Returns the number of decimal digits in n. Leading zeros are not counted +// except for n == 0 in which case count_digits returns 1. +FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int { +#ifdef FMT_BUILTIN_CLZLL + if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n); +#endif + return count_digits_fallback(n); +} + +// Counts the number of digits in n. BITS = log2(radix). +template +FMT_CONSTEXPR auto count_digits(UInt n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated() && num_bits() == 32) + return (FMT_BUILTIN_CLZ(static_cast(n) | 1) ^ 31) / BITS + 1; +#endif + // Lambda avoids unreachable code warnings from NVHPC. + return [](UInt m) { + int num_digits = 0; + do { + ++num_digits; + } while ((m >>= BITS) != 0); + return num_digits; + }(n); +} + +#ifdef FMT_BUILTIN_CLZ +// It is a separate function rather than a part of count_digits to workaround +// the lack of static constexpr in constexpr functions. +FMT_INLINE auto do_count_digits(uint32_t n) -> int { +// An optimization by Kendall Willets from https://bit.ly/3uOIQrB. +// This increments the upper 32 bits (log10(T) - 1) when >= T is added. +# define FMT_INC(T) (((sizeof(#T) - 1ull) << 32) - T) + static constexpr uint64_t table[] = { + FMT_INC(0), FMT_INC(0), FMT_INC(0), // 8 + FMT_INC(10), FMT_INC(10), FMT_INC(10), // 64 + FMT_INC(100), FMT_INC(100), FMT_INC(100), // 512 + FMT_INC(1000), FMT_INC(1000), FMT_INC(1000), // 4096 + FMT_INC(10000), FMT_INC(10000), FMT_INC(10000), // 32k + FMT_INC(100000), FMT_INC(100000), FMT_INC(100000), // 256k + FMT_INC(1000000), FMT_INC(1000000), FMT_INC(1000000), // 2048k + FMT_INC(10000000), FMT_INC(10000000), FMT_INC(10000000), // 16M + FMT_INC(100000000), FMT_INC(100000000), FMT_INC(100000000), // 128M + FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000), // 1024M + FMT_INC(1000000000), FMT_INC(1000000000) // 4B + }; + auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31]; + return static_cast((n + inc) >> 32); +} +#endif + +// Optional version of count_digits for better performance on 32-bit platforms. +FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n); +#endif + return count_digits_fallback(n); +} + +template constexpr auto digits10() noexcept -> int { + return std::numeric_limits::digits10; +} +template <> constexpr auto digits10() noexcept -> int { return 38; } +template <> constexpr auto digits10() noexcept -> int { return 38; } + +template struct thousands_sep_result { + std::string grouping; + Char thousands_sep; +}; + +template +FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result; +template +inline auto thousands_sep(locale_ref loc) -> thousands_sep_result { + auto result = thousands_sep_impl(loc); + return {result.grouping, Char(result.thousands_sep)}; +} +template <> +inline auto thousands_sep(locale_ref loc) -> thousands_sep_result { + return thousands_sep_impl(loc); +} + +template +FMT_API auto decimal_point_impl(locale_ref loc) -> Char; +template inline auto decimal_point(locale_ref loc) -> Char { + return Char(decimal_point_impl(loc)); +} +template <> inline auto decimal_point(locale_ref loc) -> wchar_t { + return decimal_point_impl(loc); +} + +#ifndef FMT_HEADER_ONLY +FMT_BEGIN_EXPORT +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto decimal_point_impl(locale_ref) -> char; +extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t; +FMT_END_EXPORT +#endif // FMT_HEADER_ONLY + +// Compares two characters for equality. +template auto equal2(const Char* lhs, const char* rhs) -> bool { + return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]); +} +inline auto equal2(const char* lhs, const char* rhs) -> bool { + return memcmp(lhs, rhs, 2) == 0; +} + +// Writes a two-digit value to out. +template +FMT_CONSTEXPR20 FMT_INLINE void write2digits(Char* out, size_t value) { + if (!is_constant_evaluated() && std::is_same::value && + !FMT_OPTIMIZE_SIZE) { + memcpy(out, digits2(value), 2); + return; + } + *out++ = static_cast('0' + value / 10); + *out = static_cast('0' + value % 10); +} + +// Formats a decimal unsigned integer value writing to out pointing to a buffer +// of specified size. The caller must ensure that the buffer is large enough. +template +FMT_CONSTEXPR20 auto do_format_decimal(Char* out, UInt value, int size) + -> Char* { + FMT_ASSERT(size >= count_digits(value), "invalid digit count"); + unsigned n = to_unsigned(size); + while (value >= 100) { + // Integer division is slow so do it for a group of two digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + n -= 2; + write2digits(out + n, static_cast(value % 100)); + value /= 100; + } + if (value >= 10) { + n -= 2; + write2digits(out + n, static_cast(value)); + } else { + out[--n] = static_cast('0' + value); + } + return out + n; +} + +template +FMT_CONSTEXPR FMT_INLINE auto format_decimal(Char* out, UInt value, + int num_digits) -> Char* { + do_format_decimal(out, value, num_digits); + return out + num_digits; +} + +template >::value)> +FMT_CONSTEXPR auto format_decimal(OutputIt out, UInt value, int num_digits) + -> OutputIt { + if (auto ptr = to_pointer(out, to_unsigned(num_digits))) { + do_format_decimal(ptr, value, num_digits); + return out; + } + // Buffer is large enough to hold all digits (digits10 + 1). + char buffer[digits10() + 1]; + if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0'); + do_format_decimal(buffer, value, num_digits); + return copy_noinline(buffer, buffer + num_digits, out); +} + +template +FMT_CONSTEXPR auto do_format_base2e(int base_bits, Char* out, UInt value, + int size, bool upper = false) -> Char* { + out += size; + do { + const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; + unsigned digit = static_cast(value & ((1u << base_bits) - 1)); + *--out = static_cast(base_bits < 4 ? static_cast('0' + digit) + : digits[digit]); + } while ((value >>= base_bits) != 0); + return out; +} + +// Formats an unsigned integer in the power of two base (binary, octal, hex). +template +FMT_CONSTEXPR auto format_base2e(int base_bits, Char* out, UInt value, + int num_digits, bool upper = false) -> Char* { + do_format_base2e(base_bits, out, value, num_digits, upper); + return out + num_digits; +} + +template ::value)> +FMT_CONSTEXPR inline auto format_base2e(int base_bits, OutputIt out, UInt value, + int num_digits, bool upper = false) + -> OutputIt { + if (auto ptr = to_pointer(out, to_unsigned(num_digits))) { + format_base2e(base_bits, ptr, value, num_digits, upper); + return out; + } + // Make buffer large enough for any base. + char buffer[num_bits()]; + if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0'); + format_base2e(base_bits, buffer, value, num_digits, upper); + return detail::copy_noinline(buffer, buffer + num_digits, out); +} + +// A converter from UTF-8 to UTF-16. +class utf8_to_utf16 { + private: + basic_memory_buffer buffer_; + + public: + FMT_API explicit utf8_to_utf16(string_view s); + inline operator basic_string_view() const { + return {&buffer_[0], size()}; + } + inline auto size() const -> size_t { return buffer_.size() - 1; } + inline auto c_str() const -> const wchar_t* { return &buffer_[0]; } + inline auto str() const -> std::wstring { return {&buffer_[0], size()}; } +}; + +enum class to_utf8_error_policy { abort, replace }; + +// A converter from UTF-16/UTF-32 (host endian) to UTF-8. +template class to_utf8 { + private: + Buffer buffer_; + + public: + to_utf8() {} + explicit to_utf8(basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) { + static_assert(sizeof(WChar) == 2 || sizeof(WChar) == 4, + "expected utf16 or utf32"); + if (!convert(s, policy)) { + FMT_THROW(std::runtime_error(sizeof(WChar) == 2 ? "invalid utf16" + : "invalid utf32")); + } + } + operator string_view() const { return string_view(&buffer_[0], size()); } + auto size() const -> size_t { return buffer_.size() - 1; } + auto c_str() const -> const char* { return &buffer_[0]; } + auto str() const -> std::string { return std::string(&buffer_[0], size()); } + + // Performs conversion returning a bool instead of throwing exception on + // conversion error. This method may still throw in case of memory allocation + // error. + auto convert(basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) + -> bool { + if (!convert(buffer_, s, policy)) return false; + buffer_.push_back(0); + return true; + } + static auto convert(Buffer& buf, basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) + -> bool { + for (auto p = s.begin(); p != s.end(); ++p) { + uint32_t c = static_cast(*p); + if (sizeof(WChar) == 2 && c >= 0xd800 && c <= 0xdfff) { + // Handle a surrogate pair. + ++p; + if (p == s.end() || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) { + if (policy == to_utf8_error_policy::abort) return false; + buf.append(string_view("\xEF\xBF\xBD")); + --p; + continue; + } + c = (c << 10) + static_cast(*p) - 0x35fdc00; + } + if (c < 0x80) { + buf.push_back(static_cast(c)); + } else if (c < 0x800) { + buf.push_back(static_cast(0xc0 | (c >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) { + buf.push_back(static_cast(0xe0 | (c >> 12))); + buf.push_back(static_cast(0x80 | ((c & 0xfff) >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else if (c >= 0x10000 && c <= 0x10ffff) { + buf.push_back(static_cast(0xf0 | (c >> 18))); + buf.push_back(static_cast(0x80 | ((c & 0x3ffff) >> 12))); + buf.push_back(static_cast(0x80 | ((c & 0xfff) >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else { + return false; + } + } + return true; + } +}; + +// Computes 128-bit result of multiplication of two 64-bit unsigned integers. +FMT_INLINE auto umul128(uint64_t x, uint64_t y) noexcept -> uint128_fallback { +#if FMT_USE_INT128 + auto p = static_cast(x) * static_cast(y); + return {static_cast(p >> 64), static_cast(p)}; +#elif defined(_MSC_VER) && defined(_M_X64) + auto hi = uint64_t(); + auto lo = _umul128(x, y, &hi); + return {hi, lo}; +#else + const uint64_t mask = static_cast(max_value()); + + uint64_t a = x >> 32; + uint64_t b = x & mask; + uint64_t c = y >> 32; + uint64_t d = y & mask; + + uint64_t ac = a * c; + uint64_t bc = b * c; + uint64_t ad = a * d; + uint64_t bd = b * d; + + uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask); + + return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32), + (intermediate << 32) + (bd & mask)}; +#endif +} + +namespace dragonbox { +// Computes floor(log10(pow(2, e))) for e in [-2620, 2620] using the method from +// https://fmt.dev/papers/Dragonbox.pdf#page=28, section 6.1. +inline auto floor_log10_pow2(int e) noexcept -> int { + FMT_ASSERT(e <= 2620 && e >= -2620, "too large exponent"); + static_assert((-1 >> 1) == -1, "right shift is not arithmetic"); + return (e * 315653) >> 20; +} + +inline auto floor_log2_pow10(int e) noexcept -> int { + FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent"); + return (e * 1741647) >> 19; +} + +// Computes upper 64 bits of multiplication of two 64-bit unsigned integers. +inline auto umul128_upper64(uint64_t x, uint64_t y) noexcept -> uint64_t { +#if FMT_USE_INT128 + auto p = static_cast(x) * static_cast(y); + return static_cast(p >> 64); +#elif defined(_MSC_VER) && defined(_M_X64) + return __umulh(x, y); +#else + return umul128(x, y).high(); +#endif +} + +// Computes upper 128 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +inline auto umul192_upper128(uint64_t x, uint128_fallback y) noexcept + -> uint128_fallback { + uint128_fallback r = umul128(x, y.high()); + r += umul128_upper64(x, y.low()); + return r; +} + +FMT_API auto get_cached_power(int k) noexcept -> uint128_fallback; + +// Type-specific information that Dragonbox uses. +template struct float_info; + +template <> struct float_info { + using carrier_uint = uint32_t; + static const int exponent_bits = 8; + static const int kappa = 1; + static const int big_divisor = 100; + static const int small_divisor = 10; + static const int min_k = -31; + static const int max_k = 46; + static const int shorter_interval_tie_lower_threshold = -35; + static const int shorter_interval_tie_upper_threshold = -35; +}; + +template <> struct float_info { + using carrier_uint = uint64_t; + static const int exponent_bits = 11; + static const int kappa = 2; + static const int big_divisor = 1000; + static const int small_divisor = 100; + static const int min_k = -292; + static const int max_k = 341; + static const int shorter_interval_tie_lower_threshold = -77; + static const int shorter_interval_tie_upper_threshold = -77; +}; + +// An 80- or 128-bit floating point number. +template +struct float_info::digits == 64 || + std::numeric_limits::digits == 113 || + is_float128::value>> { + using carrier_uint = detail::uint128_t; + static const int exponent_bits = 15; +}; + +// A double-double floating point number. +template +struct float_info::value>> { + using carrier_uint = detail::uint128_t; +}; + +template struct decimal_fp { + using significand_type = typename float_info::carrier_uint; + significand_type significand; + int exponent; +}; + +template FMT_API auto to_decimal(T x) noexcept -> decimal_fp; +} // namespace dragonbox + +// Returns true iff Float has the implicit bit which is not stored. +template constexpr auto has_implicit_bit() -> bool { + // An 80-bit FP number has a 64-bit significand an no implicit bit. + return std::numeric_limits::digits != 64; +} + +// Returns the number of significand bits stored in Float. The implicit bit is +// not counted since it is not stored. +template constexpr auto num_significand_bits() -> int { + // std::numeric_limits may not support __float128. + return is_float128() ? 112 + : (std::numeric_limits::digits - + (has_implicit_bit() ? 1 : 0)); +} + +template +constexpr auto exponent_mask() -> + typename dragonbox::float_info::carrier_uint { + using float_uint = typename dragonbox::float_info::carrier_uint; + return ((float_uint(1) << dragonbox::float_info::exponent_bits) - 1) + << num_significand_bits(); +} +template constexpr auto exponent_bias() -> int { + // std::numeric_limits may not support __float128. + return is_float128() ? 16383 + : std::numeric_limits::max_exponent - 1; +} + +FMT_CONSTEXPR inline auto compute_exp_size(int exp) -> int { + auto prefix_size = 2; // sign + 'e' + auto abs_exp = exp >= 0 ? exp : -exp; + if (abs_exp < 100) return prefix_size + 2; + return prefix_size + (abs_exp >= 1000 ? 4 : 3); +} + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template +FMT_CONSTEXPR auto write_exponent(int exp, OutputIt out) -> OutputIt { + FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); + if (exp < 0) { + *out++ = static_cast('-'); + exp = -exp; + } else { + *out++ = static_cast('+'); + } + auto uexp = static_cast(exp); + if (is_constant_evaluated()) { + if (uexp < 10) *out++ = '0'; + return format_decimal(out, uexp, count_digits(uexp)); + } + if (uexp >= 100u) { + const char* top = digits2(uexp / 100); + if (uexp >= 1000u) *out++ = static_cast(top[0]); + *out++ = static_cast(top[1]); + uexp %= 100; + } + const char* d = digits2(uexp); + *out++ = static_cast(d[0]); + *out++ = static_cast(d[1]); + return out; +} + +// A floating-point number f * pow(2, e) where F is an unsigned type. +template struct basic_fp { + F f; + int e; + + static constexpr int num_significand_bits = + static_cast(sizeof(F) * num_bits()); + + constexpr basic_fp() : f(0), e(0) {} + constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} + + // Constructs fp from an IEEE754 floating-point number. + template FMT_CONSTEXPR basic_fp(Float n) { assign(n); } + + // Assigns n to this and return true iff predecessor is closer than successor. + template ::value)> + FMT_CONSTEXPR auto assign(Float n) -> bool { + static_assert(std::numeric_limits::digits <= 113, "unsupported FP"); + // Assume Float is in the format [sign][exponent][significand]. + using carrier_uint = typename dragonbox::float_info::carrier_uint; + const auto num_float_significand_bits = + detail::num_significand_bits(); + const auto implicit_bit = carrier_uint(1) << num_float_significand_bits; + const auto significand_mask = implicit_bit - 1; + auto u = bit_cast(n); + f = static_cast(u & significand_mask); + auto biased_e = static_cast((u & exponent_mask()) >> + num_float_significand_bits); + // The predecessor is closer if n is a normalized power of 2 (f == 0) + // other than the smallest normalized number (biased_e > 1). + auto is_predecessor_closer = f == 0 && biased_e > 1; + if (biased_e == 0) + biased_e = 1; // Subnormals use biased exponent 1 (min exponent). + else if (has_implicit_bit()) + f += static_cast(implicit_bit); + e = biased_e - exponent_bias() - num_float_significand_bits; + if (!has_implicit_bit()) ++e; + return is_predecessor_closer; + } + + template ::value)> + FMT_CONSTEXPR auto assign(Float n) -> bool { + static_assert(std::numeric_limits::is_iec559, "unsupported FP"); + return assign(static_cast(n)); + } +}; + +using fp = basic_fp; + +// Normalizes the value converted from double and multiplied by (1 << SHIFT). +template +FMT_CONSTEXPR auto normalize(basic_fp value) -> basic_fp { + // Handle subnormals. + const auto implicit_bit = F(1) << num_significand_bits(); + const auto shifted_implicit_bit = implicit_bit << SHIFT; + while ((value.f & shifted_implicit_bit) == 0) { + value.f <<= 1; + --value.e; + } + // Subtract 1 to account for hidden bit. + const auto offset = basic_fp::num_significand_bits - + num_significand_bits() - SHIFT - 1; + value.f <<= offset; + value.e -= offset; + return value; +} + +// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. +FMT_CONSTEXPR inline auto multiply(uint64_t lhs, uint64_t rhs) -> uint64_t { +#if FMT_USE_INT128 + auto product = static_cast<__uint128_t>(lhs) * rhs; + auto f = static_cast(product >> 64); + return (static_cast(product) & (1ULL << 63)) != 0 ? f + 1 : f; +#else + // Multiply 32-bit parts of significands. + uint64_t mask = (1ULL << 32) - 1; + uint64_t a = lhs >> 32, b = lhs & mask; + uint64_t c = rhs >> 32, d = rhs & mask; + uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; + // Compute mid 64-bit of result and round. + uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); + return ac + (ad >> 32) + (bc >> 32) + (mid >> 32); +#endif +} + +FMT_CONSTEXPR inline auto operator*(fp x, fp y) -> fp { + return {multiply(x.f, y.f), x.e + y.e + 64}; +} + +template () == num_bits()> +using convert_float_result = + conditional_t::value || doublish, double, T>; + +template +constexpr auto convert_float(T value) -> convert_float_result { + return static_cast>(value); +} + +template +auto select(T true_value, F) -> T { + return true_value; +} +template +auto select(T, F false_value) -> F { + return false_value; +} + +template +FMT_CONSTEXPR FMT_NOINLINE auto fill(OutputIt it, size_t n, + const basic_specs& specs) -> OutputIt { + auto fill_size = specs.fill_size(); + if (fill_size == 1) return detail::fill_n(it, n, specs.fill_unit()); + if (const Char* data = specs.fill()) { + for (size_t i = 0; i < n; ++i) it = copy(data, data + fill_size, it); + } + return it; +} + +// Writes the output of f, padded according to format specifications in specs. +// size: output size in code units. +// width: output display width in (terminal) column positions. +template +FMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs, + size_t size, size_t width, F&& f) -> OutputIt { + static_assert(default_align == align::left || default_align == align::right, + ""); + unsigned spec_width = to_unsigned(specs.width); + size_t padding = spec_width > width ? spec_width - width : 0; + // Shifts are encoded as string literals because static constexpr is not + // supported in constexpr functions. + auto* shifts = + default_align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01"; + size_t left_padding = padding >> shifts[static_cast(specs.align())]; + size_t right_padding = padding - left_padding; + auto it = reserve(out, size + padding * specs.fill_size()); + if (left_padding != 0) it = fill(it, left_padding, specs); + it = f(it); + if (right_padding != 0) it = fill(it, right_padding, specs); + return base_iterator(out, it); +} + +template +constexpr auto write_padded(OutputIt out, const format_specs& specs, + size_t size, F&& f) -> OutputIt { + return write_padded(out, specs, size, size, f); +} + +template +FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes, + const format_specs& specs = {}) -> OutputIt { + return write_padded( + out, specs, bytes.size(), [bytes](reserve_iterator it) { + const char* data = bytes.data(); + return copy(data, data + bytes.size(), it); + }); +} + +template +auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs) + -> OutputIt { + int num_digits = count_digits<4>(value); + auto size = to_unsigned(num_digits) + size_t(2); + auto write = [=](reserve_iterator it) { + *it++ = static_cast('0'); + *it++ = static_cast('x'); + return format_base2e(4, it, value, num_digits); + }; + return specs ? write_padded(out, *specs, size, write) + : base_iterator(out, write(reserve(out, size))); +} + +// Returns true iff the code point cp is printable. +FMT_API auto is_printable(uint32_t cp) -> bool; + +inline auto needs_escape(uint32_t cp) -> bool { + if (cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\') return true; + if (const_check(FMT_OPTIMIZE_SIZE > 1)) return false; + return !is_printable(cp); +} + +template struct find_escape_result { + const Char* begin; + const Char* end; + uint32_t cp; +}; + +template +auto find_escape(const Char* begin, const Char* end) + -> find_escape_result { + for (; begin != end; ++begin) { + uint32_t cp = static_cast>(*begin); + if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue; + if (needs_escape(cp)) return {begin, begin + 1, cp}; + } + return {begin, nullptr, 0}; +} + +inline auto find_escape(const char* begin, const char* end) + -> find_escape_result { + if (const_check(!use_utf8)) return find_escape(begin, end); + auto result = find_escape_result{end, nullptr, 0}; + for_each_codepoint(string_view(begin, to_unsigned(end - begin)), + [&](uint32_t cp, string_view sv) { + if (needs_escape(cp)) { + result = {sv.begin(), sv.end(), cp}; + return false; + } + return true; + }); + return result; +} + +template +auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt { + *out++ = static_cast('\\'); + *out++ = static_cast(prefix); + Char buf[width]; + fill_n(buf, width, static_cast('0')); + format_base2e(4, buf, cp, width); + return copy(buf, buf + width, out); +} + +template +auto write_escaped_cp(OutputIt out, const find_escape_result& escape) + -> OutputIt { + auto c = static_cast(escape.cp); + switch (escape.cp) { + case '\n': + *out++ = static_cast('\\'); + c = static_cast('n'); + break; + case '\r': + *out++ = static_cast('\\'); + c = static_cast('r'); + break; + case '\t': + *out++ = static_cast('\\'); + c = static_cast('t'); + break; + case '"': FMT_FALLTHROUGH; + case '\'': FMT_FALLTHROUGH; + case '\\': *out++ = static_cast('\\'); break; + default: + if (escape.cp < 0x100) return write_codepoint<2, Char>(out, 'x', escape.cp); + if (escape.cp < 0x10000) + return write_codepoint<4, Char>(out, 'u', escape.cp); + if (escape.cp < 0x110000) + return write_codepoint<8, Char>(out, 'U', escape.cp); + for (Char escape_char : basic_string_view( + escape.begin, to_unsigned(escape.end - escape.begin))) { + out = write_codepoint<2, Char>(out, 'x', + static_cast(escape_char) & 0xFF); + } + return out; + } + *out++ = c; + return out; +} + +template +auto write_escaped_string(OutputIt out, basic_string_view str) + -> OutputIt { + *out++ = static_cast('"'); + auto begin = str.begin(), end = str.end(); + do { + auto escape = find_escape(begin, end); + out = copy(begin, escape.begin, out); + begin = escape.end; + if (!begin) break; + out = write_escaped_cp(out, escape); + } while (begin != end); + *out++ = static_cast('"'); + return out; +} + +template +auto write_escaped_char(OutputIt out, Char v) -> OutputIt { + Char v_array[1] = {v}; + *out++ = static_cast('\''); + if ((needs_escape(static_cast(v)) && v != static_cast('"')) || + v == static_cast('\'')) { + out = write_escaped_cp(out, + find_escape_result{v_array, v_array + 1, + static_cast(v)}); + } else { + *out++ = v; + } + *out++ = static_cast('\''); + return out; +} + +template +FMT_CONSTEXPR auto write_char(OutputIt out, Char value, + const format_specs& specs) -> OutputIt { + bool is_debug = specs.type() == presentation_type::debug; + return write_padded(out, specs, 1, [=](reserve_iterator it) { + if (is_debug) return write_escaped_char(it, value); + *it++ = value; + return it; + }); +} + +template class digit_grouping { + private: + std::string grouping_; + std::basic_string thousands_sep_; + + struct next_state { + std::string::const_iterator group; + int pos; + }; + auto initial_state() const -> next_state { return {grouping_.begin(), 0}; } + + // Returns the next digit group separator position. + auto next(next_state& state) const -> int { + if (thousands_sep_.empty()) return max_value(); + if (state.group == grouping_.end()) return state.pos += grouping_.back(); + if (*state.group <= 0 || *state.group == max_value()) + return max_value(); + state.pos += *state.group++; + return state.pos; + } + + public: + explicit digit_grouping(locale_ref loc, bool localized = true) { + if (!localized) return; + auto sep = thousands_sep(loc); + grouping_ = sep.grouping; + if (sep.thousands_sep) thousands_sep_.assign(1, sep.thousands_sep); + } + digit_grouping(std::string grouping, std::basic_string sep) + : grouping_(std::move(grouping)), thousands_sep_(std::move(sep)) {} + + auto has_separator() const -> bool { return !thousands_sep_.empty(); } + + auto count_separators(int num_digits) const -> int { + int count = 0; + auto state = initial_state(); + while (num_digits > next(state)) ++count; + return count; + } + + // Applies grouping to digits and writes the output to out. + template + auto apply(Out out, basic_string_view digits) const -> Out { + auto num_digits = static_cast(digits.size()); + auto separators = basic_memory_buffer(); + separators.push_back(0); + auto state = initial_state(); + while (int i = next(state)) { + if (i >= num_digits) break; + separators.push_back(i); + } + for (int i = 0, sep_index = static_cast(separators.size() - 1); + i < num_digits; ++i) { + if (num_digits - i == separators[sep_index]) { + out = copy(thousands_sep_.data(), + thousands_sep_.data() + thousands_sep_.size(), out); + --sep_index; + } + *out++ = static_cast(digits[to_unsigned(i)]); + } + return out; + } +}; + +FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) { + prefix |= prefix != 0 ? value << 8 : value; + prefix += (1u + (value > 0xff ? 1 : 0)) << 24; +} + +// Writes a decimal integer with digit grouping. +template +auto write_int(OutputIt out, UInt value, unsigned prefix, + const format_specs& specs, const digit_grouping& grouping) + -> OutputIt { + static_assert(std::is_same, UInt>::value, ""); + int num_digits = 0; + auto buffer = memory_buffer(); + switch (specs.type()) { + default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH; + case presentation_type::none: + case presentation_type::dec: + num_digits = count_digits(value); + format_decimal(appender(buffer), value, num_digits); + break; + case presentation_type::hex: + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0'); + num_digits = count_digits<4>(value); + format_base2e(4, appender(buffer), value, num_digits, specs.upper()); + break; + case presentation_type::oct: + num_digits = count_digits<3>(value); + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + if (specs.alt() && specs.precision <= num_digits && value != 0) + prefix_append(prefix, '0'); + format_base2e(3, appender(buffer), value, num_digits); + break; + case presentation_type::bin: + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0'); + num_digits = count_digits<1>(value); + format_base2e(1, appender(buffer), value, num_digits); + break; + case presentation_type::chr: + return write_char(out, static_cast(value), specs); + } + + unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) + + to_unsigned(grouping.count_separators(num_digits)); + return write_padded( + out, specs, size, size, [&](reserve_iterator it) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + return grouping.apply(it, string_view(buffer.data(), buffer.size())); + }); +} + +#if FMT_USE_LOCALE +// Writes a localized value. +FMT_API auto write_loc(appender out, loc_value value, const format_specs& specs, + locale_ref loc) -> bool; +auto write_loc(basic_appender out, loc_value value, + const format_specs& specs, locale_ref loc) -> bool; +#endif +template +inline auto write_loc(OutputIt, const loc_value&, const format_specs&, + locale_ref) -> bool { + return false; +} + +template struct write_int_arg { + UInt abs_value; + unsigned prefix; +}; + +template +FMT_CONSTEXPR auto make_write_int_arg(T value, sign s) + -> write_int_arg> { + auto prefix = 0u; + auto abs_value = static_cast>(value); + if (is_negative(value)) { + prefix = 0x01000000 | '-'; + abs_value = 0 - abs_value; + } else { + constexpr unsigned prefixes[4] = {0, 0, 0x1000000u | '+', 0x1000000u | ' '}; + prefix = prefixes[static_cast(s)]; + } + return {abs_value, prefix}; +} + +template struct loc_writer { + basic_appender out; + const format_specs& specs; + std::basic_string sep; + std::string grouping; + std::basic_string decimal_point; + + template ::value)> + auto operator()(T value) -> bool { + auto arg = make_write_int_arg(value, specs.sign()); + write_int(out, static_cast>(arg.abs_value), arg.prefix, + specs, digit_grouping(grouping, sep)); + return true; + } + + template ::value)> + auto operator()(T) -> bool { + return false; + } +}; + +// Size and padding computation separate from write_int to avoid template bloat. +struct size_padding { + unsigned size; + unsigned padding; + + FMT_CONSTEXPR size_padding(int num_digits, unsigned prefix, + const format_specs& specs) + : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) { + if (specs.align() == align::numeric) { + auto width = to_unsigned(specs.width); + if (width > size) { + padding = width - size; + size = width; + } + } else if (specs.precision > num_digits) { + size = (prefix >> 24) + to_unsigned(specs.precision); + padding = to_unsigned(specs.precision - num_digits); + } + } +}; + +template +FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg arg, + const format_specs& specs) -> OutputIt { + static_assert(std::is_same>::value, ""); + + constexpr size_t buffer_size = num_bits(); + char buffer[buffer_size]; + if (is_constant_evaluated()) fill_n(buffer, buffer_size, '\0'); + const char* begin = nullptr; + const char* end = buffer + buffer_size; + + auto abs_value = arg.abs_value; + auto prefix = arg.prefix; + switch (specs.type()) { + default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH; + case presentation_type::none: + case presentation_type::dec: + begin = do_format_decimal(buffer, abs_value, buffer_size); + break; + case presentation_type::hex: + begin = do_format_base2e(4, buffer, abs_value, buffer_size, specs.upper()); + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0'); + break; + case presentation_type::oct: { + begin = do_format_base2e(3, buffer, abs_value, buffer_size); + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + auto num_digits = end - begin; + if (specs.alt() && specs.precision <= num_digits && abs_value != 0) + prefix_append(prefix, '0'); + break; + } + case presentation_type::bin: + begin = do_format_base2e(1, buffer, abs_value, buffer_size); + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0'); + break; + case presentation_type::chr: + return write_char(out, static_cast(abs_value), specs); + } + + // Write an integer in the format + // + // prefix contains chars in three lower bytes and the size in the fourth byte. + int num_digits = static_cast(end - begin); + // Slightly faster check for specs.width == 0 && specs.precision == -1. + if ((specs.width | (specs.precision + 1)) == 0) { + auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24)); + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + return base_iterator(out, copy(begin, end, it)); + } + auto sp = size_padding(num_digits, prefix, specs); + unsigned padding = sp.padding; + return write_padded( + out, specs, sp.size, [=](reserve_iterator it) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + it = detail::fill_n(it, padding, static_cast('0')); + return copy(begin, end, it); + }); +} + +template +FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(OutputIt out, + write_int_arg arg, + const format_specs& specs) + -> OutputIt { + return write_int(out, arg, specs); +} + +template ::value && + !std::is_same::value && + !std::is_same::value)> +FMT_CONSTEXPR FMT_INLINE auto write(basic_appender out, T value, + const format_specs& specs, locale_ref loc) + -> basic_appender { + if (specs.localized() && write_loc(out, value, specs, loc)) return out; + return write_int_noinline(out, make_write_int_arg(value, specs.sign()), + specs); +} + +// An inlined version of write used in format string compilation. +template ::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same>::value)> +FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value, + const format_specs& specs, locale_ref loc) + -> OutputIt { + if (specs.localized() && write_loc(out, value, specs, loc)) return out; + return write_int(out, make_write_int_arg(value, specs.sign()), specs); +} + +template +FMT_CONSTEXPR auto write(OutputIt out, Char value, const format_specs& specs, + locale_ref loc = {}) -> OutputIt { + // char is formatted as unsigned char for consistency across platforms. + using unsigned_type = + conditional_t::value, unsigned char, unsigned>; + return check_char_specs(specs) + ? write_char(out, value, specs) + : write(out, static_cast(value), specs, loc); +} + +template ::value)> +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, + const format_specs& specs) -> OutputIt { + bool is_debug = specs.type() == presentation_type::debug; + if (specs.precision < 0 && specs.width == 0) { + auto&& it = reserve(out, s.size()); + return is_debug ? write_escaped_string(it, s) : copy(s, it); + } + + size_t display_width_limit = + specs.precision < 0 ? SIZE_MAX : to_unsigned(specs.precision); + size_t display_width = + !is_debug || specs.precision == 0 ? 0 : 1; // Account for opening '"'. + size_t size = !is_debug || specs.precision == 0 ? 0 : 1; + for_each_codepoint(s, [&](uint32_t cp, string_view sv) { + if (is_debug && needs_escape(cp)) { + counting_buffer buf; + write_escaped_cp(basic_appender(buf), + find_escape_result{sv.begin(), sv.end(), cp}); + // We're reinterpreting bytes as display width. That's okay + // because write_escaped_cp() only writes ASCII characters. + size_t cp_width = buf.count(); + if (display_width + cp_width <= display_width_limit) { + display_width += cp_width; + size += cp_width; + // If this is the end of the string, account for closing '"'. + if (display_width < display_width_limit && sv.end() == s.end()) { + ++display_width; + ++size; + } + return true; + } + + size += display_width_limit - display_width; + display_width = display_width_limit; + return false; + } + + size_t cp_width = display_width_of(cp); + if (cp_width + display_width <= display_width_limit) { + display_width += cp_width; + size += sv.size(); + // If this is the end of the string, account for closing '"'. + if (is_debug && display_width < display_width_limit && + sv.end() == s.end()) { + ++display_width; + ++size; + } + return true; + } + + return false; + }); + + struct bounded_output_iterator { + reserve_iterator underlying_iterator; + size_t bound; + + FMT_CONSTEXPR auto operator*() -> bounded_output_iterator& { return *this; } + FMT_CONSTEXPR auto operator++() -> bounded_output_iterator& { + return *this; + } + FMT_CONSTEXPR auto operator++(int) -> bounded_output_iterator& { + return *this; + } + FMT_CONSTEXPR auto operator=(char c) -> bounded_output_iterator& { + if (bound > 0) { + *underlying_iterator++ = c; + --bound; + } + return *this; + } + }; + + return write_padded( + out, specs, size, display_width, [=](reserve_iterator it) { + return is_debug + ? write_escaped_string(bounded_output_iterator{it, size}, s) + .underlying_iterator + : copy(s.data(), s.data() + size, it); + }); +} + +template ::value)> +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, + const format_specs& specs) -> OutputIt { + auto data = s.data(); + auto size = s.size(); + if (specs.precision >= 0 && to_unsigned(specs.precision) < size) + size = to_unsigned(specs.precision); + + bool is_debug = specs.type() == presentation_type::debug; + if (is_debug) { + auto buf = counting_buffer(); + write_escaped_string(basic_appender(buf), s); + size = buf.count(); + } + + return write_padded( + out, specs, size, [=](reserve_iterator it) { + return is_debug ? write_escaped_string(it, s) + : copy(data, data + size, it); + }); +} + +template +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, + const format_specs& specs, locale_ref) -> OutputIt { + return write(out, s, specs); +} + +template +FMT_CONSTEXPR auto write(OutputIt out, const Char* s, const format_specs& specs, + locale_ref) -> OutputIt { + if (specs.type() == presentation_type::pointer) + return write_ptr(out, bit_cast(s), &specs); + if (!s) report_error("string pointer is null"); + return write(out, basic_string_view(s), specs, {}); +} + +template ::value && + !std::is_same::value && + !std::is_same::value)> +FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { + auto abs_value = static_cast>(value); + bool negative = is_negative(value); + // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer. + if (negative) abs_value = ~abs_value + 1; + int num_digits = count_digits(abs_value); + auto size = (negative ? 1 : 0) + static_cast(num_digits); + if (auto ptr = to_pointer(out, size)) { + if (negative) *ptr++ = static_cast('-'); + format_decimal(ptr, abs_value, num_digits); + return out; + } + if (negative) *out++ = static_cast('-'); + return format_decimal(out, abs_value, num_digits); +} + +template +FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end, + format_specs& specs) -> const Char* { + FMT_ASSERT(begin != end, ""); + auto alignment = align::none; + auto p = begin + code_point_length(begin); + if (end - p <= 0) p = begin; + for (;;) { + switch (to_ascii(*p)) { + case '<': alignment = align::left; break; + case '>': alignment = align::right; break; + case '^': alignment = align::center; break; + } + if (alignment != align::none) { + if (p != begin) { + auto c = *begin; + if (c == '}') return begin; + if (c == '{') { + report_error("invalid fill character '{'"); + return begin; + } + specs.set_fill(basic_string_view(begin, to_unsigned(p - begin))); + begin = p + 1; + } else { + ++begin; + } + break; + } else if (p == begin) { + break; + } + p = begin; + } + specs.set_align(alignment); + return begin; +} + +template +FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan, + format_specs specs, sign s) -> OutputIt { + auto str = + isnan ? (specs.upper() ? "NAN" : "nan") : (specs.upper() ? "INF" : "inf"); + constexpr size_t str_size = 3; + auto size = str_size + (s != sign::none ? 1 : 0); + // Replace '0'-padding with space for non-finite values. + const bool is_zero_fill = + specs.fill_size() == 1 && specs.fill_unit() == '0'; + if (is_zero_fill) specs.set_fill(' '); + return write_padded(out, specs, size, + [=](reserve_iterator it) { + if (s != sign::none) + *it++ = detail::getsign(s); + return copy(str, str + str_size, it); + }); +} + +// A decimal floating-point number significand * pow(10, exp). +struct big_decimal_fp { + const char* significand; + int significand_size; + int exponent; +}; + +constexpr auto get_significand_size(const big_decimal_fp& f) -> int { + return f.significand_size; +} +template +inline auto get_significand_size(const dragonbox::decimal_fp& f) -> int { + return count_digits(f.significand); +} + +template +constexpr auto write_significand(OutputIt out, const char* significand, + int significand_size) -> OutputIt { + return copy(significand, significand + significand_size, out); +} +template +inline auto write_significand(OutputIt out, UInt significand, + int significand_size) -> OutputIt { + return format_decimal(out, significand, significand_size); +} +template +FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, + int significand_size, int exponent, + const Grouping& grouping) -> OutputIt { + if (!grouping.has_separator()) { + out = write_significand(out, significand, significand_size); + return detail::fill_n(out, exponent, static_cast('0')); + } + auto buffer = memory_buffer(); + write_significand(appender(buffer), significand, significand_size); + detail::fill_n(appender(buffer), exponent, '0'); + return grouping.apply(out, string_view(buffer.data(), buffer.size())); +} + +template ::value)> +inline auto write_significand(Char* out, UInt significand, int significand_size, + int integral_size, Char decimal_point) -> Char* { + if (!decimal_point) return format_decimal(out, significand, significand_size); + out += significand_size + 1; + Char* end = out; + int floating_size = significand_size - integral_size; + for (int i = floating_size / 2; i > 0; --i) { + out -= 2; + write2digits(out, static_cast(significand % 100)); + significand /= 100; + } + if (floating_size % 2 != 0) { + *--out = static_cast('0' + significand % 10); + significand /= 10; + } + *--out = decimal_point; + format_decimal(out - integral_size, significand, integral_size); + return end; +} + +template >::value)> +inline auto write_significand(OutputIt out, UInt significand, + int significand_size, int integral_size, + Char decimal_point) -> OutputIt { + // Buffer is large enough to hold digits (digits10 + 1) and a decimal point. + Char buffer[digits10() + 2]; + auto end = write_significand(buffer, significand, significand_size, + integral_size, decimal_point); + return detail::copy_noinline(buffer, end, out); +} + +template +FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand, + int significand_size, int integral_size, + Char decimal_point) -> OutputIt { + out = detail::copy_noinline(significand, significand + integral_size, + out); + if (!decimal_point) return out; + *out++ = decimal_point; + return detail::copy_noinline(significand + integral_size, + significand + significand_size, out); +} + +template +FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, + int significand_size, int integral_size, + Char decimal_point, + const Grouping& grouping) -> OutputIt { + if (!grouping.has_separator()) { + return write_significand(out, significand, significand_size, integral_size, + decimal_point); + } + auto buffer = basic_memory_buffer(); + write_significand(basic_appender(buffer), significand, significand_size, + integral_size, decimal_point); + grouping.apply( + out, basic_string_view(buffer.data(), to_unsigned(integral_size))); + return detail::copy_noinline(buffer.data() + integral_size, + buffer.end(), out); +} + +// Numbers with exponents greater or equal to the returned value will use +// the exponential notation. +template FMT_CONSTEVAL auto exp_upper() -> int { + return std::numeric_limits::digits10 != 0 + ? min_of(16, std::numeric_limits::digits10 + 1) + : 16; +} + +// Use the fixed notation if the exponent is in [-4, exp_upper), +// e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation. +constexpr auto use_fixed(int exp, int exp_upper) -> bool { + return exp >= -4 && exp < exp_upper; +} + +template class fallback_digit_grouping { + public: + constexpr fallback_digit_grouping(locale_ref, bool) {} + + constexpr auto has_separator() const -> bool { return false; } + + constexpr auto count_separators(int) const -> int { return 0; } + + template + constexpr auto apply(Out out, basic_string_view) const -> Out { + return out; + } +}; + +template +FMT_CONSTEXPR20 auto write_fixed(OutputIt out, const DecimalFP& f, + int significand_size, Char decimal_point, + const format_specs& specs, sign s, + locale_ref loc = {}) -> OutputIt { + using iterator = reserve_iterator; + + int exp = f.exponent + significand_size; + long long size = significand_size + (s != sign::none ? 1 : 0); + if (f.exponent >= 0) { + // 1234e5 -> 123400000[.0+] + size += f.exponent; + int num_zeros = specs.precision - exp; + abort_fuzzing_if(num_zeros > 5000); + if (specs.alt()) { + ++size; + if (num_zeros <= 0 && specs.type() != presentation_type::fixed) + num_zeros = 0; + if (num_zeros > 0) size += num_zeros; + } + auto grouping = Grouping(loc, specs.localized()); + size += grouping.count_separators(exp); + return write_padded( + out, specs, to_unsigned(size), [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + it = write_significand(it, f.significand, significand_size, + f.exponent, grouping); + if (!specs.alt()) return it; + *it++ = decimal_point; + return num_zeros > 0 ? detail::fill_n(it, num_zeros, Char('0')) : it; + }); + } + if (exp > 0) { + // 1234e-2 -> 12.34[0+] + int num_zeros = specs.alt() ? specs.precision - significand_size : 0; + size += 1 + max_of(num_zeros, 0); + auto grouping = Grouping(loc, specs.localized()); + size += grouping.count_separators(exp); + return write_padded( + out, specs, to_unsigned(size), [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + it = write_significand(it, f.significand, significand_size, exp, + decimal_point, grouping); + return num_zeros > 0 ? detail::fill_n(it, num_zeros, Char('0')) : it; + }); + } + // 1234e-6 -> 0.001234 + int num_zeros = -exp; + if (significand_size == 0 && specs.precision >= 0 && + specs.precision < num_zeros) { + num_zeros = specs.precision; + } + bool pointy = num_zeros != 0 || significand_size != 0 || specs.alt(); + size += 1 + (pointy ? 1 : 0) + num_zeros; + return write_padded( + out, specs, to_unsigned(size), [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + *it++ = Char('0'); + if (!pointy) return it; + *it++ = decimal_point; + it = detail::fill_n(it, num_zeros, Char('0')); + return write_significand(it, f.significand, significand_size); + }); +} + +template +FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f, + const format_specs& specs, sign s, + int exp_upper, locale_ref loc) -> OutputIt { + Char point = specs.localized() ? detail::decimal_point(loc) : Char('.'); + int significand_size = get_significand_size(f); + int exp = f.exponent + significand_size - 1; + if (specs.type() == presentation_type::fixed || + (specs.type() != presentation_type::exp && + use_fixed(exp, specs.precision > 0 ? specs.precision : exp_upper))) { + return write_fixed(out, f, significand_size, point, specs, + s, loc); + } + + // Write value in the exponential format. + int num_zeros = 0; + long long size = significand_size + (s != sign::none ? 1 : 0); + if (specs.alt()) { + num_zeros = max_of(specs.precision - significand_size, 0); + size += num_zeros; + } else if (significand_size == 1) { + point = Char(); + } + size += (point ? 1 : 0) + compute_exp_size(exp); + char exp_char = specs.upper() ? 'E' : 'e'; + auto write = [=](reserve_iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + // Insert a decimal point after the first digit and add an exponent. + it = write_significand(it, f.significand, significand_size, 1, point); + if (num_zeros > 0) it = detail::fill_n(it, num_zeros, Char('0')); + *it++ = Char(exp_char); + return write_exponent(exp, it); + }; + auto usize = to_unsigned(size); + return specs.width > 0 + ? write_padded(out, specs, usize, write) + : base_iterator(out, write(reserve(out, usize))); +} + +template +FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f, + const format_specs& specs, sign s, + int exp_upper, locale_ref loc) -> OutputIt { + if (is_constant_evaluated()) { + return do_write_float>(out, f, specs, s, + exp_upper, loc); + } else { + return do_write_float>(out, f, specs, s, + exp_upper, loc); + } +} + +template constexpr auto isnan(T value) -> bool { + return value != value; // std::isnan doesn't support __float128. +} + +template +struct has_isfinite : std::false_type {}; + +template +struct has_isfinite> + : std::true_type {}; + +template ::value&& has_isfinite::value)> +FMT_CONSTEXPR20 auto isfinite(T value) -> bool { + constexpr T inf = T(std::numeric_limits::infinity()); + if (is_constant_evaluated()) + return !detail::isnan(value) && value < inf && value > -inf; + return std::isfinite(value); +} +template ::value)> +FMT_CONSTEXPR auto isfinite(T value) -> bool { + T inf = T(std::numeric_limits::infinity()); + // std::isfinite doesn't support __float128. + return !detail::isnan(value) && value < inf && value > -inf; +} + +template ::value)> +FMT_INLINE FMT_CONSTEXPR auto signbit(T value) -> bool { + if (is_constant_evaluated()) { +#ifdef __cpp_if_constexpr + if constexpr (std::numeric_limits::is_iec559) { + auto bits = detail::bit_cast(static_cast(value)); + return (bits >> (num_bits() - 1)) != 0; + } +#endif + } + return std::signbit(static_cast(value)); +} + +inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) { + // Adjust fixed precision by exponent because it is relative to decimal + // point. + if (exp10 > 0 && precision > max_value() - exp10) + FMT_THROW(format_error("number is too big")); + precision += exp10; +} + +class bigint { + private: + // A bigint is a number in the form bigit_[N - 1] ... bigit_[0] * 32^exp_. + using bigit = uint32_t; // A big digit. + using double_bigit = uint64_t; + enum { bigit_bits = num_bits() }; + enum { bigits_capacity = 32 }; + basic_memory_buffer bigits_; + int exp_; + + friend struct formatter; + + FMT_CONSTEXPR auto get_bigit(int i) const -> bigit { + return i >= exp_ && i < num_bigits() ? bigits_[i - exp_] : 0; + } + + FMT_CONSTEXPR void subtract_bigits(int index, bigit other, bigit& borrow) { + auto result = double_bigit(bigits_[index]) - other - borrow; + bigits_[index] = static_cast(result); + borrow = static_cast(result >> (bigit_bits * 2 - 1)); + } + + FMT_CONSTEXPR void remove_leading_zeros() { + int num_bigits = static_cast(bigits_.size()) - 1; + while (num_bigits > 0 && bigits_[num_bigits] == 0) --num_bigits; + bigits_.resize(to_unsigned(num_bigits + 1)); + } + + // Computes *this -= other assuming aligned bigints and *this >= other. + FMT_CONSTEXPR void subtract_aligned(const bigint& other) { + FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); + FMT_ASSERT(compare(*this, other) >= 0, ""); + bigit borrow = 0; + int i = other.exp_ - exp_; + for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j) + subtract_bigits(i, other.bigits_[j], borrow); + if (borrow != 0) subtract_bigits(i, 0, borrow); + FMT_ASSERT(borrow == 0, ""); + remove_leading_zeros(); + } + + FMT_CONSTEXPR void multiply(uint32_t value) { + bigit carry = 0; + const double_bigit wide_value = value; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * wide_value + carry; + bigits_[i] = static_cast(result); + carry = static_cast(result >> bigit_bits); + } + if (carry != 0) bigits_.push_back(carry); + } + + template ::value || + std::is_same::value)> + FMT_CONSTEXPR void multiply(UInt value) { + using half_uint = + conditional_t::value, uint64_t, uint32_t>; + const int shift = num_bits() - bigit_bits; + const UInt lower = static_cast(value); + const UInt upper = value >> num_bits(); + UInt carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + UInt result = lower * bigits_[i] + static_cast(carry); + carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) + + (carry >> bigit_bits); + bigits_[i] = static_cast(result); + } + while (carry != 0) { + bigits_.push_back(static_cast(carry)); + carry >>= bigit_bits; + } + } + + template ::value || + std::is_same::value)> + FMT_CONSTEXPR void assign(UInt n) { + size_t num_bigits = 0; + do { + bigits_[num_bigits++] = static_cast(n); + n >>= bigit_bits; + } while (n != 0); + bigits_.resize(num_bigits); + exp_ = 0; + } + + public: + FMT_CONSTEXPR bigint() : exp_(0) {} + explicit bigint(uint64_t n) { assign(n); } + + bigint(const bigint&) = delete; + void operator=(const bigint&) = delete; + + FMT_CONSTEXPR void assign(const bigint& other) { + auto size = other.bigits_.size(); + bigits_.resize(size); + auto data = other.bigits_.data(); + copy(data, data + size, bigits_.data()); + exp_ = other.exp_; + } + + template FMT_CONSTEXPR void operator=(Int n) { + FMT_ASSERT(n > 0, ""); + assign(uint64_or_128_t(n)); + } + + FMT_CONSTEXPR auto num_bigits() const -> int { + return static_cast(bigits_.size()) + exp_; + } + + FMT_CONSTEXPR auto operator<<=(int shift) -> bigint& { + FMT_ASSERT(shift >= 0, ""); + exp_ += shift / bigit_bits; + shift %= bigit_bits; + if (shift == 0) return *this; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + bigit c = bigits_[i] >> (bigit_bits - shift); + bigits_[i] = (bigits_[i] << shift) + carry; + carry = c; + } + if (carry != 0) bigits_.push_back(carry); + return *this; + } + + template FMT_CONSTEXPR auto operator*=(Int value) -> bigint& { + FMT_ASSERT(value > 0, ""); + multiply(uint32_or_64_or_128_t(value)); + return *this; + } + + friend FMT_CONSTEXPR auto compare(const bigint& b1, const bigint& b2) -> int { + int num_bigits1 = b1.num_bigits(), num_bigits2 = b2.num_bigits(); + if (num_bigits1 != num_bigits2) return num_bigits1 > num_bigits2 ? 1 : -1; + int i = static_cast(b1.bigits_.size()) - 1; + int j = static_cast(b2.bigits_.size()) - 1; + int end = i - j; + if (end < 0) end = 0; + for (; i >= end; --i, --j) { + bigit b1_bigit = b1.bigits_[i], b2_bigit = b2.bigits_[j]; + if (b1_bigit != b2_bigit) return b1_bigit > b2_bigit ? 1 : -1; + } + if (i != j) return i > j ? 1 : -1; + return 0; + } + + // Returns compare(lhs1 + lhs2, rhs). + friend FMT_CONSTEXPR auto add_compare(const bigint& lhs1, const bigint& lhs2, + const bigint& rhs) -> int { + int max_lhs_bigits = max_of(lhs1.num_bigits(), lhs2.num_bigits()); + int num_rhs_bigits = rhs.num_bigits(); + if (max_lhs_bigits + 1 < num_rhs_bigits) return -1; + if (max_lhs_bigits > num_rhs_bigits) return 1; + double_bigit borrow = 0; + int min_exp = min_of(min_of(lhs1.exp_, lhs2.exp_), rhs.exp_); + for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { + double_bigit sum = double_bigit(lhs1.get_bigit(i)) + lhs2.get_bigit(i); + bigit rhs_bigit = rhs.get_bigit(i); + if (sum > rhs_bigit + borrow) return 1; + borrow = rhs_bigit + borrow - sum; + if (borrow > 1) return -1; + borrow <<= bigit_bits; + } + return borrow != 0 ? -1 : 0; + } + + // Assigns pow(10, exp) to this bigint. + FMT_CONSTEXPR20 void assign_pow10(int exp) { + FMT_ASSERT(exp >= 0, ""); + if (exp == 0) return *this = 1; + int bitmask = 1 << (num_bits() - + countl_zero(static_cast(exp)) - 1); + // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by + // repeated squaring and multiplication. + *this = 5; + bitmask >>= 1; + while (bitmask != 0) { + square(); + if ((exp & bitmask) != 0) *this *= 5; + bitmask >>= 1; + } + *this <<= exp; // Multiply by pow(2, exp) by shifting. + } + + FMT_CONSTEXPR20 void square() { + int num_bigits = static_cast(bigits_.size()); + int num_result_bigits = 2 * num_bigits; + basic_memory_buffer n(std::move(bigits_)); + bigits_.resize(to_unsigned(num_result_bigits)); + auto sum = uint128_t(); + for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) { + // Compute bigit at position bigit_index of the result by adding + // cross-product terms n[i] * n[j] such that i + j == bigit_index. + for (int i = 0, j = bigit_index; j >= 0; ++i, --j) { + // Most terms are multiplied twice which can be optimized in the future. + sum += double_bigit(n[i]) * n[j]; + } + bigits_[bigit_index] = static_cast(sum); + sum >>= num_bits(); // Compute the carry. + } + // Do the same for the top half. + for (int bigit_index = num_bigits; bigit_index < num_result_bigits; + ++bigit_index) { + for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) + sum += double_bigit(n[i++]) * n[j--]; + bigits_[bigit_index] = static_cast(sum); + sum >>= num_bits(); + } + remove_leading_zeros(); + exp_ *= 2; + } + + // If this bigint has a bigger exponent than other, adds trailing zero to make + // exponents equal. This simplifies some operations such as subtraction. + FMT_CONSTEXPR void align(const bigint& other) { + int exp_difference = exp_ - other.exp_; + if (exp_difference <= 0) return; + int num_bigits = static_cast(bigits_.size()); + bigits_.resize(to_unsigned(num_bigits + exp_difference)); + for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j) + bigits_[j] = bigits_[i]; + fill_n(bigits_.data(), to_unsigned(exp_difference), 0U); + exp_ -= exp_difference; + } + + // Divides this bignum by divisor, assigning the remainder to this and + // returning the quotient. + FMT_CONSTEXPR auto divmod_assign(const bigint& divisor) -> int { + FMT_ASSERT(this != &divisor, ""); + if (compare(*this, divisor) < 0) return 0; + FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, ""); + align(divisor); + int quotient = 0; + do { + subtract_aligned(divisor); + ++quotient; + } while (compare(*this, divisor) >= 0); + return quotient; + } +}; + +// format_dragon flags. +enum dragon { + predecessor_closer = 1, + fixup = 2, // Run fixup to correct exp10 which can be off by one. + fixed = 4, +}; + +// Formats a floating-point number using a variation of the Fixed-Precision +// Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White: +// https://fmt.dev/papers/p372-steele.pdf. +FMT_CONSTEXPR20 inline void format_dragon(basic_fp value, + unsigned flags, int num_digits, + buffer& buf, int& exp10) { + bigint numerator; // 2 * R in (FPP)^2. + bigint denominator; // 2 * S in (FPP)^2. + // lower and upper are differences between value and corresponding boundaries. + bigint lower; // (M^- in (FPP)^2). + bigint upper_store; // upper's value if different from lower. + bigint* upper = nullptr; // (M^+ in (FPP)^2). + // Shift numerator and denominator by an extra bit or two (if lower boundary + // is closer) to make lower and upper integers. This eliminates multiplication + // by 2 during later computations. + bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0; + int shift = is_predecessor_closer ? 2 : 1; + if (value.e >= 0) { + numerator = value.f; + numerator <<= value.e + shift; + lower = 1; + lower <<= value.e; + if (is_predecessor_closer) { + upper_store = 1; + upper_store <<= value.e + 1; + upper = &upper_store; + } + denominator.assign_pow10(exp10); + denominator <<= shift; + } else if (exp10 < 0) { + numerator.assign_pow10(-exp10); + lower.assign(numerator); + if (is_predecessor_closer) { + upper_store.assign(numerator); + upper_store <<= 1; + upper = &upper_store; + } + numerator *= value.f; + numerator <<= shift; + denominator = 1; + denominator <<= shift - value.e; + } else { + numerator = value.f; + numerator <<= shift; + denominator.assign_pow10(exp10); + denominator <<= shift - value.e; + lower = 1; + if (is_predecessor_closer) { + upper_store = 1ULL << 1; + upper = &upper_store; + } + } + int even = static_cast((value.f & 1) == 0); + if (!upper) upper = &lower; + bool shortest = num_digits < 0; + if ((flags & dragon::fixup) != 0) { + if (add_compare(numerator, *upper, denominator) + even <= 0) { + --exp10; + numerator *= 10; + if (num_digits < 0) { + lower *= 10; + if (upper != &lower) *upper *= 10; + } + } + if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1); + } + // Invariant: value == (numerator / denominator) * pow(10, exp10). + if (shortest) { + // Generate the shortest representation. + num_digits = 0; + char* data = buf.data(); + for (;;) { + int digit = numerator.divmod_assign(denominator); + bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower. + // numerator + upper >[=] pow10: + bool high = add_compare(numerator, *upper, denominator) + even > 0; + data[num_digits++] = static_cast('0' + digit); + if (low || high) { + if (!low) { + ++data[num_digits - 1]; + } else if (high) { + int result = add_compare(numerator, numerator, denominator); + // Round half to even. + if (result > 0 || (result == 0 && (digit % 2) != 0)) + ++data[num_digits - 1]; + } + buf.try_resize(to_unsigned(num_digits)); + exp10 -= num_digits - 1; + return; + } + numerator *= 10; + lower *= 10; + if (upper != &lower) *upper *= 10; + } + } + // Generate the given number of digits. + exp10 -= num_digits - 1; + if (num_digits <= 0) { + auto digit = '0'; + if (num_digits == 0) { + denominator *= 10; + digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0'; + } + buf.push_back(digit); + return; + } + buf.try_resize(to_unsigned(num_digits)); + for (int i = 0; i < num_digits - 1; ++i) { + int digit = numerator.divmod_assign(denominator); + buf[i] = static_cast('0' + digit); + numerator *= 10; + } + int digit = numerator.divmod_assign(denominator); + auto result = add_compare(numerator, numerator, denominator); + if (result > 0 || (result == 0 && (digit % 2) != 0)) { + if (digit == 9) { + const auto overflow = '0' + 10; + buf[num_digits - 1] = overflow; + // Propagate the carry. + for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] == overflow) { + buf[0] = '1'; + if ((flags & dragon::fixed) != 0) + buf.push_back('0'); + else + ++exp10; + } + return; + } + ++digit; + } + buf[num_digits - 1] = static_cast('0' + digit); +} + +// Formats a floating-point number using the hexfloat format. +template ::value)> +FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs, + buffer& buf) { + // float is passed as double to reduce the number of instantiations and to + // simplify implementation. + static_assert(!std::is_same::value, ""); + + using info = dragonbox::float_info; + + // Assume Float is in the format [sign][exponent][significand]. + using carrier_uint = typename info::carrier_uint; + + const auto num_float_significand_bits = detail::num_significand_bits(); + + basic_fp f(value); + f.e += num_float_significand_bits; + if (!has_implicit_bit()) --f.e; + + const auto num_fraction_bits = + num_float_significand_bits + (has_implicit_bit() ? 1 : 0); + const auto num_xdigits = (num_fraction_bits + 3) / 4; + + const auto leading_shift = ((num_xdigits - 1) * 4); + const auto leading_mask = carrier_uint(0xF) << leading_shift; + const auto leading_xdigit = + static_cast((f.f & leading_mask) >> leading_shift); + if (leading_xdigit > 1) f.e -= (32 - countl_zero(leading_xdigit) - 1); + + int print_xdigits = num_xdigits - 1; + if (specs.precision >= 0 && print_xdigits > specs.precision) { + const int shift = ((print_xdigits - specs.precision - 1) * 4); + const auto mask = carrier_uint(0xF) << shift; + const auto v = static_cast((f.f & mask) >> shift); + + if (v >= 8) { + const auto inc = carrier_uint(1) << (shift + 4); + f.f += inc; + f.f &= ~(inc - 1); + } + + // Check long double overflow + if (!has_implicit_bit()) { + const auto implicit_bit = carrier_uint(1) << num_float_significand_bits; + if ((f.f & implicit_bit) == implicit_bit) { + f.f >>= 4; + f.e += 4; + } + } + + print_xdigits = specs.precision; + } + + char xdigits[num_bits() / 4]; + detail::fill_n(xdigits, sizeof(xdigits), '0'); + format_base2e(4, xdigits, f.f, num_xdigits, specs.upper()); + + // Remove zero tail + while (print_xdigits > 0 && xdigits[print_xdigits] == '0') --print_xdigits; + + buf.push_back('0'); + buf.push_back(specs.upper() ? 'X' : 'x'); + buf.push_back(xdigits[0]); + if (specs.alt() || print_xdigits > 0 || print_xdigits < specs.precision) + buf.push_back('.'); + buf.append(xdigits + 1, xdigits + 1 + print_xdigits); + for (; print_xdigits < specs.precision; ++print_xdigits) buf.push_back('0'); + + buf.push_back(specs.upper() ? 'P' : 'p'); + + uint32_t abs_e; + if (f.e < 0) { + buf.push_back('-'); + abs_e = static_cast(-f.e); + } else { + buf.push_back('+'); + abs_e = static_cast(f.e); + } + format_decimal(appender(buf), abs_e, detail::count_digits(abs_e)); +} + +template ::value)> +FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs, + buffer& buf) { + format_hexfloat(static_cast(value), specs, buf); +} + +constexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t { + // For checking rounding thresholds. + // The kth entry is chosen to be the smallest integer such that the + // upper 32-bits of 10^(k+1) times it is strictly bigger than 5 * 10^k. + // It is equal to ceil(2^31 + 2^32/10^(k + 1)). + // These are stored in a string literal because we cannot have static arrays + // in constexpr functions and non-static ones are poorly optimized. + return U"\x9999999a\x828f5c29\x80418938\x80068db9\x8000a7c6\x800010c7" + U"\x800001ae\x8000002b"[index]; +} + +template +FMT_CONSTEXPR20 auto format_float(Float value, int precision, + const format_specs& specs, bool binary32, + buffer& buf) -> int { + // float is passed as double to reduce the number of instantiations. + static_assert(!std::is_same::value, ""); + auto converted_value = convert_float(value); + + const bool fixed = specs.type() == presentation_type::fixed; + if (value == 0) { + if (precision <= 0 || !fixed) { + buf.push_back('0'); + return 0; + } + buf.try_resize(to_unsigned(precision)); + fill_n(buf.data(), precision, '0'); + return -precision; + } + + int exp = 0; + bool use_dragon = true; + unsigned dragon_flags = 0; + if (!is_fast_float() || is_constant_evaluated()) { + const auto inv_log2_10 = 0.3010299956639812; // 1 / log2(10) + using info = dragonbox::float_info; + const auto f = basic_fp(converted_value); + // Compute exp, an approximate power of 10, such that + // 10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1). + // This is based on log10(value) == log2(value) / log2(10) and approximation + // of log2(value) by e + num_fraction_bits idea from double-conversion. + auto e = (f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10; + exp = static_cast(e); + if (e > exp) ++exp; // Compute ceil. + dragon_flags = dragon::fixup; + } else { + // Extract significand bits and exponent bits. + using info = dragonbox::float_info; + auto br = bit_cast(static_cast(value)); + + const uint64_t significand_mask = + (static_cast(1) << num_significand_bits()) - 1; + uint64_t significand = (br & significand_mask); + int exponent = static_cast((br & exponent_mask()) >> + num_significand_bits()); + + if (exponent != 0) { // Check if normal. + exponent -= exponent_bias() + num_significand_bits(); + significand |= + (static_cast(1) << num_significand_bits()); + significand <<= 1; + } else { + // Normalize subnormal inputs. + FMT_ASSERT(significand != 0, "zeros should not appear here"); + int shift = countl_zero(significand); + FMT_ASSERT(shift >= num_bits() - num_significand_bits(), + ""); + shift -= (num_bits() - num_significand_bits() - 2); + exponent = (std::numeric_limits::min_exponent - + num_significand_bits()) - + shift; + significand <<= shift; + } + + // Compute the first several nonzero decimal significand digits. + // We call the number we get the first segment. + const int k = info::kappa - dragonbox::floor_log10_pow2(exponent); + exp = -k; + const int beta = exponent + dragonbox::floor_log2_pow10(k); + uint64_t first_segment; + bool has_more_segments; + int digits_in_the_first_segment; + { + const auto r = dragonbox::umul192_upper128( + significand << beta, dragonbox::get_cached_power(k)); + first_segment = r.high(); + has_more_segments = r.low() != 0; + + // The first segment can have 18 ~ 19 digits. + if (first_segment >= 1000000000000000000ULL) { + digits_in_the_first_segment = 19; + } else { + // When it is of 18-digits, we align it to 19-digits by adding a bogus + // zero at the end. + digits_in_the_first_segment = 18; + first_segment *= 10; + } + } + + // Compute the actual number of decimal digits to print. + if (fixed) adjust_precision(precision, exp + digits_in_the_first_segment); + + // Use Dragon4 only when there might be not enough digits in the first + // segment. + if (digits_in_the_first_segment > precision) { + use_dragon = false; + + if (precision <= 0) { + exp += digits_in_the_first_segment; + + if (precision < 0) { + // Nothing to do, since all we have are just leading zeros. + buf.try_resize(0); + } else { + // We may need to round-up. + buf.try_resize(1); + if ((first_segment | static_cast(has_more_segments)) > + 5000000000000000000ULL) { + buf[0] = '1'; + } else { + buf[0] = '0'; + } + } + } // precision <= 0 + else { + exp += digits_in_the_first_segment - precision; + + // When precision > 0, we divide the first segment into three + // subsegments, each with 9, 9, and 0 ~ 1 digits so that each fits + // in 32-bits which usually allows faster calculation than in + // 64-bits. Since some compiler (e.g. MSVC) doesn't know how to optimize + // division-by-constant for large 64-bit divisors, we do it here + // manually. The magic number 7922816251426433760 below is equal to + // ceil(2^(64+32) / 10^10). + const uint32_t first_subsegment = static_cast( + dragonbox::umul128_upper64(first_segment, 7922816251426433760ULL) >> + 32); + const uint64_t second_third_subsegments = + first_segment - first_subsegment * 10000000000ULL; + + uint64_t prod; + uint32_t digits; + bool should_round_up; + int number_of_digits_to_print = min_of(precision, 9); + + // Print a 9-digits subsegment, either the first or the second. + auto print_subsegment = [&](uint32_t subsegment, char* buffer) { + int number_of_digits_printed = 0; + + // If we want to print an odd number of digits from the subsegment, + if ((number_of_digits_to_print & 1) != 0) { + // Convert to 64-bit fixed-point fractional form with 1-digit + // integer part. The magic number 720575941 is a good enough + // approximation of 2^(32 + 24) / 10^8; see + // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case + // for details. + prod = ((subsegment * static_cast(720575941)) >> 24) + 1; + digits = static_cast(prod >> 32); + *buffer = static_cast('0' + digits); + number_of_digits_printed++; + } + // If we want to print an even number of digits from the + // first_subsegment, + else { + // Convert to 64-bit fixed-point fractional form with 2-digits + // integer part. The magic number 450359963 is a good enough + // approximation of 2^(32 + 20) / 10^7; see + // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case + // for details. + prod = ((subsegment * static_cast(450359963)) >> 20) + 1; + digits = static_cast(prod >> 32); + write2digits(buffer, digits); + number_of_digits_printed += 2; + } + + // Print all digit pairs. + while (number_of_digits_printed < number_of_digits_to_print) { + prod = static_cast(prod) * static_cast(100); + digits = static_cast(prod >> 32); + write2digits(buffer + number_of_digits_printed, digits); + number_of_digits_printed += 2; + } + }; + + // Print first subsegment. + print_subsegment(first_subsegment, buf.data()); + + // Perform rounding if the first subsegment is the last subsegment to + // print. + if (precision <= 9) { + // Rounding inside the subsegment. + // We round-up if: + // - either the fractional part is strictly larger than 1/2, or + // - the fractional part is exactly 1/2 and the last digit is odd. + // We rely on the following observations: + // - If fractional_part >= threshold, then the fractional part is + // strictly larger than 1/2. + // - If the MSB of fractional_part is set, then the fractional part + // must be at least 1/2. + // - When the MSB of fractional_part is set, either + // second_third_subsegments being nonzero or has_more_segments + // being true means there are further digits not printed, so the + // fractional part is strictly larger than 1/2. + if (precision < 9) { + uint32_t fractional_part = static_cast(prod); + should_round_up = + fractional_part >= fractional_part_rounding_thresholds( + 8 - number_of_digits_to_print) || + ((fractional_part >> 31) & + ((digits & 1) | (second_third_subsegments != 0) | + has_more_segments)) != 0; + } + // Rounding at the subsegment boundary. + // In this case, the fractional part is at least 1/2 if and only if + // second_third_subsegments >= 5000000000ULL, and is strictly larger + // than 1/2 if we further have either second_third_subsegments > + // 5000000000ULL or has_more_segments == true. + else { + should_round_up = second_third_subsegments > 5000000000ULL || + (second_third_subsegments == 5000000000ULL && + ((digits & 1) != 0 || has_more_segments)); + } + } + // Otherwise, print the second subsegment. + else { + // Compilers are not aware of how to leverage the maximum value of + // second_third_subsegments to find out a better magic number which + // allows us to eliminate an additional shift. 1844674407370955162 = + // ceil(2^64/10) < ceil(2^64*(10^9/(10^10 - 1))). + const uint32_t second_subsegment = + static_cast(dragonbox::umul128_upper64( + second_third_subsegments, 1844674407370955162ULL)); + const uint32_t third_subsegment = + static_cast(second_third_subsegments) - + second_subsegment * 10; + + number_of_digits_to_print = precision - 9; + print_subsegment(second_subsegment, buf.data() + 9); + + // Rounding inside the subsegment. + if (precision < 18) { + // The condition third_subsegment != 0 implies that the segment was + // of 19 digits, so in this case the third segment should be + // consisting of a genuine digit from the input. + uint32_t fractional_part = static_cast(prod); + should_round_up = + fractional_part >= fractional_part_rounding_thresholds( + 8 - number_of_digits_to_print) || + ((fractional_part >> 31) & + ((digits & 1) | (third_subsegment != 0) | + has_more_segments)) != 0; + } + // Rounding at the subsegment boundary. + else { + // In this case, the segment must be of 19 digits, thus + // the third subsegment should be consisting of a genuine digit from + // the input. + should_round_up = third_subsegment > 5 || + (third_subsegment == 5 && + ((digits & 1) != 0 || has_more_segments)); + } + } + + // Round-up if necessary. + if (should_round_up) { + ++buf[precision - 1]; + for (int i = precision - 1; i > 0 && buf[i] > '9'; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] > '9') { + buf[0] = '1'; + if (fixed) + buf[precision++] = '0'; + else + ++exp; + } + } + buf.try_resize(to_unsigned(precision)); + } + } // if (digits_in_the_first_segment > precision) + else { + // Adjust the exponent for its use in Dragon4. + exp += digits_in_the_first_segment - 1; + } + } + if (use_dragon) { + auto f = basic_fp(); + bool is_predecessor_closer = binary32 ? f.assign(static_cast(value)) + : f.assign(converted_value); + if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer; + if (fixed) dragon_flags |= dragon::fixed; + // Limit precision to the maximum possible number of significant digits in + // an IEEE754 double because we don't need to generate zeros. + const int max_double_digits = 767; + if (precision > max_double_digits) precision = max_double_digits; + format_dragon(f, dragon_flags, precision, buf, exp); + } + if (!fixed && !specs.alt()) { + // Remove trailing zeros. + auto num_digits = buf.size(); + while (num_digits > 0 && buf[num_digits - 1] == '0') { + --num_digits; + ++exp; + } + buf.try_resize(num_digits); + } + return exp; +} + +template ::value)> +FMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs, + locale_ref loc = {}) -> OutputIt { + if (specs.localized() && write_loc(out, value, specs, loc)) return out; + + // Use signbit because value < 0 is false for NaN. + sign s = detail::signbit(value) ? sign::minus : specs.sign(); + + if (!detail::isfinite(value)) + return write_nonfinite(out, detail::isnan(value), specs, s); + + if (specs.align() == align::numeric && s != sign::none) { + *out++ = detail::getsign(s); + s = sign::none; + if (specs.width != 0) --specs.width; + } + + const int exp_upper = detail::exp_upper(); + int precision = specs.precision; + if (precision < 0) { + if (specs.type() != presentation_type::none) { + precision = 6; + } else if (is_fast_float::value && !is_constant_evaluated()) { + // Use Dragonbox for the shortest format. + auto dec = dragonbox::to_decimal(static_cast>(value)); + return write_float(out, dec, specs, s, exp_upper, loc); + } + } + + memory_buffer buffer; + if (specs.type() == presentation_type::hexfloat) { + if (s != sign::none) buffer.push_back(detail::getsign(s)); + format_hexfloat(convert_float(value), specs, buffer); + return write_bytes(out, {buffer.data(), buffer.size()}, + specs); + } + + if (specs.type() == presentation_type::exp) { + if (precision == max_value()) + report_error("number is too big"); + else + ++precision; + if (specs.precision != 0) specs.set_alt(); + } else if (specs.type() == presentation_type::fixed) { + if (specs.precision != 0) specs.set_alt(); + } else if (precision == 0) { + precision = 1; + } + int exp = format_float(convert_float(value), precision, specs, + std::is_same(), buffer); + + specs.precision = precision; + auto f = big_decimal_fp{buffer.data(), static_cast(buffer.size()), exp}; + return write_float(out, f, specs, s, exp_upper, loc); +} + +template ::value)> +FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt { + if (is_constant_evaluated()) return write(out, value, format_specs()); + + auto s = detail::signbit(value) ? sign::minus : sign::none; + auto mask = exponent_mask>(); + if ((bit_cast(value) & mask) == mask) + return write_nonfinite(out, std::isnan(value), {}, s); + + auto dec = dragonbox::to_decimal(static_cast>(value)); + auto significand = dec.significand; + int significand_size = count_digits(significand); + int exponent = dec.exponent + significand_size - 1; + if (use_fixed(exponent, detail::exp_upper())) { + return write_fixed>( + out, dec, significand_size, Char('.'), {}, s); + } + + // Write value in the exponential format. + const char* prefix = "e+"; + int abs_exponent = exponent; + if (exponent < 0) { + abs_exponent = -exponent; + prefix = "e-"; + } + auto has_decimal_point = significand_size != 1; + size_t size = std::is_pointer::value + ? 0u + : to_unsigned((s != sign::none ? 1 : 0) + significand_size + + (has_decimal_point ? 1 : 0) + + (abs_exponent >= 100 ? 5 : 4)); + if (auto ptr = to_pointer(out, size)) { + if (s != sign::none) *ptr++ = Char('-'); + if (has_decimal_point) { + auto begin = ptr; + ptr = format_decimal(ptr, significand, significand_size + 1); + *begin = begin[1]; + begin[1] = '.'; + } else { + *ptr++ = static_cast('0' + significand); + } + if (std::is_same::value) { + memcpy(ptr, prefix, 2); + ptr += 2; + } else { + *ptr++ = prefix[0]; + *ptr++ = prefix[1]; + } + if (abs_exponent >= 100) { + *ptr++ = static_cast('0' + abs_exponent / 100); + abs_exponent %= 100; + } + write2digits(ptr, static_cast(abs_exponent)); + return select::value>(ptr + 2, out); + } + auto it = reserve(out, size); + if (s != sign::none) *it++ = Char('-'); + // Insert a decimal point after the first digit and add an exponent. + it = write_significand(it, significand, significand_size, 1, + has_decimal_point ? Char('.') : Char()); + *it++ = Char('e'); + it = write_exponent(exponent, it); + return base_iterator(out, it); +} + +template ::value && + !is_fast_float::value)> +inline auto write(OutputIt out, T value) -> OutputIt { + return write(out, value, {}); +} + +template +auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {}) + -> OutputIt { + FMT_ASSERT(false, ""); + return out; +} + +template +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view value) + -> OutputIt { + return copy_noinline(value.begin(), value.end(), out); +} + +template ::value)> +constexpr auto write(OutputIt out, const T& value) -> OutputIt { + return write(out, to_string_view(value)); +} + +// FMT_ENABLE_IF() condition separated to workaround an MSVC bug. +template < + typename Char, typename OutputIt, typename T, + bool check = std::is_enum::value && !std::is_same::value && + mapped_type_constant::value != type::custom_type, + FMT_ENABLE_IF(check)> +FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { + return write(out, static_cast>(value)); +} + +template ::value)> +FMT_CONSTEXPR auto write(OutputIt out, T value, const format_specs& specs = {}, + locale_ref = {}) -> OutputIt { + return specs.type() != presentation_type::none && + specs.type() != presentation_type::string + ? write(out, value ? 1 : 0, specs, {}) + : write_bytes(out, value ? "true" : "false", specs); +} + +template +FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt { + auto it = reserve(out, 1); + *it++ = value; + return base_iterator(out, it); +} + +template +FMT_CONSTEXPR20 auto write(OutputIt out, const Char* value) -> OutputIt { + if (value) return write(out, basic_string_view(value)); + report_error("string pointer is null"); + return out; +} + +template ::value)> +auto write(OutputIt out, const T* value, const format_specs& specs = {}, + locale_ref = {}) -> OutputIt { + return write_ptr(out, bit_cast(value), &specs); +} + +template ::value == + type::custom_type && + !std::is_fundamental::value)> +FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> OutputIt { + auto f = formatter(); + auto parse_ctx = parse_context({}); + f.parse(parse_ctx); + auto ctx = basic_format_context(out, {}, {}); + return f.format(value, ctx); +} + +template +using is_builtin = + bool_constant::value || FMT_BUILTIN_TYPES>; + +// An argument visitor that formats the argument and writes it via the output +// iterator. It's a class and not a generic lambda for compatibility with C++11. +template struct default_arg_formatter { + using context = buffered_context; + + basic_appender out; + + void operator()(monostate) { report_error("argument not found"); } + + template ::value)> + void operator()(T value) { + write(out, value); + } + + template ::value)> + void operator()(T) { + FMT_ASSERT(false, ""); + } + + void operator()(typename basic_format_arg::handle h) { + // Use a null locale since the default format must be unlocalized. + auto parse_ctx = parse_context({}); + auto format_ctx = context(out, {}, {}); + h.format(parse_ctx, format_ctx); + } +}; + +template struct arg_formatter { + basic_appender out; + const format_specs& specs; + FMT_NO_UNIQUE_ADDRESS locale_ref locale; + + template ::value)> + FMT_CONSTEXPR FMT_INLINE void operator()(T value) { + detail::write(out, value, specs, locale); + } + + template ::value)> + void operator()(T) { + FMT_ASSERT(false, ""); + } + + void operator()(typename basic_format_arg>::handle) { + // User-defined types are handled separately because they require access + // to the parse context. + } +}; + +struct dynamic_spec_getter { + template ::value)> + FMT_CONSTEXPR auto operator()(T value) -> unsigned long long { + return is_negative(value) ? ~0ull : static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR auto operator()(T) -> unsigned long long { + report_error("width/precision is not integer"); + return 0; + } +}; + +template +FMT_CONSTEXPR void handle_dynamic_spec( + arg_id_kind kind, int& value, + const arg_ref& ref, Context& ctx) { + if (kind == arg_id_kind::none) return; + auto arg = + kind == arg_id_kind::index ? ctx.arg(ref.index) : ctx.arg(ref.name); + if (!arg) report_error("argument not found"); + unsigned long long result = arg.visit(dynamic_spec_getter()); + if (result > to_unsigned(max_value())) + report_error("width/precision is out of range"); + value = static_cast(result); +} + +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template Str> +struct static_named_arg : view { + static constexpr auto name = Str.data; + + const T& value; + static_named_arg(const T& v) : value(v) {} +}; + +template Str> +struct is_named_arg> : std::true_type {}; + +template Str> +struct is_static_named_arg> : std::true_type { +}; + +template Str> +struct udl_arg { + template auto operator=(T&& value) const { + return static_named_arg(std::forward(value)); + } +}; +#else +template struct udl_arg { + const Char* str; + + template auto operator=(T&& value) const -> named_arg { + return {str, std::forward(value)}; + } +}; +#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS + +template struct format_handler { + parse_context parse_ctx; + buffered_context ctx; + + void on_text(const Char* begin, const Char* end) { + copy_noinline(begin, end, ctx.out()); + } + + FMT_CONSTEXPR auto on_arg_id() -> int { return parse_ctx.next_arg_id(); } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + parse_ctx.check_arg_id(id); + return id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { + parse_ctx.check_arg_id(id); + int arg_id = ctx.arg_id(id); + if (arg_id < 0) report_error("argument not found"); + return arg_id; + } + + FMT_INLINE void on_replacement_field(int id, const Char*) { + ctx.arg(id).visit(default_arg_formatter{ctx.out()}); + } + + auto on_format_specs(int id, const Char* begin, const Char* end) + -> const Char* { + auto arg = ctx.arg(id); + if (!arg) report_error("argument not found"); + // Not using a visitor for custom types gives better codegen. + if (arg.format_custom(begin, parse_ctx, ctx)) return parse_ctx.begin(); + + auto specs = dynamic_format_specs(); + begin = parse_format_specs(begin, end, specs, parse_ctx, arg.type()); + if (specs.dynamic()) { + handle_dynamic_spec(specs.dynamic_width(), specs.width, specs.width_ref, + ctx); + handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + } + + arg.visit(arg_formatter{ctx.out(), specs, ctx.locale()}); + return begin; + } + + FMT_NORETURN void on_error(const char* message) { report_error(message); } +}; + +// It is used in format-inl.h and os.cc. +using format_func = void (*)(detail::buffer&, int, const char*); +FMT_API void do_report_error(format_func func, int error_code, + const char* message) noexcept; + +FMT_API void format_error_code(buffer& out, int error_code, + string_view message) noexcept; + +template +template +FMT_CONSTEXPR auto native_formatter::format( + const T& val, FormatContext& ctx) const -> decltype(ctx.out()) { + if (!specs_.dynamic()) + return write(ctx.out(), val, specs_, ctx.locale()); + auto specs = format_specs(specs_); + handle_dynamic_spec(specs.dynamic_width(), specs.width, specs_.width_ref, + ctx); + handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs_.precision_ref, ctx); + return write(ctx.out(), val, specs, ctx.locale()); +} +} // namespace detail + +FMT_BEGIN_EXPORT + +// A generic formatting context with custom output iterator and character +// (code unit) support. Char is the format string code unit type which can be +// different from OutputIt::value_type. +template class generic_context { + private: + OutputIt out_; + basic_format_args args_; + locale_ref loc_; + + public: + using char_type = Char; + using iterator = OutputIt; + enum { builtin_types = FMT_BUILTIN_TYPES }; + + constexpr generic_context(OutputIt out, + basic_format_args args, + locale_ref loc = {}) + : out_(out), args_(args), loc_(loc) {} + generic_context(generic_context&&) = default; + generic_context(const generic_context&) = delete; + void operator=(const generic_context&) = delete; + + constexpr auto arg(int id) const -> basic_format_arg { + return args_.get(id); + } + auto arg(basic_string_view name) const + -> basic_format_arg { + return args_.get(name); + } + constexpr auto arg_id(basic_string_view name) const -> int { + return args_.get_id(name); + } + + constexpr auto out() const -> iterator { return out_; } + + void advance_to(iterator it) { + if (!detail::is_back_insert_iterator()) out_ = it; + } + + constexpr auto locale() const -> locale_ref { return loc_; } +}; + +class loc_value { + private: + basic_format_arg value_; + + public: + template ::value)> + loc_value(T value) : value_(value) {} + + template ::value)> + loc_value(T) {} + + template auto visit(Visitor&& vis) -> decltype(vis(0)) { + return value_.visit(vis); + } +}; + +// A locale facet that formats values in UTF-8. +// It is parameterized on the locale to avoid the heavy include. +template class format_facet : public Locale::facet { + private: + std::string separator_; + std::string grouping_; + std::string decimal_point_; + + protected: + virtual auto do_put(appender out, loc_value val, + const format_specs& specs) const -> bool; + + public: + static FMT_API typename Locale::id id; + + explicit format_facet(Locale& loc); + explicit format_facet(string_view sep = "", std::string grouping = "\3", + std::string decimal_point = ".") + : separator_(sep.data(), sep.size()), + grouping_(grouping), + decimal_point_(decimal_point) {} + + auto put(appender out, loc_value val, const format_specs& specs) const + -> bool { + return do_put(out, val, specs); + } +}; + +#define FMT_FORMAT_AS(Type, Base) \ + template \ + struct formatter : formatter { \ + template \ + FMT_CONSTEXPR auto format(Type value, FormatContext& ctx) const \ + -> decltype(ctx.out()) { \ + return formatter::format(value, ctx); \ + } \ + } + +FMT_FORMAT_AS(signed char, int); +FMT_FORMAT_AS(unsigned char, unsigned); +FMT_FORMAT_AS(short, int); +FMT_FORMAT_AS(unsigned short, unsigned); +FMT_FORMAT_AS(long, detail::long_type); +FMT_FORMAT_AS(unsigned long, detail::ulong_type); +FMT_FORMAT_AS(Char*, const Char*); +FMT_FORMAT_AS(detail::std_string_view, basic_string_view); +FMT_FORMAT_AS(std::nullptr_t, const void*); +FMT_FORMAT_AS(void*, const void*); + +template +struct formatter : formatter, Char> {}; + +template +class formatter, Char> + : public formatter, Char> {}; + +template +struct formatter, Char> : formatter {}; +template +struct formatter, Char> + : formatter {}; + +template +struct formatter + : detail::native_formatter {}; + +template +struct formatter>> + : formatter, Char> { + template + FMT_CONSTEXPR auto format(const T& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto&& val = format_as(value); // Make an lvalue reference for format. + return formatter, Char>::format(val, ctx); + } +}; + +/** + * Converts `p` to `const void*` for pointer formatting. + * + * **Example**: + * + * auto s = fmt::format("{}", fmt::ptr(p)); + */ +template auto ptr(T p) -> const void* { + static_assert(std::is_pointer::value, "fmt::ptr used with non-pointer"); + return detail::bit_cast(p); +} + +/** + * Converts `e` to the underlying type. + * + * **Example**: + * + * enum class color { red, green, blue }; + * auto s = fmt::format("{}", fmt::underlying(color::red)); // s == "0" + */ +template +constexpr auto underlying(Enum e) noexcept -> underlying_t { + return static_cast>(e); +} + +namespace enums { +template ::value)> +constexpr auto format_as(Enum e) noexcept -> underlying_t { + return static_cast>(e); +} +} // namespace enums + +#ifdef __cpp_lib_byte +template +struct formatter : formatter { + static auto format_as(std::byte b) -> unsigned char { + return static_cast(b); + } + template + auto format(std::byte b, Context& ctx) const -> decltype(ctx.out()) { + return formatter::format(format_as(b), ctx); + } +}; +#endif + +struct bytes { + string_view data; + + inline explicit bytes(string_view s) : data(s) {} +}; + +template <> struct formatter { + private: + detail::dynamic_format_specs<> specs_; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type::string_type); + } + + template + auto format(bytes b, FormatContext& ctx) const -> decltype(ctx.out()) { + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + return detail::write_bytes(ctx.out(), b.data, specs); + } +}; + +// group_digits_view is not derived from view because it copies the argument. +template struct group_digits_view { + T value; +}; + +/** + * Returns a view that formats an integer value using ',' as a + * locale-independent thousands separator. + * + * **Example**: + * + * fmt::print("{}", fmt::group_digits(12345)); + * // Output: "12,345" + */ +template auto group_digits(T value) -> group_digits_view { + return {value}; +} + +template struct formatter> : formatter { + private: + detail::dynamic_format_specs<> specs_; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type::int_type); + } + + template + auto format(group_digits_view view, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + auto arg = detail::make_write_int_arg(view.value, specs.sign()); + return detail::write_int( + ctx.out(), static_cast>(arg.abs_value), + arg.prefix, specs, detail::digit_grouping("\3", ",")); + } +}; + +template struct nested_view { + const formatter* fmt; + const T* value; +}; + +template +struct formatter, Char> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return ctx.begin(); + } + template + auto format(nested_view view, FormatContext& ctx) const + -> decltype(ctx.out()) { + return view.fmt->format(*view.value, ctx); + } +}; + +template struct nested_formatter { + private: + basic_specs specs_; + int width_; + formatter formatter_; + + public: + constexpr nested_formatter() : width_(0) {} + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + auto specs = format_specs(); + it = detail::parse_align(it, end, specs); + specs_ = specs; + Char c = *it; + auto width_ref = detail::arg_ref(); + if ((c >= '0' && c <= '9') || c == '{') { + it = detail::parse_width(it, end, specs, width_ref, ctx); + width_ = specs.width; + } + ctx.advance_to(it); + return formatter_.parse(ctx); + } + + template + auto write_padded(FormatContext& ctx, F write) const -> decltype(ctx.out()) { + if (width_ == 0) return write(ctx.out()); + auto buf = basic_memory_buffer(); + write(basic_appender(buf)); + auto specs = format_specs(); + specs.width = width_; + specs.copy_fill_from(specs_); + specs.set_align(specs_.align()); + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); + } + + auto nested(const T& value) const -> nested_view { + return nested_view{&formatter_, &value}; + } +}; + +inline namespace literals { +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template constexpr auto operator""_a() { + using char_t = remove_cvref_t; + return detail::udl_arg(); +} +#else +/** + * User-defined literal equivalent of `fmt::arg`. + * + * **Example**: + * + * using namespace fmt::literals; + * fmt::print("The answer is {answer}.", "answer"_a=42); + */ +constexpr auto operator""_a(const char* s, size_t) -> detail::udl_arg { + return {s}; +} +#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS +} // namespace literals + +/// A fast integer formatter. +class format_int { + private: + // Buffer should be large enough to hold all digits (digits10 + 1), + // a sign and a null character. + enum { buffer_size = std::numeric_limits::digits10 + 3 }; + mutable char buffer_[buffer_size]; + char* str_; + + template + FMT_CONSTEXPR20 auto format_unsigned(UInt value) -> char* { + auto n = static_cast>(value); + return detail::do_format_decimal(buffer_, n, buffer_size - 1); + } + + template + FMT_CONSTEXPR20 auto format_signed(Int value) -> char* { + auto abs_value = static_cast>(value); + bool negative = value < 0; + if (negative) abs_value = 0 - abs_value; + auto begin = format_unsigned(abs_value); + if (negative) *--begin = '-'; + return begin; + } + + public: + FMT_CONSTEXPR20 explicit format_int(int value) : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(long value) + : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(long long value) + : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned value) + : str_(format_unsigned(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned long value) + : str_(format_unsigned(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned long long value) + : str_(format_unsigned(value)) {} + + /// Returns the number of characters written to the output buffer. + FMT_CONSTEXPR20 auto size() const -> size_t { + return detail::to_unsigned(buffer_ - str_ + buffer_size - 1); + } + + /// Returns a pointer to the output buffer content. No terminating null + /// character is appended. + FMT_CONSTEXPR20 auto data() const -> const char* { return str_; } + + /// Returns a pointer to the output buffer content with terminating null + /// character appended. + FMT_CONSTEXPR20 auto c_str() const -> const char* { + buffer_[buffer_size - 1] = '\0'; + return str_; + } + + /// Returns the content of the output buffer as an `std::string`. + inline auto str() const -> std::string { return {str_, size()}; } +}; + +#if FMT_CLANG_ANALYZER +# define FMT_STRING_IMPL(s, base) s +#else +# define FMT_STRING_IMPL(s, base) \ + [] { \ + /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \ + /* Use a macro-like name to avoid shadowing warnings. */ \ + struct FMT_VISIBILITY("hidden") FMT_COMPILE_STRING : base { \ + using char_type = fmt::remove_cvref_t; \ + constexpr explicit operator fmt::basic_string_view() \ + const { \ + return fmt::detail::compile_string_to_view(s); \ + } \ + }; \ + using FMT_STRING_VIEW = \ + fmt::basic_string_view; \ + fmt::detail::ignore_unused(FMT_STRING_VIEW(FMT_COMPILE_STRING())); \ + return FMT_COMPILE_STRING(); \ + }() +#endif // FMT_CLANG_ANALYZER + +/** + * Constructs a legacy compile-time format string from a string literal `s`. + * + * **Example**: + * + * // A compile-time error because 'd' is an invalid specifier for strings. + * std::string s = fmt::format(FMT_STRING("{:d}"), "foo"); + */ +#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string) + +FMT_API auto vsystem_error(int error_code, string_view fmt, format_args args) + -> std::system_error; + +/** + * Constructs `std::system_error` with a message formatted with + * `fmt::format(fmt, args...)`. + * `error_code` is a system error code as given by `errno`. + * + * **Example**: + * + * // This throws std::system_error with the description + * // cannot open file 'madeup': No such file or directory + * // or similar (system message may vary). + * const char* filename = "madeup"; + * FILE* file = fopen(filename, "r"); + * if (!file) + * throw fmt::system_error(errno, "cannot open file '{}'", filename); + */ +template +auto system_error(int error_code, format_string fmt, T&&... args) + -> std::system_error { + return vsystem_error(error_code, fmt.str, vargs{{args...}}); +} + +/** + * Formats an error message for an error returned by an operating system or a + * language runtime, for example a file opening error, and writes it to `out`. + * The format is the same as the one used by `std::system_error(ec, message)` + * where `ec` is `std::error_code(error_code, std::generic_category())`. + * It is implementation-defined but normally looks like: + * + * : + * + * where `` is the passed message and `` is the system + * message corresponding to the error code. + * `error_code` is a system error code as given by `errno`. + */ +FMT_API void format_system_error(detail::buffer& out, int error_code, + const char* message) noexcept; + +// Reports a system error without throwing an exception. +// Can be used to report errors from destructors. +FMT_API void report_system_error(int error_code, const char* message) noexcept; + +inline auto vformat(locale_ref loc, string_view fmt, format_args args) + -> std::string { + auto buf = memory_buffer(); + detail::vformat_to(buf, fmt, args, loc); + return {buf.data(), buf.size()}; +} + +template +FMT_INLINE auto format(locale_ref loc, format_string fmt, T&&... args) + -> std::string { + return vformat(loc, fmt.str, vargs{{args...}}); +} + +template ::value)> +auto vformat_to(OutputIt out, locale_ref loc, string_view fmt, format_args args) + -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, fmt, args, loc); + return detail::get_iterator(buf, out); +} + +template ::value)> +FMT_INLINE auto format_to(OutputIt out, locale_ref loc, format_string fmt, + T&&... args) -> OutputIt { + return fmt::vformat_to(out, loc, fmt.str, vargs{{args...}}); +} + +template +FMT_NODISCARD FMT_INLINE auto formatted_size(locale_ref loc, + format_string fmt, + T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + detail::vformat_to(buf, fmt.str, vargs{{args...}}, loc); + return buf.count(); +} + +FMT_API auto vformat(string_view fmt, format_args args) -> std::string; + +/** + * Formats `args` according to specifications in `fmt` and returns the result + * as a string. + * + * **Example**: + * + * #include + * std::string message = fmt::format("The answer is {}.", 42); + */ +template +FMT_NODISCARD FMT_INLINE auto format(format_string fmt, T&&... args) + -> std::string { + return vformat(fmt.str, vargs{{args...}}); +} + +/** + * Converts `value` to `std::string` using the default format for type `T`. + * + * **Example**: + * + * std::string answer = fmt::to_string(42); + */ +template ::value)> +FMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(T value) -> std::string { + // The buffer should be large enough to store the number including the sign + // or "false" for bool. + char buffer[max_of(detail::digits10() + 2, 5)]; + return {buffer, detail::write(buffer, value)}; +} + +template ::value)> +FMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(const T& value) + -> std::string { + return to_string(format_as(value)); +} + +template ::value && + !detail::use_format_as::value)> +FMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(const T& value) + -> std::string { + auto buffer = memory_buffer(); + detail::write(appender(buffer), value); + return {buffer.data(), buffer.size()}; +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#ifdef FMT_HEADER_ONLY +# define FMT_FUNC inline +# include "format-inl.h" +#endif + +// Restore _LIBCPP_REMOVE_TRANSITIVE_INCLUDES. +#ifdef FMT_REMOVE_TRANSITIVE_INCLUDES +# undef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +#endif + +#endif // FMT_FORMAT_H_ diff --git a/vendor/btop/include/fmt/os.h b/vendor/btop/include/fmt/os.h new file mode 100644 index 000000000..40cdcdd4f --- /dev/null +++ b/vendor/btop/include/fmt/os.h @@ -0,0 +1,428 @@ +// Formatting library for C++ - optional OS-specific functionality +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_OS_H_ +#define FMT_OS_H_ + +#include "format.h" + +#ifndef FMT_MODULE +# include +# include +# include +# include // std::system_error + +# if FMT_HAS_INCLUDE() +# include // LC_NUMERIC_MASK on macOS +# endif +#endif // FMT_MODULE + +#ifndef FMT_USE_FCNTL +// UWP doesn't provide _pipe. +# if FMT_HAS_INCLUDE("winapifamily.h") +# include +# endif +# if (FMT_HAS_INCLUDE() || defined(__APPLE__) || \ + defined(__linux__)) && \ + (!defined(WINAPI_FAMILY) || \ + (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) && \ + !defined(__wasm__) +# include // for O_RDONLY +# define FMT_USE_FCNTL 1 +# else +# define FMT_USE_FCNTL 0 +# endif +#endif + +#ifndef FMT_POSIX +# if defined(_WIN32) && !defined(__MINGW32__) +// Fix warnings about deprecated symbols. +# define FMT_POSIX(call) _##call +# else +# define FMT_POSIX(call) call +# endif +#endif + +// Calls to system functions are wrapped in FMT_SYSTEM for testability. +#ifdef FMT_SYSTEM +# define FMT_HAS_SYSTEM +# define FMT_POSIX_CALL(call) FMT_SYSTEM(call) +#else +# define FMT_SYSTEM(call) ::call +# ifdef _WIN32 +// Fix warnings about deprecated symbols. +# define FMT_POSIX_CALL(call) ::_##call +# else +# define FMT_POSIX_CALL(call) ::call +# endif +#endif + +// Retries the expression while it evaluates to error_result and errno +// equals to EINTR. +#ifndef _WIN32 +# define FMT_RETRY_VAL(result, expression, error_result) \ + do { \ + (result) = (expression); \ + } while ((result) == (error_result) && errno == EINTR) +#else +# define FMT_RETRY_VAL(result, expression, error_result) result = (expression) +#endif + +#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1) + +FMT_BEGIN_NAMESPACE +FMT_BEGIN_EXPORT + +/** + * A reference to a null-terminated string. It can be constructed from a C + * string or `std::string`. + * + * You can use one of the following type aliases for common character types: + * + * +---------------+-----------------------------+ + * | Type | Definition | + * +===============+=============================+ + * | cstring_view | basic_cstring_view | + * +---------------+-----------------------------+ + * | wcstring_view | basic_cstring_view | + * +---------------+-----------------------------+ + * + * This class is most useful as a parameter type for functions that wrap C APIs. + */ +template class basic_cstring_view { + private: + const Char* data_; + + public: + /// Constructs a string reference object from a C string. + basic_cstring_view(const Char* s) : data_(s) {} + + /// Constructs a string reference from an `std::string` object. + basic_cstring_view(const std::basic_string& s) : data_(s.c_str()) {} + + /// Returns the pointer to a C string. + auto c_str() const -> const Char* { return data_; } +}; + +using cstring_view = basic_cstring_view; +using wcstring_view = basic_cstring_view; + +#ifdef _WIN32 +FMT_API const std::error_category& system_category() noexcept; + +namespace detail { +FMT_API void format_windows_error(buffer& out, int error_code, + const char* message) noexcept; +} + +FMT_API std::system_error vwindows_error(int error_code, string_view fmt, + format_args args); + +/** + * Constructs a `std::system_error` object with the description of the form + * + * : + * + * where `` is the formatted message and `` is the + * system message corresponding to the error code. + * `error_code` is a Windows error code as given by `GetLastError`. + * If `error_code` is not a valid error code such as -1, the system message + * will look like "error -1". + * + * **Example**: + * + * // This throws a system_error with the description + * // cannot open file 'madeup': The system cannot find the file + * specified. + * // or similar (system message may vary). + * const char *filename = "madeup"; + * LPOFSTRUCT of = LPOFSTRUCT(); + * HFILE file = OpenFile(filename, &of, OF_READ); + * if (file == HFILE_ERROR) { + * throw fmt::windows_error(GetLastError(), + * "cannot open file '{}'", filename); + * } + */ +template +auto windows_error(int error_code, string_view message, const T&... args) + -> std::system_error { + return vwindows_error(error_code, message, vargs{{args...}}); +} + +// Reports a Windows error without throwing an exception. +// Can be used to report errors from destructors. +FMT_API void report_windows_error(int error_code, const char* message) noexcept; +#else +inline auto system_category() noexcept -> const std::error_category& { + return std::system_category(); +} +#endif // _WIN32 + +// std::system is not available on some platforms such as iOS (#2248). +#ifdef __OSX__ +template > +void say(const S& fmt, Args&&... args) { + std::system(format("say \"{}\"", format(fmt, args...)).c_str()); +} +#endif + +// A buffered file. +class buffered_file { + private: + FILE* file_; + + friend class file; + + inline explicit buffered_file(FILE* f) : file_(f) {} + + public: + buffered_file(const buffered_file&) = delete; + void operator=(const buffered_file&) = delete; + + // Constructs a buffered_file object which doesn't represent any file. + inline buffered_file() noexcept : file_(nullptr) {} + + // Destroys the object closing the file it represents if any. + FMT_API ~buffered_file() noexcept; + + public: + inline buffered_file(buffered_file&& other) noexcept : file_(other.file_) { + other.file_ = nullptr; + } + + inline auto operator=(buffered_file&& other) -> buffered_file& { + close(); + file_ = other.file_; + other.file_ = nullptr; + return *this; + } + + // Opens a file. + FMT_API buffered_file(cstring_view filename, cstring_view mode); + + // Closes the file. + FMT_API void close(); + + // Returns the pointer to a FILE object representing this file. + inline auto get() const noexcept -> FILE* { return file_; } + + FMT_API auto descriptor() const -> int; + + template + inline void print(string_view fmt, const T&... args) { + fmt::vargs vargs = {{args...}}; + detail::is_locking() ? fmt::vprint_buffered(file_, fmt, vargs) + : fmt::vprint(file_, fmt, vargs); + } +}; + +#if FMT_USE_FCNTL + +// A file. Closed file is represented by a file object with descriptor -1. +// Methods that are not declared with noexcept may throw +// fmt::system_error in case of failure. Note that some errors such as +// closing the file multiple times will cause a crash on Windows rather +// than an exception. You can get standard behavior by overriding the +// invalid parameter handler with _set_invalid_parameter_handler. +class FMT_API file { + private: + int fd_; // File descriptor. + + // Constructs a file object with a given descriptor. + explicit file(int fd) : fd_(fd) {} + + friend struct pipe; + + public: + // Possible values for the oflag argument to the constructor. + enum { + RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only. + WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only. + RDWR = FMT_POSIX(O_RDWR), // Open for reading and writing. + CREATE = FMT_POSIX(O_CREAT), // Create if the file doesn't exist. + APPEND = FMT_POSIX(O_APPEND), // Open in append mode. + TRUNC = FMT_POSIX(O_TRUNC) // Truncate the content of the file. + }; + + // Constructs a file object which doesn't represent any file. + inline file() noexcept : fd_(-1) {} + + // Opens a file and constructs a file object representing this file. + file(cstring_view path, int oflag); + + public: + file(const file&) = delete; + void operator=(const file&) = delete; + + inline file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; } + + // Move assignment is not noexcept because close may throw. + inline auto operator=(file&& other) -> file& { + close(); + fd_ = other.fd_; + other.fd_ = -1; + return *this; + } + + // Destroys the object closing the file it represents if any. + ~file() noexcept; + + // Returns the file descriptor. + inline auto descriptor() const noexcept -> int { return fd_; } + + // Closes the file. + void close(); + + // Returns the file size. The size has signed type for consistency with + // stat::st_size. + auto size() const -> long long; + + // Attempts to read count bytes from the file into the specified buffer. + auto read(void* buffer, size_t count) -> size_t; + + // Attempts to write count bytes from the specified buffer to the file. + auto write(const void* buffer, size_t count) -> size_t; + + // Duplicates a file descriptor with the dup function and returns + // the duplicate as a file object. + static auto dup(int fd) -> file; + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + void dup2(int fd); + + // Makes fd be the copy of this file descriptor, closing fd first if + // necessary. + void dup2(int fd, std::error_code& ec) noexcept; + + // Creates a buffered_file object associated with this file and detaches + // this file object from the file. + auto fdopen(const char* mode) -> buffered_file; + +# if defined(_WIN32) && !defined(__MINGW32__) + // Opens a file and constructs a file object representing this file by + // wcstring_view filename. Windows only. + static file open_windows_file(wcstring_view path, int oflag); +# endif +}; + +struct FMT_API pipe { + file read_end; + file write_end; + + // Creates a pipe setting up read_end and write_end file objects for reading + // and writing respectively. + pipe(); +}; + +// Returns the memory page size. +auto getpagesize() -> long; + +namespace detail { + +struct buffer_size { + constexpr buffer_size() = default; + size_t value = 0; + FMT_CONSTEXPR auto operator=(size_t val) const -> buffer_size { + auto bs = buffer_size(); + bs.value = val; + return bs; + } +}; + +struct ostream_params { + int oflag = file::WRONLY | file::CREATE | file::TRUNC; + size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768; + + constexpr ostream_params() {} + + template + ostream_params(T... params, int new_oflag) : ostream_params(params...) { + oflag = new_oflag; + } + + template + ostream_params(T... params, detail::buffer_size bs) + : ostream_params(params...) { + this->buffer_size = bs.value; + } + +// Intel has a bug that results in failure to deduce a constructor +// for empty parameter packs. +# if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000 + ostream_params(int new_oflag) : oflag(new_oflag) {} + ostream_params(detail::buffer_size bs) : buffer_size(bs.value) {} +# endif +}; + +} // namespace detail + +FMT_INLINE_VARIABLE constexpr auto buffer_size = detail::buffer_size(); + +/// A fast buffered output stream for writing from a single thread. Writing from +/// multiple threads without external synchronization may result in a data race. +class FMT_API ostream : private detail::buffer { + private: + file file_; + + ostream(cstring_view path, const detail::ostream_params& params); + + static void grow(buffer& buf, size_t); + + public: + ostream(ostream&& other) noexcept; + ~ostream(); + + operator writer() { + detail::buffer& buf = *this; + return buf; + } + + inline void flush() { + if (size() == 0) return; + file_.write(data(), size() * sizeof(data()[0])); + clear(); + } + + template + friend auto output_file(cstring_view path, T... params) -> ostream; + + inline void close() { + flush(); + file_.close(); + } + + /// Formats `args` according to specifications in `fmt` and writes the + /// output to the file. + template void print(format_string fmt, T&&... args) { + vformat_to(appender(*this), fmt.str, vargs{{args...}}); + } +}; + +/** + * Opens a file for writing. Supported parameters passed in `params`: + * + * - ``: Flags passed to [open]( + * https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html) + * (`file::WRONLY | file::CREATE | file::TRUNC` by default) + * - `buffer_size=`: Output buffer size + * + * **Example**: + * + * auto out = fmt::output_file("guide.txt"); + * out.print("Don't {}", "Panic"); + */ +template +inline auto output_file(cstring_view path, T... params) -> ostream { + return {path, detail::ostream_params(params...)}; +} +#endif // FMT_USE_FCNTL + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_OS_H_ diff --git a/vendor/btop/include/fmt/ostream.h b/vendor/btop/include/fmt/ostream.h new file mode 100644 index 000000000..bf2371b79 --- /dev/null +++ b/vendor/btop/include/fmt/ostream.h @@ -0,0 +1,167 @@ +// Formatting library for C++ - std::ostream support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_OSTREAM_H_ +#define FMT_OSTREAM_H_ + +#ifndef FMT_MODULE +# include // std::filebuf +#endif + +#ifdef _WIN32 +# ifdef __GLIBCXX__ +# include +# include +# endif +# include +#endif + +#include "chrono.h" // formatbuf + +#ifdef _MSVC_STL_UPDATE +# define FMT_MSVC_STL_UPDATE _MSVC_STL_UPDATE +#elif defined(_MSC_VER) && _MSC_VER < 1912 // VS 15.5 +# define FMT_MSVC_STL_UPDATE _MSVC_LANG +#else +# define FMT_MSVC_STL_UPDATE 0 +#endif + +FMT_BEGIN_NAMESPACE +namespace detail { + +// Generate a unique explicit instantiation in every translation unit using a +// tag type in an anonymous namespace. +namespace { +struct file_access_tag {}; +} // namespace +template +class file_access { + friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; } +}; + +#if FMT_MSVC_STL_UPDATE +template class file_access; +auto get_file(std::filebuf&) -> FILE*; +#endif + +// Write the content of buf to os. +// It is a separate function rather than a part of vprint to simplify testing. +template +void write_buffer(std::basic_ostream& os, buffer& buf) { + const Char* buf_data = buf.data(); + using unsigned_streamsize = make_unsigned_t; + unsigned_streamsize size = buf.size(); + unsigned_streamsize max_size = to_unsigned(max_value()); + do { + unsigned_streamsize n = size <= max_size ? size : max_size; + os.write(buf_data, static_cast(n)); + buf_data += n; + size -= n; + } while (size != 0); +} + +template struct streamed_view { + const T& value; +}; +} // namespace detail + +// Formats an object of type T that has an overloaded ostream operator<<. +template +struct basic_ostream_formatter : formatter, Char> { + void set_debug_format() = delete; + + template + auto format(const T& value, Context& ctx) const -> decltype(ctx.out()) { + auto buffer = basic_memory_buffer(); + auto&& formatbuf = detail::formatbuf>(buffer); + auto&& output = std::basic_ostream(&formatbuf); + output.imbue(std::locale::classic()); // The default is always unlocalized. + output << value; + output.exceptions(std::ios_base::failbit | std::ios_base::badbit); + return formatter, Char>::format( + {buffer.data(), buffer.size()}, ctx); + } +}; + +using ostream_formatter = basic_ostream_formatter; + +template +struct formatter, Char> + : basic_ostream_formatter { + template + auto format(detail::streamed_view view, Context& ctx) const + -> decltype(ctx.out()) { + return basic_ostream_formatter::format(view.value, ctx); + } +}; + +/** + * Returns a view that formats `value` via an ostream `operator<<`. + * + * **Example**: + * + * fmt::print("Current thread id: {}\n", + * fmt::streamed(std::this_thread::get_id())); + */ +template +constexpr auto streamed(const T& value) -> detail::streamed_view { + return {value}; +} + +inline void vprint(std::ostream& os, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + FILE* f = nullptr; +#if FMT_MSVC_STL_UPDATE && FMT_USE_RTTI + if (auto* buf = dynamic_cast(os.rdbuf())) + f = detail::get_file(*buf); +#elif defined(_WIN32) && defined(__GLIBCXX__) && FMT_USE_RTTI + auto* rdbuf = os.rdbuf(); + if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf*>(rdbuf)) + f = sfbuf->file(); + else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf*>(rdbuf)) + f = fbuf->file(); +#endif +#ifdef _WIN32 + if (f) { + int fd = _fileno(f); + if (_isatty(fd)) { + os.flush(); + if (detail::write_console(fd, {buffer.data(), buffer.size()})) return; + } + } +#endif + detail::ignore_unused(f); + detail::write_buffer(os, buffer); +} + +/** + * Prints formatted data to the stream `os`. + * + * **Example**: + * + * fmt::print(cerr, "Don't {}!", "panic"); + */ +FMT_EXPORT template +void print(std::ostream& os, format_string fmt, T&&... args) { + fmt::vargs vargs = {{args...}}; + if (detail::const_check(detail::use_utf8)) return vprint(os, fmt.str, vargs); + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt.str, vargs); + detail::write_buffer(os, buffer); +} + +FMT_EXPORT template +void println(std::ostream& os, format_string fmt, T&&... args) { + fmt::print(os, FMT_STRING("{}\n"), + fmt::format(fmt, std::forward(args)...)); +} + +FMT_END_NAMESPACE + +#endif // FMT_OSTREAM_H_ diff --git a/vendor/btop/include/fmt/printf.h b/vendor/btop/include/fmt/printf.h new file mode 100644 index 000000000..cc066d8c0 --- /dev/null +++ b/vendor/btop/include/fmt/printf.h @@ -0,0 +1,624 @@ +// Formatting library for C++ - legacy printf implementation +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_PRINTF_H_ +#define FMT_PRINTF_H_ + +#ifndef FMT_MODULE +# include // std::find +# include // std::numeric_limits +#endif + +#include "format.h" + +FMT_BEGIN_NAMESPACE +FMT_BEGIN_EXPORT + +template class basic_printf_context { + private: + basic_appender out_; + basic_format_args args_; + + static_assert(std::is_same::value || + std::is_same::value, + "Unsupported code unit type."); + + public: + using char_type = Char; + enum { builtin_types = 1 }; + + /// Constructs a `printf_context` object. References to the arguments are + /// stored in the context object so make sure they have appropriate lifetimes. + basic_printf_context(basic_appender out, + basic_format_args args) + : out_(out), args_(args) {} + + auto out() -> basic_appender { return out_; } + void advance_to(basic_appender) {} + + auto locale() -> locale_ref { return {}; } + + auto arg(int id) const -> basic_format_arg { + return args_.get(id); + } +}; + +namespace detail { + +// Return the result via the out param to workaround gcc bug 77539. +template +FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool { + for (out = first; out != last; ++out) { + if (*out == value) return true; + } + return false; +} + +template <> +inline auto find(const char* first, const char* last, char value, + const char*& out) -> bool { + out = + static_cast(memchr(first, value, to_unsigned(last - first))); + return out != nullptr; +} + +// Checks if a value fits in int - used to avoid warnings about comparing +// signed and unsigned integers. +template struct int_checker { + template static auto fits_in_int(T value) -> bool { + return value <= to_unsigned(max_value()); + } + inline static auto fits_in_int(bool) -> bool { return true; } +}; + +template <> struct int_checker { + template static auto fits_in_int(T value) -> bool { + return value >= (std::numeric_limits::min)() && + value <= max_value(); + } + inline static auto fits_in_int(int) -> bool { return true; } +}; + +struct printf_precision_handler { + template ::value)> + auto operator()(T value) -> int { + if (!int_checker::is_signed>::fits_in_int(value)) + report_error("number is too big"); + return max_of(static_cast(value), 0); + } + + template ::value)> + auto operator()(T) -> int { + report_error("precision is not integer"); + return 0; + } +}; + +// An argument visitor that returns true iff arg is a zero integer. +struct is_zero_int { + template ::value)> + auto operator()(T value) -> bool { + return value == 0; + } + + template ::value)> + auto operator()(T) -> bool { + return false; + } +}; + +template struct make_unsigned_or_bool : std::make_unsigned {}; + +template <> struct make_unsigned_or_bool { + using type = bool; +}; + +template class arg_converter { + private: + using char_type = typename Context::char_type; + + basic_format_arg& arg_; + char_type type_; + + public: + arg_converter(basic_format_arg& arg, char_type type) + : arg_(arg), type_(type) {} + + void operator()(bool value) { + if (type_ != 's') operator()(value); + } + + template ::value)> + void operator()(U value) { + bool is_signed = type_ == 'd' || type_ == 'i'; + using target_type = conditional_t::value, U, T>; + if (const_check(sizeof(target_type) <= sizeof(int))) { + // Extra casts are used to silence warnings. + using unsigned_type = typename make_unsigned_or_bool::type; + if (is_signed) + arg_ = static_cast(static_cast(value)); + else + arg_ = static_cast(static_cast(value)); + } else { + // glibc's printf doesn't sign extend arguments of smaller types: + // std::printf("%lld", -42); // prints "4294967254" + // but we don't have to do the same because it's a UB. + if (is_signed) + arg_ = static_cast(value); + else + arg_ = static_cast::type>(value); + } + } + + template ::value)> + void operator()(U) {} // No conversion needed for non-integral types. +}; + +// Converts an integer argument to T for printf, if T is an integral type. +// If T is void, the argument is converted to corresponding signed or unsigned +// type depending on the type specifier: 'd' and 'i' - signed, other - +// unsigned). +template +void convert_arg(basic_format_arg& arg, Char type) { + arg.visit(arg_converter(arg, type)); +} + +// Converts an integer argument to char for printf. +template class char_converter { + private: + basic_format_arg& arg_; + + public: + explicit char_converter(basic_format_arg& arg) : arg_(arg) {} + + template ::value)> + void operator()(T value) { + arg_ = static_cast(value); + } + + template ::value)> + void operator()(T) {} // No conversion needed for non-integral types. +}; + +// An argument visitor that return a pointer to a C string if argument is a +// string or null otherwise. +template struct get_cstring { + template auto operator()(T) -> const Char* { return nullptr; } + auto operator()(const Char* s) -> const Char* { return s; } +}; + +// Checks if an argument is a valid printf width specifier and sets +// left alignment if it is negative. +class printf_width_handler { + private: + format_specs& specs_; + + public: + inline explicit printf_width_handler(format_specs& specs) : specs_(specs) {} + + template ::value)> + auto operator()(T value) -> unsigned { + auto width = static_cast>(value); + if (detail::is_negative(value)) { + specs_.set_align(align::left); + width = 0 - width; + } + unsigned int_max = to_unsigned(max_value()); + if (width > int_max) report_error("number is too big"); + return static_cast(width); + } + + template ::value)> + auto operator()(T) -> unsigned { + report_error("width is not integer"); + return 0; + } +}; + +// Workaround for a bug with the XL compiler when initializing +// printf_arg_formatter's base class. +template +auto make_arg_formatter(basic_appender iter, format_specs& s) + -> arg_formatter { + return {iter, s, locale_ref()}; +} + +// The `printf` argument formatter. +template +class printf_arg_formatter : public arg_formatter { + private: + using base = arg_formatter; + using context_type = basic_printf_context; + + context_type& context_; + + void write_null_pointer(bool is_string = false) { + auto s = this->specs; + s.set_type(presentation_type::none); + write_bytes(this->out, is_string ? "(null)" : "(nil)", s); + } + + template void write(T value) { + detail::write(this->out, value, this->specs, this->locale); + } + + public: + printf_arg_formatter(basic_appender iter, format_specs& s, + context_type& ctx) + : base(make_arg_formatter(iter, s)), context_(ctx) {} + + void operator()(monostate value) { write(value); } + + template ::value)> + void operator()(T value) { + // MSVC2013 fails to compile separate overloads for bool and Char so use + // std::is_same instead. + if (!std::is_same::value) { + write(value); + return; + } + format_specs s = this->specs; + if (s.type() != presentation_type::none && + s.type() != presentation_type::chr) { + return (*this)(static_cast(value)); + } + s.set_sign(sign::none); + s.clear_alt(); + s.set_fill(' '); // Ignore '0' flag for char types. + // align::numeric needs to be overwritten here since the '0' flag is + // ignored for non-numeric types + if (s.align() == align::none || s.align() == align::numeric) + s.set_align(align::right); + detail::write(this->out, static_cast(value), s); + } + + template ::value)> + void operator()(T value) { + write(value); + } + + void operator()(const char* value) { + if (value) + write(value); + else + write_null_pointer(this->specs.type() != presentation_type::pointer); + } + + void operator()(const wchar_t* value) { + if (value) + write(value); + else + write_null_pointer(this->specs.type() != presentation_type::pointer); + } + + void operator()(basic_string_view value) { write(value); } + + void operator()(const void* value) { + if (value) + write(value); + else + write_null_pointer(); + } + + void operator()(typename basic_format_arg::handle handle) { + auto parse_ctx = parse_context({}); + handle.format(parse_ctx, context_); + } +}; + +template +void parse_flags(format_specs& specs, const Char*& it, const Char* end) { + for (; it != end; ++it) { + switch (*it) { + case '-': specs.set_align(align::left); break; + case '+': specs.set_sign(sign::plus); break; + case '0': specs.set_fill('0'); break; + case ' ': + if (specs.sign() != sign::plus) specs.set_sign(sign::space); + break; + case '#': specs.set_alt(); break; + default: return; + } + } +} + +template +auto parse_header(const Char*& it, const Char* end, format_specs& specs, + GetArg get_arg) -> int { + int arg_index = -1; + Char c = *it; + if (c >= '0' && c <= '9') { + // Parse an argument index (if followed by '$') or a width possibly + // preceded with '0' flag(s). + int value = parse_nonnegative_int(it, end, -1); + if (it != end && *it == '$') { // value is an argument index + ++it; + arg_index = value != -1 ? value : max_value(); + } else { + if (c == '0') specs.set_fill('0'); + if (value != 0) { + // Nonzero value means that we parsed width and don't need to + // parse it or flags again, so return now. + if (value == -1) report_error("number is too big"); + specs.width = value; + return arg_index; + } + } + } + parse_flags(specs, it, end); + // Parse width. + if (it != end) { + if (*it >= '0' && *it <= '9') { + specs.width = parse_nonnegative_int(it, end, -1); + if (specs.width == -1) report_error("number is too big"); + } else if (*it == '*') { + ++it; + specs.width = static_cast( + get_arg(-1).visit(detail::printf_width_handler(specs))); + } + } + return arg_index; +} + +inline auto parse_printf_presentation_type(char c, type t, bool& upper) + -> presentation_type { + using pt = presentation_type; + constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; + switch (c) { + case 'd': return in(t, integral_set) ? pt::dec : pt::none; + case 'o': return in(t, integral_set) ? pt::oct : pt::none; + case 'X': upper = true; FMT_FALLTHROUGH; + case 'x': return in(t, integral_set) ? pt::hex : pt::none; + case 'E': upper = true; FMT_FALLTHROUGH; + case 'e': return in(t, float_set) ? pt::exp : pt::none; + case 'F': upper = true; FMT_FALLTHROUGH; + case 'f': return in(t, float_set) ? pt::fixed : pt::none; + case 'G': upper = true; FMT_FALLTHROUGH; + case 'g': return in(t, float_set) ? pt::general : pt::none; + case 'A': upper = true; FMT_FALLTHROUGH; + case 'a': return in(t, float_set) ? pt::hexfloat : pt::none; + case 'c': return in(t, integral_set) ? pt::chr : pt::none; + case 's': return in(t, string_set | cstring_set) ? pt::string : pt::none; + case 'p': return in(t, pointer_set | cstring_set) ? pt::pointer : pt::none; + default: return pt::none; + } +} + +template +void vprintf(buffer& buf, basic_string_view format, + basic_format_args args) { + using iterator = basic_appender; + auto out = iterator(buf); + auto context = basic_printf_context(out, args); + auto parse_ctx = parse_context(format); + + // Returns the argument with specified index or, if arg_index is -1, the next + // argument. + auto get_arg = [&](int arg_index) { + if (arg_index < 0) + arg_index = parse_ctx.next_arg_id(); + else + parse_ctx.check_arg_id(--arg_index); + auto arg = context.arg(arg_index); + if (!arg) report_error("argument not found"); + return arg; + }; + + const Char* start = parse_ctx.begin(); + const Char* end = parse_ctx.end(); + auto it = start; + while (it != end) { + if (!find(it, end, '%', it)) { + it = end; // find leaves it == nullptr if it doesn't find '%'. + break; + } + Char c = *it++; + if (it != end && *it == c) { + write(out, basic_string_view(start, to_unsigned(it - start))); + start = ++it; + continue; + } + write(out, basic_string_view(start, to_unsigned(it - 1 - start))); + + auto specs = format_specs(); + specs.set_align(align::right); + + // Parse argument index, flags and width. + int arg_index = parse_header(it, end, specs, get_arg); + if (arg_index == 0) report_error("argument not found"); + + // Parse precision. + if (it != end && *it == '.') { + ++it; + c = it != end ? *it : 0; + if ('0' <= c && c <= '9') { + specs.precision = parse_nonnegative_int(it, end, 0); + } else if (c == '*') { + ++it; + specs.precision = + static_cast(get_arg(-1).visit(printf_precision_handler())); + } else { + specs.precision = 0; + } + } + + auto arg = get_arg(arg_index); + // For d, i, o, u, x, and X conversion specifiers, if a precision is + // specified, the '0' flag is ignored + if (specs.precision >= 0 && is_integral_type(arg.type())) { + // Ignore '0' for non-numeric types or if '-' present. + specs.set_fill(' '); + } + if (specs.precision >= 0 && arg.type() == type::cstring_type) { + auto str = arg.visit(get_cstring()); + auto str_end = str + specs.precision; + auto nul = std::find(str, str_end, Char()); + auto sv = basic_string_view( + str, to_unsigned(nul != str_end ? nul - str : specs.precision)); + arg = sv; + } + if (specs.alt() && arg.visit(is_zero_int())) specs.clear_alt(); + if (specs.fill_unit() == '0') { + if (is_arithmetic_type(arg.type()) && specs.align() != align::left) { + specs.set_align(align::numeric); + } else { + // Ignore '0' flag for non-numeric types or if '-' flag is also present. + specs.set_fill(' '); + } + } + + // Parse length and convert the argument to the required type. + c = it != end ? *it++ : 0; + Char t = it != end ? *it : 0; + switch (c) { + case 'h': + if (t == 'h') { + ++it; + t = it != end ? *it : 0; + convert_arg(arg, t); + } else { + convert_arg(arg, t); + } + break; + case 'l': + if (t == 'l') { + ++it; + t = it != end ? *it : 0; + convert_arg(arg, t); + } else { + convert_arg(arg, t); + } + break; + case 'j': convert_arg(arg, t); break; + case 'z': convert_arg(arg, t); break; + case 't': convert_arg(arg, t); break; + case 'L': + // printf produces garbage when 'L' is omitted for long double, no + // need to do the same. + break; + default: --it; convert_arg(arg, c); + } + + // Parse type. + if (it == end) report_error("invalid format string"); + char type = static_cast(*it++); + if (is_integral_type(arg.type())) { + // Normalize type. + switch (type) { + case 'i': + case 'u': type = 'd'; break; + case 'c': + arg.visit(char_converter>(arg)); + break; + } + } + bool upper = false; + specs.set_type(parse_printf_presentation_type(type, arg.type(), upper)); + if (specs.type() == presentation_type::none) + report_error("invalid format specifier"); + if (upper) specs.set_upper(); + + start = it; + + // Format argument. + arg.visit(printf_arg_formatter(out, specs, context)); + } + write(out, basic_string_view(start, to_unsigned(it - start))); +} +} // namespace detail + +using printf_context = basic_printf_context; +using wprintf_context = basic_printf_context; + +using printf_args = basic_format_args; +using wprintf_args = basic_format_args; + +/// Constructs an `format_arg_store` object that contains references to +/// arguments and can be implicitly converted to `printf_args`. +template +inline auto make_printf_args(T&... args) + -> decltype(fmt::make_format_args>(args...)) { + return fmt::make_format_args>(args...); +} + +template struct vprintf_args { + using type = basic_format_args>; +}; + +template +inline auto vsprintf(basic_string_view fmt, + typename vprintf_args::type args) + -> std::basic_string { + auto buf = basic_memory_buffer(); + detail::vprintf(buf, fmt, args); + return {buf.data(), buf.size()}; +} + +/** + * Formats `args` according to specifications in `fmt` and returns the result + * as as string. + * + * **Example**: + * + * std::string message = fmt::sprintf("The answer is %d", 42); + */ +template +inline auto sprintf(string_view fmt, const T&... args) -> std::string { + return vsprintf(fmt, make_printf_args(args...)); +} +template +FMT_DEPRECATED auto sprintf(basic_string_view fmt, const T&... args) + -> std::wstring { + return vsprintf(fmt, make_printf_args(args...)); +} + +template +auto vfprintf(std::FILE* f, basic_string_view fmt, + typename vprintf_args::type args) -> int { + auto buf = basic_memory_buffer(); + detail::vprintf(buf, fmt, args); + size_t size = buf.size(); + return std::fwrite(buf.data(), sizeof(Char), size, f) < size + ? -1 + : static_cast(size); +} + +/** + * Formats `args` according to specifications in `fmt` and writes the output + * to `f`. + * + * **Example**: + * + * fmt::fprintf(stderr, "Don't %s!", "panic"); + */ +template +inline auto fprintf(std::FILE* f, string_view fmt, const T&... args) -> int { + return vfprintf(f, fmt, make_printf_args(args...)); +} +template +FMT_DEPRECATED auto fprintf(std::FILE* f, basic_string_view fmt, + const T&... args) -> int { + return vfprintf(f, fmt, make_printf_args(args...)); +} + +/** + * Formats `args` according to specifications in `fmt` and writes the output + * to `stdout`. + * + * **Example**: + * + * fmt::printf("Elapsed time: %.2f seconds", 1.23); + */ +template +inline auto printf(string_view fmt, const T&... args) -> int { + return vfprintf(stdout, fmt, make_printf_args(args...)); +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_PRINTF_H_ diff --git a/vendor/btop/include/fmt/ranges.h b/vendor/btop/include/fmt/ranges.h new file mode 100644 index 000000000..24c61e93b --- /dev/null +++ b/vendor/btop/include/fmt/ranges.h @@ -0,0 +1,852 @@ +// Formatting library for C++ - range and tuple support +// +// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_RANGES_H_ +#define FMT_RANGES_H_ + +#ifndef FMT_MODULE +# include +# include +# include +# include +# include +#endif + +#include "format.h" + +FMT_BEGIN_NAMESPACE + +FMT_EXPORT +enum class range_format { disabled, map, set, sequence, string, debug_string }; + +namespace detail { + +template class is_map { + template static auto check(U*) -> typename U::mapped_type; + template static void check(...); + + public: + static constexpr bool value = + !std::is_void(nullptr))>::value; +}; + +template class is_set { + template static auto check(U*) -> typename U::key_type; + template static void check(...); + + public: + static constexpr bool value = + !std::is_void(nullptr))>::value && !is_map::value; +}; + +// C array overload +template +auto range_begin(const T (&arr)[N]) -> const T* { + return arr; +} +template auto range_end(const T (&arr)[N]) -> const T* { + return arr + N; +} + +template +struct has_member_fn_begin_end_t : std::false_type {}; + +template +struct has_member_fn_begin_end_t().begin()), + decltype(std::declval().end())>> + : std::true_type {}; + +// Member function overloads. +template +auto range_begin(T&& rng) -> decltype(static_cast(rng).begin()) { + return static_cast(rng).begin(); +} +template +auto range_end(T&& rng) -> decltype(static_cast(rng).end()) { + return static_cast(rng).end(); +} + +// ADL overloads. Only participate in overload resolution if member functions +// are not found. +template +auto range_begin(T&& rng) + -> enable_if_t::value, + decltype(begin(static_cast(rng)))> { + return begin(static_cast(rng)); +} +template +auto range_end(T&& rng) -> enable_if_t::value, + decltype(end(static_cast(rng)))> { + return end(static_cast(rng)); +} + +template +struct has_const_begin_end : std::false_type {}; +template +struct has_mutable_begin_end : std::false_type {}; + +template +struct has_const_begin_end< + T, void_t&>())), + decltype(detail::range_end( + std::declval&>()))>> + : std::true_type {}; + +template +struct has_mutable_begin_end< + T, void_t())), + decltype(detail::range_end(std::declval())), + // the extra int here is because older versions of MSVC don't + // SFINAE properly unless there are distinct types + int>> : std::true_type {}; + +template struct is_range_ : std::false_type {}; +template +struct is_range_ + : std::integral_constant::value || + has_mutable_begin_end::value)> {}; + +// tuple_size and tuple_element check. +template class is_tuple_like_ { + template ::type> + static auto check(U* p) -> decltype(std::tuple_size::value, 0); + template static void check(...); + + public: + static constexpr bool value = + !std::is_void(nullptr))>::value; +}; + +// Check for integer_sequence +#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VERSION >= 1900 +template +using integer_sequence = std::integer_sequence; +template using index_sequence = std::index_sequence; +template using make_index_sequence = std::make_index_sequence; +#else +template struct integer_sequence { + using value_type = T; + + static FMT_CONSTEXPR auto size() -> size_t { return sizeof...(N); } +}; + +template using index_sequence = integer_sequence; + +template +struct make_integer_sequence : make_integer_sequence {}; +template +struct make_integer_sequence : integer_sequence {}; + +template +using make_index_sequence = make_integer_sequence; +#endif + +template +using tuple_index_sequence = make_index_sequence::value>; + +template ::value> +class is_tuple_formattable_ { + public: + static constexpr bool value = false; +}; +template class is_tuple_formattable_ { + template + static auto all_true(index_sequence, + integer_sequence= 0)...>) -> std::true_type; + static auto all_true(...) -> std::false_type; + + template + static auto check(index_sequence) -> decltype(all_true( + index_sequence{}, + integer_sequence::type, + C>::value)...>{})); + + public: + static constexpr bool value = + decltype(check(tuple_index_sequence{}))::value; +}; + +template +FMT_CONSTEXPR void for_each(index_sequence, Tuple&& t, F&& f) { + using std::get; + // Using a free function get(Tuple) now. + const int unused[] = {0, ((void)f(get(t)), 0)...}; + ignore_unused(unused); +} + +template +FMT_CONSTEXPR void for_each(Tuple&& t, F&& f) { + for_each(tuple_index_sequence>(), + std::forward(t), std::forward(f)); +} + +template +void for_each2(index_sequence, Tuple1&& t1, Tuple2&& t2, F&& f) { + using std::get; + const int unused[] = {0, ((void)f(get(t1), get(t2)), 0)...}; + ignore_unused(unused); +} + +template +void for_each2(Tuple1&& t1, Tuple2&& t2, F&& f) { + for_each2(tuple_index_sequence>(), + std::forward(t1), std::forward(t2), + std::forward(f)); +} + +namespace tuple { +// Workaround a bug in MSVC 2019 (v140). +template +using result_t = std::tuple, Char>...>; + +using std::get; +template +auto get_formatters(index_sequence) + -> result_t(std::declval()))...>; +} // namespace tuple + +#if FMT_MSC_VERSION && FMT_MSC_VERSION < 1920 +// Older MSVC doesn't get the reference type correctly for arrays. +template struct range_reference_type_impl { + using type = decltype(*detail::range_begin(std::declval())); +}; + +template struct range_reference_type_impl { + using type = T&; +}; + +template +using range_reference_type = typename range_reference_type_impl::type; +#else +template +using range_reference_type = + decltype(*detail::range_begin(std::declval())); +#endif + +// We don't use the Range's value_type for anything, but we do need the Range's +// reference type, with cv-ref stripped. +template +using uncvref_type = remove_cvref_t>; + +template +FMT_CONSTEXPR auto maybe_set_debug_format(Formatter& f, bool set) + -> decltype(f.set_debug_format(set)) { + f.set_debug_format(set); +} +template +FMT_CONSTEXPR void maybe_set_debug_format(Formatter&, ...) {} + +template +struct range_format_kind_ + : std::integral_constant, T>::value + ? range_format::disabled + : is_map::value ? range_format::map + : is_set::value ? range_format::set + : range_format::sequence> {}; + +template +using range_format_constant = std::integral_constant; + +// These are not generic lambdas for compatibility with C++11. +template struct parse_empty_specs { + template FMT_CONSTEXPR void operator()(Formatter& f) { + f.parse(ctx); + detail::maybe_set_debug_format(f, true); + } + parse_context& ctx; +}; +template struct format_tuple_element { + using char_type = typename FormatContext::char_type; + + template + void operator()(const formatter& f, const T& v) { + if (i > 0) ctx.advance_to(detail::copy(separator, ctx.out())); + ctx.advance_to(f.format(v, ctx)); + ++i; + } + + int i; + FormatContext& ctx; + basic_string_view separator; +}; + +} // namespace detail + +FMT_EXPORT +template struct is_tuple_like { + static constexpr bool value = + detail::is_tuple_like_::value && !detail::is_range_::value; +}; + +FMT_EXPORT +template struct is_tuple_formattable { + static constexpr bool value = detail::is_tuple_formattable_::value; +}; + +template +struct formatter::value && + fmt::is_tuple_formattable::value>> { + private: + decltype(detail::tuple::get_formatters( + detail::tuple_index_sequence())) formatters_; + + basic_string_view separator_ = detail::string_literal{}; + basic_string_view opening_bracket_ = + detail::string_literal{}; + basic_string_view closing_bracket_ = + detail::string_literal{}; + + public: + FMT_CONSTEXPR formatter() {} + + FMT_CONSTEXPR void set_separator(basic_string_view sep) { + separator_ = sep; + } + + FMT_CONSTEXPR void set_brackets(basic_string_view open, + basic_string_view close) { + opening_bracket_ = open; + closing_bracket_ = close; + } + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(); + auto end = ctx.end(); + if (it != end && detail::to_ascii(*it) == 'n') { + ++it; + set_brackets({}, {}); + set_separator({}); + } + if (it != end && *it != '}') report_error("invalid format specifier"); + ctx.advance_to(it); + detail::for_each(formatters_, detail::parse_empty_specs{ctx}); + return it; + } + + template + auto format(const Tuple& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + ctx.advance_to(detail::copy(opening_bracket_, ctx.out())); + detail::for_each2( + formatters_, value, + detail::format_tuple_element{0, ctx, separator_}); + return detail::copy(closing_bracket_, ctx.out()); + } +}; + +FMT_EXPORT +template struct is_range { + static constexpr bool value = + detail::is_range_::value && !detail::has_to_string_view::value; +}; + +namespace detail { + +template +using range_formatter_type = formatter, Char>; + +template +using maybe_const_range = + conditional_t::value, const R, R>; + +template +struct is_formattable_delayed + : is_formattable>, Char> {}; +} // namespace detail + +template struct conjunction : std::true_type {}; +template struct conjunction

: P {}; +template +struct conjunction + : conditional_t, P1> {}; + +FMT_EXPORT +template +struct range_formatter; + +template +struct range_formatter< + T, Char, + enable_if_t>, + is_formattable>::value>> { + private: + detail::range_formatter_type underlying_; + basic_string_view separator_ = detail::string_literal{}; + basic_string_view opening_bracket_ = + detail::string_literal{}; + basic_string_view closing_bracket_ = + detail::string_literal{}; + bool is_debug = false; + + template ::value)> + auto write_debug_string(Output& out, It it, Sentinel end) const -> Output { + auto buf = basic_memory_buffer(); + for (; it != end; ++it) buf.push_back(*it); + auto specs = format_specs(); + specs.set_type(presentation_type::debug); + return detail::write( + out, basic_string_view(buf.data(), buf.size()), specs); + } + + template ::value)> + auto write_debug_string(Output& out, It, Sentinel) const -> Output { + return out; + } + + public: + FMT_CONSTEXPR range_formatter() {} + + FMT_CONSTEXPR auto underlying() -> detail::range_formatter_type& { + return underlying_; + } + + FMT_CONSTEXPR void set_separator(basic_string_view sep) { + separator_ = sep; + } + + FMT_CONSTEXPR void set_brackets(basic_string_view open, + basic_string_view close) { + opening_bracket_ = open; + closing_bracket_ = close; + } + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(); + auto end = ctx.end(); + detail::maybe_set_debug_format(underlying_, true); + if (it == end) return underlying_.parse(ctx); + + switch (detail::to_ascii(*it)) { + case 'n': + set_brackets({}, {}); + ++it; + break; + case '?': + is_debug = true; + set_brackets({}, {}); + ++it; + if (it == end || *it != 's') report_error("invalid format specifier"); + FMT_FALLTHROUGH; + case 's': + if (!std::is_same::value) + report_error("invalid format specifier"); + if (!is_debug) { + set_brackets(detail::string_literal{}, + detail::string_literal{}); + set_separator({}); + detail::maybe_set_debug_format(underlying_, false); + } + ++it; + return it; + } + + if (it != end && *it != '}') { + if (*it != ':') report_error("invalid format specifier"); + detail::maybe_set_debug_format(underlying_, false); + ++it; + } + + ctx.advance_to(it); + return underlying_.parse(ctx); + } + + template + auto format(R&& range, FormatContext& ctx) const -> decltype(ctx.out()) { + auto out = ctx.out(); + auto it = detail::range_begin(range); + auto end = detail::range_end(range); + if (is_debug) return write_debug_string(out, std::move(it), end); + + out = detail::copy(opening_bracket_, out); + int i = 0; + for (; it != end; ++it) { + if (i > 0) out = detail::copy(separator_, out); + ctx.advance_to(out); + auto&& item = *it; // Need an lvalue + out = underlying_.format(item, ctx); + ++i; + } + out = detail::copy(closing_bracket_, out); + return out; + } +}; + +FMT_EXPORT +template +struct range_format_kind + : conditional_t< + is_range::value, detail::range_format_kind_, + std::integral_constant> {}; + +template +struct formatter< + R, Char, + enable_if_t::value != range_format::disabled && + range_format_kind::value != range_format::map && + range_format_kind::value != range_format::string && + range_format_kind::value != range_format::debug_string>, + detail::is_formattable_delayed>::value>> { + private: + using range_type = detail::maybe_const_range; + range_formatter, Char> range_formatter_; + + public: + using nonlocking = void; + + FMT_CONSTEXPR formatter() { + if (detail::const_check(range_format_kind::value != + range_format::set)) + return; + range_formatter_.set_brackets(detail::string_literal{}, + detail::string_literal{}); + } + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return range_formatter_.parse(ctx); + } + + template + auto format(range_type& range, FormatContext& ctx) const + -> decltype(ctx.out()) { + return range_formatter_.format(range, ctx); + } +}; + +// A map formatter. +template +struct formatter< + R, Char, + enable_if_t::value == range_format::map>, + detail::is_formattable_delayed>::value>> { + private: + using map_type = detail::maybe_const_range; + using element_type = detail::uncvref_type; + + decltype(detail::tuple::get_formatters( + detail::tuple_index_sequence())) formatters_; + bool no_delimiters_ = false; + + public: + FMT_CONSTEXPR formatter() {} + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(); + auto end = ctx.end(); + if (it != end) { + if (detail::to_ascii(*it) == 'n') { + no_delimiters_ = true; + ++it; + } + if (it != end && *it != '}') { + if (*it != ':') report_error("invalid format specifier"); + ++it; + } + ctx.advance_to(it); + } + detail::for_each(formatters_, detail::parse_empty_specs{ctx}); + return it; + } + + template + auto format(map_type& map, FormatContext& ctx) const -> decltype(ctx.out()) { + auto out = ctx.out(); + basic_string_view open = detail::string_literal{}; + if (!no_delimiters_) out = detail::copy(open, out); + int i = 0; + basic_string_view sep = detail::string_literal{}; + for (auto&& value : map) { + if (i > 0) out = detail::copy(sep, out); + ctx.advance_to(out); + detail::for_each2(formatters_, value, + detail::format_tuple_element{ + 0, ctx, detail::string_literal{}}); + ++i; + } + basic_string_view close = detail::string_literal{}; + if (!no_delimiters_) out = detail::copy(close, out); + return out; + } +}; + +// A (debug_)string formatter. +template +struct formatter< + R, Char, + enable_if_t::value == range_format::string || + range_format_kind::value == + range_format::debug_string>> { + private: + using range_type = detail::maybe_const_range; + using string_type = + conditional_t, + decltype(detail::range_begin(std::declval())), + decltype(detail::range_end(std::declval()))>::value, + detail::std_string_view, std::basic_string>; + + formatter underlying_; + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return underlying_.parse(ctx); + } + + template + auto format(range_type& range, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + if (detail::const_check(range_format_kind::value == + range_format::debug_string)) + *out++ = '"'; + out = underlying_.format( + string_type{detail::range_begin(range), detail::range_end(range)}, ctx); + if (detail::const_check(range_format_kind::value == + range_format::debug_string)) + *out++ = '"'; + return out; + } +}; + +template +struct join_view : detail::view { + It begin; + Sentinel end; + basic_string_view sep; + + join_view(It b, Sentinel e, basic_string_view s) + : begin(std::move(b)), end(e), sep(s) {} +}; + +template +struct formatter, Char> { + private: + using value_type = +#ifdef __cpp_lib_ranges + std::iter_value_t; +#else + typename std::iterator_traits::value_type; +#endif + formatter, Char> value_formatter_; + + using view = conditional_t::value, + const join_view, + join_view>; + + public: + using nonlocking = void; + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return value_formatter_.parse(ctx); + } + + template + auto format(view& value, FormatContext& ctx) const -> decltype(ctx.out()) { + using iter = + conditional_t::value, It, It&>; + iter it = value.begin; + auto out = ctx.out(); + if (it == value.end) return out; + out = value_formatter_.format(*it, ctx); + ++it; + while (it != value.end) { + out = detail::copy(value.sep.begin(), value.sep.end(), out); + ctx.advance_to(out); + out = value_formatter_.format(*it, ctx); + ++it; + } + return out; + } +}; + +FMT_EXPORT +template struct tuple_join_view : detail::view { + const Tuple& tuple; + basic_string_view sep; + + tuple_join_view(const Tuple& t, basic_string_view s) + : tuple(t), sep{s} {} +}; + +// Define FMT_TUPLE_JOIN_SPECIFIERS to enable experimental format specifiers +// support in tuple_join. It is disabled by default because of issues with +// the dynamic width and precision. +#ifndef FMT_TUPLE_JOIN_SPECIFIERS +# define FMT_TUPLE_JOIN_SPECIFIERS 0 +#endif + +template +struct formatter, Char, + enable_if_t::value>> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return do_parse(ctx, std::tuple_size()); + } + + template + auto format(const tuple_join_view& value, + FormatContext& ctx) const -> typename FormatContext::iterator { + return do_format(value, ctx, std::tuple_size()); + } + + private: + decltype(detail::tuple::get_formatters( + detail::tuple_index_sequence())) formatters_; + + FMT_CONSTEXPR auto do_parse(parse_context& ctx, + std::integral_constant) + -> const Char* { + return ctx.begin(); + } + + template + FMT_CONSTEXPR auto do_parse(parse_context& ctx, + std::integral_constant) + -> const Char* { + auto end = ctx.begin(); +#if FMT_TUPLE_JOIN_SPECIFIERS + end = std::get::value - N>(formatters_).parse(ctx); + if (N > 1) { + auto end1 = do_parse(ctx, std::integral_constant()); + if (end != end1) + report_error("incompatible format specs for tuple elements"); + } +#endif + return end; + } + + template + auto do_format(const tuple_join_view&, FormatContext& ctx, + std::integral_constant) const -> + typename FormatContext::iterator { + return ctx.out(); + } + + template + auto do_format(const tuple_join_view& value, FormatContext& ctx, + std::integral_constant) const -> + typename FormatContext::iterator { + using std::get; + auto out = + std::get::value - N>(formatters_) + .format(get::value - N>(value.tuple), ctx); + if (N <= 1) return out; + out = detail::copy(value.sep, out); + ctx.advance_to(out); + return do_format(value, ctx, std::integral_constant()); + } +}; + +namespace detail { +// Check if T has an interface like a container adaptor (e.g. std::stack, +// std::queue, std::priority_queue). +template class is_container_adaptor_like { + template static auto check(U* p) -> typename U::container_type; + template static void check(...); + + public: + static constexpr bool value = + !std::is_void(nullptr))>::value; +}; + +template struct all { + const Container& c; + auto begin() const -> typename Container::const_iterator { return c.begin(); } + auto end() const -> typename Container::const_iterator { return c.end(); } +}; +} // namespace detail + +template +struct formatter< + T, Char, + enable_if_t, + bool_constant::value == + range_format::disabled>>::value>> + : formatter, Char> { + using all = detail::all; + template + auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) { + struct getter : T { + static auto get(const T& v) -> all { + return {v.*(&getter::c)}; // Access c through the derived class. + } + }; + return formatter::format(getter::get(value), ctx); + } +}; + +FMT_BEGIN_EXPORT + +/// Returns a view that formats the iterator range `[begin, end)` with elements +/// separated by `sep`. +template +auto join(It begin, Sentinel end, string_view sep) -> join_view { + return {std::move(begin), end, sep}; +} + +/** + * Returns a view that formats `range` with elements separated by `sep`. + * + * **Example**: + * + * auto v = std::vector{1, 2, 3}; + * fmt::print("{}", fmt::join(v, ", ")); + * // Output: 1, 2, 3 + * + * `fmt::join` applies passed format specifiers to the range elements: + * + * fmt::print("{:02}", fmt::join(v, ", ")); + * // Output: 01, 02, 03 + */ +template ::value)> +auto join(Range&& r, string_view sep) + -> join_view { + return {detail::range_begin(r), detail::range_end(r), sep}; +} + +/** + * Returns an object that formats `std::tuple` with elements separated by `sep`. + * + * **Example**: + * + * auto t = std::tuple{1, 'a'}; + * fmt::print("{}", fmt::join(t, ", ")); + * // Output: 1, a + */ +template ::value)> +FMT_CONSTEXPR auto join(const Tuple& tuple, string_view sep) + -> tuple_join_view { + return {tuple, sep}; +} + +/** + * Returns an object that formats `std::initializer_list` with elements + * separated by `sep`. + * + * **Example**: + * + * fmt::print("{}", fmt::join({1, 2, 3}, ", ")); + * // Output: "1, 2, 3" + */ +template +auto join(std::initializer_list list, string_view sep) + -> join_view { + return join(std::begin(list), std::end(list), sep); +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_RANGES_H_ diff --git a/vendor/btop/include/fmt/std.h b/vendor/btop/include/fmt/std.h new file mode 100644 index 000000000..5cf106181 --- /dev/null +++ b/vendor/btop/include/fmt/std.h @@ -0,0 +1,707 @@ +// Formatting library for C++ - formatters for standard library types +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_STD_H_ +#define FMT_STD_H_ + +#include "format.h" +#include "ostream.h" + +#ifndef FMT_MODULE +# include +# include +# include +# include +# include // std::reference_wrapper +# include +# include +# include +# include // std::type_info +# include // std::make_index_sequence + +// Check FMT_CPLUSPLUS to suppress a bogus warning in MSVC. +# if FMT_CPLUSPLUS >= 201703L +# if FMT_HAS_INCLUDE() && \ + (!defined(FMT_CPP_LIB_FILESYSTEM) || FMT_CPP_LIB_FILESYSTEM != 0) +# include +# endif +# if FMT_HAS_INCLUDE() +# include +# endif +# if FMT_HAS_INCLUDE() +# include +# endif +# endif +// Use > instead of >= in the version check because may be +// available after C++17 but before C++20 is marked as implemented. +# if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE() +# include +# endif +# if FMT_CPLUSPLUS > 202002L && FMT_HAS_INCLUDE() +# include +# endif +#endif // FMT_MODULE + +#if FMT_HAS_INCLUDE() +# include +#endif + +// GCC 4 does not support FMT_HAS_INCLUDE. +#if FMT_HAS_INCLUDE() || defined(__GLIBCXX__) +# include +// Android NDK with gabi++ library on some architectures does not implement +// abi::__cxa_demangle(). +# ifndef __GABIXX_CXXABI_H__ +# define FMT_HAS_ABI_CXA_DEMANGLE +# endif +#endif + +#ifdef FMT_CPP_LIB_FILESYSTEM +// Use the provided definition. +#elif defined(__cpp_lib_filesystem) +# define FMT_CPP_LIB_FILESYSTEM __cpp_lib_filesystem +#else +# define FMT_CPP_LIB_FILESYSTEM 0 +#endif + +#ifdef FMT_CPP_LIB_VARIANT +// Use the provided definition. +#elif defined(__cpp_lib_variant) +# define FMT_CPP_LIB_VARIANT __cpp_lib_variant +#else +# define FMT_CPP_LIB_VARIANT 0 +#endif + +FMT_BEGIN_NAMESPACE +namespace detail { + +#if FMT_CPP_LIB_FILESYSTEM + +template +auto get_path_string(const std::filesystem::path& p, + const std::basic_string& native) { + if constexpr (std::is_same_v && std::is_same_v) + return to_utf8(native, to_utf8_error_policy::replace); + else + return p.string(); +} + +template +void write_escaped_path(basic_memory_buffer& quoted, + const std::filesystem::path& p, + const std::basic_string& native) { + if constexpr (std::is_same_v && + std::is_same_v) { + auto buf = basic_memory_buffer(); + write_escaped_string(std::back_inserter(buf), native); + bool valid = to_utf8::convert(quoted, {buf.data(), buf.size()}); + FMT_ASSERT(valid, "invalid utf16"); + } else if constexpr (std::is_same_v) { + write_escaped_string( + std::back_inserter(quoted), native); + } else { + write_escaped_string(std::back_inserter(quoted), p.string()); + } +} + +#endif // FMT_CPP_LIB_FILESYSTEM + +#if defined(__cpp_lib_expected) || FMT_CPP_LIB_VARIANT +template +auto write_escaped_alternative(OutputIt out, const T& v) -> OutputIt { + if constexpr (has_to_string_view::value) + return write_escaped_string(out, detail::to_string_view(v)); + if constexpr (std::is_same_v) return write_escaped_char(out, v); + return write(out, v); +} +#endif + +#if FMT_CPP_LIB_VARIANT + +template struct is_variant_like_ : std::false_type {}; +template +struct is_variant_like_> : std::true_type {}; + +template class is_variant_formattable { + template + static auto check(std::index_sequence) -> std::conjunction< + is_formattable, Char>...>; + + public: + static constexpr bool value = decltype(check( + std::make_index_sequence::value>()))::value; +}; + +#endif // FMT_CPP_LIB_VARIANT + +#if FMT_USE_RTTI + +template +auto write_demangled_name(OutputIt out, const std::type_info& ti) -> OutputIt { +# ifdef FMT_HAS_ABI_CXA_DEMANGLE + int status = 0; + size_t size = 0; + std::unique_ptr demangled_name_ptr( + abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free); + + string_view demangled_name_view; + if (demangled_name_ptr) { + demangled_name_view = demangled_name_ptr.get(); + + // Normalization of stdlib inline namespace names. + // libc++ inline namespaces. + // std::__1::* -> std::* + // std::__1::__fs::* -> std::* + // libstdc++ inline namespaces. + // std::__cxx11::* -> std::* + // std::filesystem::__cxx11::* -> std::filesystem::* + if (demangled_name_view.starts_with("std::")) { + char* begin = demangled_name_ptr.get(); + char* to = begin + 5; // std:: + for (char *from = to, *end = begin + demangled_name_view.size(); + from < end;) { + // This is safe, because demangled_name is NUL-terminated. + if (from[0] == '_' && from[1] == '_') { + char* next = from + 1; + while (next < end && *next != ':') next++; + if (next[0] == ':' && next[1] == ':') { + from = next + 2; + continue; + } + } + *to++ = *from++; + } + demangled_name_view = {begin, detail::to_unsigned(to - begin)}; + } + } else { + demangled_name_view = string_view(ti.name()); + } + return detail::write_bytes(out, demangled_name_view); +# elif FMT_MSC_VERSION + const string_view demangled_name(ti.name()); + for (size_t i = 0; i < demangled_name.size(); ++i) { + auto sub = demangled_name; + sub.remove_prefix(i); + if (sub.starts_with("enum ")) { + i += 4; + continue; + } + if (sub.starts_with("class ") || sub.starts_with("union ")) { + i += 5; + continue; + } + if (sub.starts_with("struct ")) { + i += 6; + continue; + } + if (*sub.begin() != ' ') *out++ = *sub.begin(); + } + return out; +# else + return detail::write_bytes(out, string_view(ti.name())); +# endif +} + +#endif // FMT_USE_RTTI + +template +struct has_flip : std::false_type {}; + +template +struct has_flip().flip())>> + : std::true_type {}; + +template struct is_bit_reference_like { + static constexpr bool value = std::is_convertible::value && + std::is_nothrow_assignable::value && + has_flip::value; +}; + +// Workaround for libc++ incompatibility with C++ standard. +// According to the Standard, `bitset::operator[] const` returns bool. +#if defined(_LIBCPP_VERSION) && !defined(FMT_IMPORT_STD) +template +struct is_bit_reference_like> { + static constexpr bool value = true; +}; +#endif + +template +struct has_format_as : std::false_type {}; +template +struct has_format_as()))>> + : std::true_type {}; + +template +struct has_format_as_member : std::false_type {}; +template +struct has_format_as_member< + T, void_t::format_as(std::declval()))>> + : std::true_type {}; + +} // namespace detail + +template +auto ptr(const std::unique_ptr& p) -> const void* { + return p.get(); +} +template auto ptr(const std::shared_ptr& p) -> const void* { + return p.get(); +} + +#if FMT_CPP_LIB_FILESYSTEM + +class path : public std::filesystem::path { + public: + auto display_string() const -> std::string { + const std::filesystem::path& base = *this; + return fmt::format(FMT_STRING("{}"), base); + } + auto system_string() const -> std::string { return string(); } + + auto generic_display_string() const -> std::string { + const std::filesystem::path& base = *this; + return fmt::format(FMT_STRING("{:g}"), base); + } + auto generic_system_string() const -> std::string { return generic_string(); } +}; + +template struct formatter { + private: + format_specs specs_; + detail::arg_ref width_ref_; + bool debug_ = false; + char path_type_ = 0; + + public: + FMT_CONSTEXPR void set_debug_format(bool set = true) { debug_ = set; } + + FMT_CONSTEXPR auto parse(parse_context& ctx) { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + + it = detail::parse_align(it, end, specs_); + if (it == end) return it; + + Char c = *it; + if ((c >= '0' && c <= '9') || c == '{') + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + if (it != end && *it == '?') { + debug_ = true; + ++it; + } + if (it != end && (*it == 'g')) path_type_ = detail::to_ascii(*it++); + return it; + } + + template + auto format(const std::filesystem::path& p, FormatContext& ctx) const { + auto specs = specs_; + auto path_string = + !path_type_ ? p.native() + : p.generic_string(); + + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); + if (!debug_) { + auto s = detail::get_path_string(p, path_string); + return detail::write(ctx.out(), basic_string_view(s), specs); + } + auto quoted = basic_memory_buffer(); + detail::write_escaped_path(quoted, p, path_string); + return detail::write(ctx.out(), + basic_string_view(quoted.data(), quoted.size()), + specs); + } +}; + +#endif // FMT_CPP_LIB_FILESYSTEM + +template +struct formatter, Char> + : nested_formatter, Char> { + private: + // This is a functor because C++11 doesn't support generic lambdas. + struct writer { + const std::bitset& bs; + + template + FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt { + for (auto pos = N; pos > 0; --pos) + out = detail::write(out, bs[pos - 1] ? Char('1') : Char('0')); + return out; + } + }; + + public: + template + auto format(const std::bitset& bs, FormatContext& ctx) const + -> decltype(ctx.out()) { + return this->write_padded(ctx, writer{bs}); + } +}; + +template +struct formatter : basic_ostream_formatter {}; + +#ifdef __cpp_lib_optional +template +struct formatter, Char, + std::enable_if_t::value>> { + private: + formatter underlying_; + static constexpr basic_string_view optional = + detail::string_literal{}; + static constexpr basic_string_view none = + detail::string_literal{}; + + template + FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, bool set) + -> decltype(u.set_debug_format(set)) { + u.set_debug_format(set); + } + + template + FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {} + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) { + maybe_set_debug_format(underlying_, true); + return underlying_.parse(ctx); + } + + template + auto format(const std::optional& opt, FormatContext& ctx) const + -> decltype(ctx.out()) { + if (!opt) return detail::write(ctx.out(), none); + + auto out = ctx.out(); + out = detail::write(out, optional); + ctx.advance_to(out); + out = underlying_.format(*opt, ctx); + return detail::write(out, ')'); + } +}; +#endif // __cpp_lib_optional + +#ifdef __cpp_lib_expected +template +struct formatter, Char, + std::enable_if_t<(std::is_void::value || + is_formattable::value) && + is_formattable::value>> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return ctx.begin(); + } + + template + auto format(const std::expected& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + + if (value.has_value()) { + out = detail::write(out, "expected("); + if constexpr (!std::is_void::value) + out = detail::write_escaped_alternative(out, *value); + } else { + out = detail::write(out, "unexpected("); + out = detail::write_escaped_alternative(out, value.error()); + } + *out++ = ')'; + return out; + } +}; +#endif // __cpp_lib_expected + +#ifdef __cpp_lib_source_location +template <> struct formatter { + FMT_CONSTEXPR auto parse(parse_context<>& ctx) { return ctx.begin(); } + + template + auto format(const std::source_location& loc, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + out = detail::write(out, loc.file_name()); + out = detail::write(out, ':'); + out = detail::write(out, loc.line()); + out = detail::write(out, ':'); + out = detail::write(out, loc.column()); + out = detail::write(out, ": "); + out = detail::write(out, loc.function_name()); + return out; + } +}; +#endif + +#if FMT_CPP_LIB_VARIANT + +template struct is_variant_like { + static constexpr bool value = detail::is_variant_like_::value; +}; + +template struct formatter { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return ctx.begin(); + } + + template + auto format(const std::monostate&, FormatContext& ctx) const + -> decltype(ctx.out()) { + return detail::write(ctx.out(), "monostate"); + } +}; + +template +struct formatter, + detail::is_variant_formattable>>> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return ctx.begin(); + } + + template + auto format(const Variant& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); + + out = detail::write(out, "variant("); + FMT_TRY { + std::visit( + [&](const auto& v) { + out = detail::write_escaped_alternative(out, v); + }, + value); + } + FMT_CATCH(const std::bad_variant_access&) { + detail::write(out, "valueless by exception"); + } + *out++ = ')'; + return out; + } +}; + +#endif // FMT_CPP_LIB_VARIANT + +template <> struct formatter { + private: + format_specs specs_; + detail::arg_ref width_ref_; + bool debug_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + + it = detail::parse_align(it, end, specs_); + + char c = *it; + if (it != end && ((c >= '0' && c <= '9') || c == '{')) + it = detail::parse_width(it, end, specs_, width_ref_, ctx); + + if (it != end && *it == '?') { + debug_ = true; + ++it; + } + if (it != end && *it == 's') { + specs_.set_type(presentation_type::string); + ++it; + } + return it; + } + + template + FMT_CONSTEXPR20 auto format(const std::error_code& ec, + FormatContext& ctx) const -> decltype(ctx.out()) { + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_, + ctx); + auto buf = memory_buffer(); + if (specs_.type() == presentation_type::string) { + buf.append(ec.message()); + } else { + buf.append(string_view(ec.category().name())); + buf.push_back(':'); + detail::write(appender(buf), ec.value()); + } + auto quoted = memory_buffer(); + auto str = string_view(buf.data(), buf.size()); + if (debug_) { + detail::write_escaped_string(std::back_inserter(quoted), str); + str = string_view(quoted.data(), quoted.size()); + } + return detail::write(ctx.out(), str, specs); + } +}; + +#if FMT_USE_RTTI +template <> struct formatter { + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + return ctx.begin(); + } + + template + auto format(const std::type_info& ti, Context& ctx) const + -> decltype(ctx.out()) { + return detail::write_demangled_name(ctx.out(), ti); + } +}; +#endif // FMT_USE_RTTI + +template +struct formatter< + T, char, + typename std::enable_if::value>::type> { + private: + bool with_typename_ = false; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + auto it = ctx.begin(); + auto end = ctx.end(); + if (it == end || *it == '}') return it; + if (*it == 't') { + ++it; + with_typename_ = FMT_USE_RTTI != 0; + } + return it; + } + + template + auto format(const std::exception& ex, Context& ctx) const + -> decltype(ctx.out()) { + auto out = ctx.out(); +#if FMT_USE_RTTI + if (with_typename_) { + out = detail::write_demangled_name(out, typeid(ex)); + *out++ = ':'; + *out++ = ' '; + } +#endif + return detail::write_bytes(out, string_view(ex.what())); + } +}; + +// We can't use std::vector::reference and +// std::bitset::reference because the compiler can't deduce Allocator and N +// in partial specialization. +template +struct formatter::value>> + : formatter { + template + FMT_CONSTEXPR auto format(const BitRef& v, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter::format(v, ctx); + } +}; + +template +struct formatter, Char, + enable_if_t::value>> + : formatter { + template + auto format(const std::atomic& v, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter::format(v.load(), ctx); + } +}; + +#ifdef __cpp_lib_atomic_flag_test +template +struct formatter : formatter { + template + auto format(const std::atomic_flag& v, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter::format(v.test(), ctx); + } +}; +#endif // __cpp_lib_atomic_flag_test + +template struct formatter, Char> { + private: + detail::dynamic_format_specs specs_; + + template + FMT_CONSTEXPR auto do_format(const std::complex& c, + detail::dynamic_format_specs& specs, + FormatContext& ctx, OutputIt out) const + -> OutputIt { + if (c.real() != 0) { + *out++ = Char('('); + out = detail::write(out, c.real(), specs, ctx.locale()); + specs.set_sign(sign::plus); + out = detail::write(out, c.imag(), specs, ctx.locale()); + if (!detail::isfinite(c.imag())) *out++ = Char(' '); + *out++ = Char('i'); + *out++ = Char(')'); + return out; + } + out = detail::write(out, c.imag(), specs, ctx.locale()); + if (!detail::isfinite(c.imag())) *out++ = Char(' '); + *out++ = Char('i'); + return out; + } + + public: + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin(); + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type_constant::value); + } + + template + auto format(const std::complex& c, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto specs = specs_; + if (specs.dynamic()) { + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + } + + if (specs.width == 0) return do_format(c, specs, ctx, ctx.out()); + auto buf = basic_memory_buffer(); + + auto outer_specs = format_specs(); + outer_specs.width = specs.width; + outer_specs.copy_fill_from(specs); + outer_specs.set_align(specs.align()); + + specs.width = 0; + specs.set_fill({}); + specs.set_align(align::none); + + do_format(c, specs, ctx, basic_appender(buf)); + return detail::write(ctx.out(), + basic_string_view(buf.data(), buf.size()), + outer_specs); + } +}; + +template +struct formatter, Char, + // Guard against format_as because reference_wrapper is + // implicitly convertible to T&. + enable_if_t, Char>::value && + !detail::has_format_as::value && + !detail::has_format_as_member::value>> + : formatter, Char> { + template + auto format(std::reference_wrapper ref, FormatContext& ctx) const + -> decltype(ctx.out()) { + return formatter, Char>::format(ref.get(), ctx); + } +}; + +FMT_END_NAMESPACE + +#endif // FMT_STD_H_ diff --git a/vendor/btop/include/fmt/xchar.h b/vendor/btop/include/fmt/xchar.h new file mode 100644 index 000000000..9334b87fd --- /dev/null +++ b/vendor/btop/include/fmt/xchar.h @@ -0,0 +1,356 @@ +// Formatting library for C++ - optional wchar_t and exotic character support +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_XCHAR_H_ +#define FMT_XCHAR_H_ + +#include "color.h" +#include "format.h" +#include "ostream.h" +#include "ranges.h" + +#ifndef FMT_MODULE +# include +# if FMT_USE_LOCALE +# include +# endif +#endif + +FMT_BEGIN_NAMESPACE +namespace detail { + +template +using is_exotic_char = bool_constant::value>; + +template struct format_string_char {}; + +template +struct format_string_char< + S, void_t())))>> { + using type = char_t; +}; + +template +struct format_string_char< + S, enable_if_t::value>> { + using type = typename S::char_type; +}; + +template +using format_string_char_t = typename format_string_char::type; + +inline auto write_loc(basic_appender out, loc_value value, + const format_specs& specs, locale_ref loc) -> bool { +#if FMT_USE_LOCALE + auto& numpunct = + std::use_facet>(loc.get()); + auto separator = std::wstring(); + auto grouping = numpunct.grouping(); + if (!grouping.empty()) separator = std::wstring(1, numpunct.thousands_sep()); + return value.visit(loc_writer{out, specs, separator, grouping, {}}); +#endif + return false; +} + +template +void vformat_to(buffer& buf, basic_string_view fmt, + basic_format_args> args, + locale_ref loc = {}) { + static_assert(!std::is_same::value, ""); + auto out = basic_appender(buf); + parse_format_string( + fmt, format_handler{parse_context(fmt), {out, args, loc}}); +} +} // namespace detail + +FMT_BEGIN_EXPORT + +using wstring_view = basic_string_view; +using wformat_parse_context = parse_context; +using wformat_context = buffered_context; +using wformat_args = basic_format_args; +using wmemory_buffer = basic_memory_buffer; + +template struct basic_fstring { + private: + basic_string_view str_; + + static constexpr int num_static_named_args = + detail::count_static_named_args(); + + using checker = detail::format_string_checker< + Char, static_cast(sizeof...(T)), num_static_named_args, + num_static_named_args != detail::count_named_args()>; + + using arg_pack = detail::arg_pack; + + public: + using t = basic_fstring; + + template >::value)> + FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_fstring(const S& s) : str_(s) { + if (FMT_USE_CONSTEVAL) + detail::parse_format_string(s, checker(s, arg_pack())); + } + template ::value&& + std::is_same::value)> + FMT_ALWAYS_INLINE basic_fstring(const S&) : str_(S()) { + FMT_CONSTEXPR auto sv = basic_string_view(S()); + FMT_CONSTEXPR int ignore = + (parse_format_string(sv, checker(sv, arg_pack())), 0); + detail::ignore_unused(ignore); + } + basic_fstring(runtime_format_string fmt) : str_(fmt.str) {} + + operator basic_string_view() const { return str_; } + auto get() const -> basic_string_view { return str_; } +}; + +template +using basic_format_string = basic_fstring; + +template +using wformat_string = typename basic_format_string::t; +inline auto runtime(wstring_view s) -> runtime_format_string { + return {{s}}; +} + +template +constexpr auto make_wformat_args(T&... args) + -> decltype(fmt::make_format_args(args...)) { + return fmt::make_format_args(args...); +} + +#if !FMT_USE_NONTYPE_TEMPLATE_ARGS +inline namespace literals { +inline auto operator""_a(const wchar_t* s, size_t) -> detail::udl_arg { + return {s}; +} +} // namespace literals +#endif + +template +auto join(It begin, Sentinel end, wstring_view sep) + -> join_view { + return {begin, end, sep}; +} + +template ::value)> +auto join(Range&& range, wstring_view sep) + -> join_view { + return join(std::begin(range), std::end(range), sep); +} + +template +auto join(std::initializer_list list, wstring_view sep) + -> join_view { + return join(std::begin(list), std::end(list), sep); +} + +template ::value)> +auto join(const Tuple& tuple, basic_string_view sep) + -> tuple_join_view { + return {tuple, sep}; +} + +template ::value)> +auto vformat(basic_string_view fmt, + basic_format_args> args) + -> std::basic_string { + auto buf = basic_memory_buffer(); + detail::vformat_to(buf, fmt, args); + return {buf.data(), buf.size()}; +} + +template +auto format(wformat_string fmt, T&&... args) -> std::wstring { + return vformat(fmt::wstring_view(fmt), fmt::make_wformat_args(args...)); +} + +template +auto format_to(OutputIt out, wformat_string fmt, T&&... args) + -> OutputIt { + return vformat_to(out, fmt::wstring_view(fmt), + fmt::make_wformat_args(args...)); +} + +// Pass char_t as a default template parameter instead of using +// std::basic_string> to reduce the symbol size. +template , + FMT_ENABLE_IF(!std::is_same::value && + !std::is_same::value)> +auto format(const S& fmt, T&&... args) -> std::basic_string { + return vformat(detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_exotic_char::value)> +inline auto vformat(locale_ref loc, const S& fmt, + basic_format_args> args) + -> std::basic_string { + auto buf = basic_memory_buffer(); + detail::vformat_to(buf, detail::to_string_view(fmt), args, loc); + return {buf.data(), buf.size()}; +} + +template , + FMT_ENABLE_IF(detail::is_exotic_char::value)> +inline auto format(locale_ref loc, const S& fmt, T&&... args) + -> std::basic_string { + return vformat(loc, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value&& + detail::is_exotic_char::value)> +auto vformat_to(OutputIt out, const S& fmt, + basic_format_args> args) -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, detail::to_string_view(fmt), args); + return detail::get_iterator(buf, out); +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value && + !std::is_same::value && + !std::is_same::value)> +inline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt { + return vformat_to(out, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value&& + detail::is_exotic_char::value)> +inline auto vformat_to(OutputIt out, locale_ref loc, const S& fmt, + basic_format_args> args) + -> OutputIt { + auto&& buf = detail::get_buffer(out); + vformat_to(buf, detail::to_string_view(fmt), args, loc); + return detail::get_iterator(buf, out); +} + +template , + bool enable = detail::is_output_iterator::value && + detail::is_exotic_char::value> +inline auto format_to(OutputIt out, locale_ref loc, const S& fmt, T&&... args) + -> typename std::enable_if::type { + return vformat_to(out, loc, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template ::value&& + detail::is_exotic_char::value)> +inline auto vformat_to_n(OutputIt out, size_t n, basic_string_view fmt, + basic_format_args> args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + detail::vformat_to(buf, fmt, args); + return {buf.out(), buf.count()}; +} + +template , + FMT_ENABLE_IF(detail::is_output_iterator::value&& + detail::is_exotic_char::value)> +inline auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args) + -> format_to_n_result { + return vformat_to_n(out, n, fmt::basic_string_view(fmt), + fmt::make_format_args>(args...)); +} + +template , + FMT_ENABLE_IF(detail::is_exotic_char::value)> +inline auto formatted_size(const S& fmt, T&&... args) -> size_t { + auto buf = detail::counting_buffer(); + detail::vformat_to(buf, detail::to_string_view(fmt), + fmt::make_format_args>(args...)); + return buf.count(); +} + +inline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) { + auto buf = wmemory_buffer(); + detail::vformat_to(buf, fmt, args); + buf.push_back(L'\0'); + if (std::fputws(buf.data(), f) == -1) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); +} + +inline void vprint(wstring_view fmt, wformat_args args) { + vprint(stdout, fmt, args); +} + +template +void print(std::FILE* f, wformat_string fmt, T&&... args) { + return vprint(f, wstring_view(fmt), fmt::make_wformat_args(args...)); +} + +template void print(wformat_string fmt, T&&... args) { + return vprint(wstring_view(fmt), fmt::make_wformat_args(args...)); +} + +template +void println(std::FILE* f, wformat_string fmt, T&&... args) { + return print(f, L"{}\n", fmt::format(fmt, std::forward(args)...)); +} + +template void println(wformat_string fmt, T&&... args) { + return print(L"{}\n", fmt::format(fmt, std::forward(args)...)); +} + +inline auto vformat(text_style ts, wstring_view fmt, wformat_args args) + -> std::wstring { + auto buf = wmemory_buffer(); + detail::vformat_to(buf, ts, fmt, args); + return {buf.data(), buf.size()}; +} + +template +inline auto format(text_style ts, wformat_string fmt, T&&... args) + -> std::wstring { + return fmt::vformat(ts, fmt, fmt::make_wformat_args(args...)); +} + +inline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) { + auto buffer = basic_memory_buffer(); + detail::vformat_to(buffer, fmt, args); + detail::write_buffer(os, buffer); +} + +template +void print(std::wostream& os, wformat_string fmt, T&&... args) { + vprint(os, fmt, fmt::make_format_args>(args...)); +} + +template +void println(std::wostream& os, wformat_string fmt, T&&... args) { + print(os, L"{}\n", fmt::format(fmt, std::forward(args)...)); +} + +/// Converts `value` to `std::wstring` using the default format for type `T`. +template inline auto to_wstring(const T& value) -> std::wstring { + return format(FMT_STRING(L"{}"), value); +} +FMT_END_EXPORT +FMT_END_NAMESPACE + +#endif // FMT_XCHAR_H_ diff --git a/vendor/btop/include/widechar_width.hpp b/vendor/btop/include/widechar_width.hpp new file mode 100644 index 000000000..c91fb7e10 --- /dev/null +++ b/vendor/btop/include/widechar_width.hpp @@ -0,0 +1,1571 @@ +/** + * widechar_width.h for Unicode 17.0.0 + * See https://github.com/ridiculousfish/widecharwidth/ + * + * SHA1 file hashes: + * ( + * the hashes for generate.py and the template are git object hashes, + * use `git log --all --find-object=` in the widecharwidth repository + * to see which commit they correspond to, + * or run `git hash-object` on the file to compare. + * The other hashes are simple `sha1sum` style hashes. + * ) + * + * generate.py: b35da43f176cc0d5880c67356ebb064048c5bac4 + * template.js: 1249763c5b7c1e308aeb4ca64f1e15bce1fab9b3 + * UnicodeData.txt: 50dffef1b7d1f97b72e4c2adceb9b2245f0f34ba + * EastAsianWidth.txt: 2cadc5034b6206ad84b75898a1d4186bb38fc12b + * emoji-data.txt: 3d123e12f70f63e609c4281ce83dfdd9ac7443d2 + */ + +#ifndef WIDECHAR_WIDTH_H +#define WIDECHAR_WIDTH_H + +#include +#include +#include +#include + +namespace { + +/* Special width values */ +enum { + widechar_nonprint = 0, // The character is not printable. + widechar_combining = 0, // The character is a zero-width combiner. + widechar_ambiguous = 1, // The character is East-Asian ambiguous width. + widechar_private_use = 1, // The character is for private use. + widechar_unassigned = 0, // The character is unassigned. + widechar_widened_in_9 = 2, // Width is 1 in Unicode 8, 2 in Unicode 9+. + widechar_non_character = 0 // The character is a noncharacter. +}; + +/* An inclusive range of characters. */ +struct widechar_range { + uint32_t lo; + uint32_t hi; +}; + +/* Simple ASCII characters - used a lot, so we check them first. */ +static const struct widechar_range widechar_ascii_table[] = { + {0x00020, 0x0007E} +}; + +/* Private usage range. */ +static const struct widechar_range widechar_private_table[] = { + {0x0E000, 0x0F8FF}, + {0xF0000, 0xFFFFD}, + {0x100000, 0x10FFFD} +}; + +/* Nonprinting characters. */ +static const struct widechar_range widechar_nonprint_table[] = { + {0x00000, 0x0001F}, + {0x0007F, 0x0009F}, + {0x000AD, 0x000AD}, + {0x00600, 0x00605}, + {0x0061C, 0x0061C}, + {0x006DD, 0x006DD}, + {0x0070F, 0x0070F}, + {0x00890, 0x00891}, + {0x008E2, 0x008E2}, + {0x0180E, 0x0180E}, + {0x0200B, 0x0200F}, + {0x02028, 0x0202E}, + {0x02060, 0x02064}, + {0x02066, 0x0206F}, + {0x0D800, 0x0DFFF}, + {0x0FEFF, 0x0FEFF}, + {0x0FFF9, 0x0FFFB}, + {0x110BD, 0x110BD}, + {0x110CD, 0x110CD}, + {0x13430, 0x1343F}, + {0x1BCA0, 0x1BCA3}, + {0x1D173, 0x1D17A}, + {0xE0001, 0xE0001}, + {0xE0020, 0xE007F} +}; + +/* Width 0 combining marks. */ +static const struct widechar_range widechar_combining_table[] = { + {0x00300, 0x0036F}, + {0x00483, 0x00489}, + {0x00591, 0x005BD}, + {0x005BF, 0x005BF}, + {0x005C1, 0x005C2}, + {0x005C4, 0x005C5}, + {0x005C7, 0x005C7}, + {0x00610, 0x0061A}, + {0x0064B, 0x0065F}, + {0x00670, 0x00670}, + {0x006D6, 0x006DC}, + {0x006DF, 0x006E4}, + {0x006E7, 0x006E8}, + {0x006EA, 0x006ED}, + {0x00711, 0x00711}, + {0x00730, 0x0074A}, + {0x007A6, 0x007B0}, + {0x007EB, 0x007F3}, + {0x007FD, 0x007FD}, + {0x00816, 0x00819}, + {0x0081B, 0x00823}, + {0x00825, 0x00827}, + {0x00829, 0x0082D}, + {0x00859, 0x0085B}, + {0x00897, 0x0089F}, + {0x008CA, 0x008E1}, + {0x008E3, 0x00903}, + {0x0093A, 0x0093C}, + {0x0093E, 0x0094F}, + {0x00951, 0x00957}, + {0x00962, 0x00963}, + {0x00981, 0x00983}, + {0x009BC, 0x009BC}, + {0x009BE, 0x009C4}, + {0x009C7, 0x009C8}, + {0x009CB, 0x009CD}, + {0x009D7, 0x009D7}, + {0x009E2, 0x009E3}, + {0x009FE, 0x009FE}, + {0x00A01, 0x00A03}, + {0x00A3C, 0x00A3C}, + {0x00A3E, 0x00A42}, + {0x00A47, 0x00A48}, + {0x00A4B, 0x00A4D}, + {0x00A51, 0x00A51}, + {0x00A70, 0x00A71}, + {0x00A75, 0x00A75}, + {0x00A81, 0x00A83}, + {0x00ABC, 0x00ABC}, + {0x00ABE, 0x00AC5}, + {0x00AC7, 0x00AC9}, + {0x00ACB, 0x00ACD}, + {0x00AE2, 0x00AE3}, + {0x00AFA, 0x00AFF}, + {0x00B01, 0x00B03}, + {0x00B3C, 0x00B3C}, + {0x00B3E, 0x00B44}, + {0x00B47, 0x00B48}, + {0x00B4B, 0x00B4D}, + {0x00B55, 0x00B57}, + {0x00B62, 0x00B63}, + {0x00B82, 0x00B82}, + {0x00BBE, 0x00BC2}, + {0x00BC6, 0x00BC8}, + {0x00BCA, 0x00BCD}, + {0x00BD7, 0x00BD7}, + {0x00C00, 0x00C04}, + {0x00C3C, 0x00C3C}, + {0x00C3E, 0x00C44}, + {0x00C46, 0x00C48}, + {0x00C4A, 0x00C4D}, + {0x00C55, 0x00C56}, + {0x00C62, 0x00C63}, + {0x00C81, 0x00C83}, + {0x00CBC, 0x00CBC}, + {0x00CBE, 0x00CC4}, + {0x00CC6, 0x00CC8}, + {0x00CCA, 0x00CCD}, + {0x00CD5, 0x00CD6}, + {0x00CE2, 0x00CE3}, + {0x00CF3, 0x00CF3}, + {0x00D00, 0x00D03}, + {0x00D3B, 0x00D3C}, + {0x00D3E, 0x00D44}, + {0x00D46, 0x00D48}, + {0x00D4A, 0x00D4D}, + {0x00D57, 0x00D57}, + {0x00D62, 0x00D63}, + {0x00D81, 0x00D83}, + {0x00DCA, 0x00DCA}, + {0x00DCF, 0x00DD4}, + {0x00DD6, 0x00DD6}, + {0x00DD8, 0x00DDF}, + {0x00DF2, 0x00DF3}, + {0x00E31, 0x00E31}, + {0x00E34, 0x00E3A}, + {0x00E47, 0x00E4E}, + {0x00EB1, 0x00EB1}, + {0x00EB4, 0x00EBC}, + {0x00EC8, 0x00ECE}, + {0x00F18, 0x00F19}, + {0x00F35, 0x00F35}, + {0x00F37, 0x00F37}, + {0x00F39, 0x00F39}, + {0x00F3E, 0x00F3F}, + {0x00F71, 0x00F84}, + {0x00F86, 0x00F87}, + {0x00F8D, 0x00F97}, + {0x00F99, 0x00FBC}, + {0x00FC6, 0x00FC6}, + {0x0102B, 0x0103E}, + {0x01056, 0x01059}, + {0x0105E, 0x01060}, + {0x01062, 0x01064}, + {0x01067, 0x0106D}, + {0x01071, 0x01074}, + {0x01082, 0x0108D}, + {0x0108F, 0x0108F}, + {0x0109A, 0x0109D}, + {0x0135D, 0x0135F}, + {0x01712, 0x01715}, + {0x01732, 0x01734}, + {0x01752, 0x01753}, + {0x01772, 0x01773}, + {0x017B4, 0x017D3}, + {0x017DD, 0x017DD}, + {0x0180B, 0x0180D}, + {0x0180F, 0x0180F}, + {0x01885, 0x01886}, + {0x018A9, 0x018A9}, + {0x01920, 0x0192B}, + {0x01930, 0x0193B}, + {0x01A17, 0x01A1B}, + {0x01A55, 0x01A5E}, + {0x01A60, 0x01A7C}, + {0x01A7F, 0x01A7F}, + {0x01AB0, 0x01ADD}, + {0x01AE0, 0x01AEB}, + {0x01B00, 0x01B04}, + {0x01B34, 0x01B44}, + {0x01B6B, 0x01B73}, + {0x01B80, 0x01B82}, + {0x01BA1, 0x01BAD}, + {0x01BE6, 0x01BF3}, + {0x01C24, 0x01C37}, + {0x01CD0, 0x01CD2}, + {0x01CD4, 0x01CE8}, + {0x01CED, 0x01CED}, + {0x01CF4, 0x01CF4}, + {0x01CF7, 0x01CF9}, + {0x01DC0, 0x01DFF}, + {0x020D0, 0x020F0}, + {0x02CEF, 0x02CF1}, + {0x02D7F, 0x02D7F}, + {0x02DE0, 0x02DFF}, + {0x0302A, 0x0302F}, + {0x03099, 0x0309A}, + {0x0A66F, 0x0A672}, + {0x0A674, 0x0A67D}, + {0x0A69E, 0x0A69F}, + {0x0A6F0, 0x0A6F1}, + {0x0A802, 0x0A802}, + {0x0A806, 0x0A806}, + {0x0A80B, 0x0A80B}, + {0x0A823, 0x0A827}, + {0x0A82C, 0x0A82C}, + {0x0A880, 0x0A881}, + {0x0A8B4, 0x0A8C5}, + {0x0A8E0, 0x0A8F1}, + {0x0A8FF, 0x0A8FF}, + {0x0A926, 0x0A92D}, + {0x0A947, 0x0A953}, + {0x0A980, 0x0A983}, + {0x0A9B3, 0x0A9C0}, + {0x0A9E5, 0x0A9E5}, + {0x0AA29, 0x0AA36}, + {0x0AA43, 0x0AA43}, + {0x0AA4C, 0x0AA4D}, + {0x0AA7B, 0x0AA7D}, + {0x0AAB0, 0x0AAB0}, + {0x0AAB2, 0x0AAB4}, + {0x0AAB7, 0x0AAB8}, + {0x0AABE, 0x0AABF}, + {0x0AAC1, 0x0AAC1}, + {0x0AAEB, 0x0AAEF}, + {0x0AAF5, 0x0AAF6}, + {0x0ABE3, 0x0ABEA}, + {0x0ABEC, 0x0ABED}, + {0x0FB1E, 0x0FB1E}, + {0x0FE00, 0x0FE0F}, + {0x0FE20, 0x0FE2F}, + {0x101FD, 0x101FD}, + {0x102E0, 0x102E0}, + {0x10376, 0x1037A}, + {0x10A01, 0x10A03}, + {0x10A05, 0x10A06}, + {0x10A0C, 0x10A0F}, + {0x10A38, 0x10A3A}, + {0x10A3F, 0x10A3F}, + {0x10AE5, 0x10AE6}, + {0x10D24, 0x10D27}, + {0x10D69, 0x10D6D}, + {0x10EAB, 0x10EAC}, + {0x10EFA, 0x10EFF}, + {0x10F46, 0x10F50}, + {0x10F82, 0x10F85}, + {0x11000, 0x11002}, + {0x11038, 0x11046}, + {0x11070, 0x11070}, + {0x11073, 0x11074}, + {0x1107F, 0x11082}, + {0x110B0, 0x110BA}, + {0x110C2, 0x110C2}, + {0x11100, 0x11102}, + {0x11127, 0x11134}, + {0x11145, 0x11146}, + {0x11173, 0x11173}, + {0x11180, 0x11182}, + {0x111B3, 0x111C0}, + {0x111C9, 0x111CC}, + {0x111CE, 0x111CF}, + {0x1122C, 0x11237}, + {0x1123E, 0x1123E}, + {0x11241, 0x11241}, + {0x112DF, 0x112EA}, + {0x11300, 0x11303}, + {0x1133B, 0x1133C}, + {0x1133E, 0x11344}, + {0x11347, 0x11348}, + {0x1134B, 0x1134D}, + {0x11357, 0x11357}, + {0x11362, 0x11363}, + {0x11366, 0x1136C}, + {0x11370, 0x11374}, + {0x113B8, 0x113C0}, + {0x113C2, 0x113C2}, + {0x113C5, 0x113C5}, + {0x113C7, 0x113CA}, + {0x113CC, 0x113D0}, + {0x113D2, 0x113D2}, + {0x113E1, 0x113E2}, + {0x11435, 0x11446}, + {0x1145E, 0x1145E}, + {0x114B0, 0x114C3}, + {0x115AF, 0x115B5}, + {0x115B8, 0x115C0}, + {0x115DC, 0x115DD}, + {0x11630, 0x11640}, + {0x116AB, 0x116B7}, + {0x1171D, 0x1172B}, + {0x1182C, 0x1183A}, + {0x11930, 0x11935}, + {0x11937, 0x11938}, + {0x1193B, 0x1193E}, + {0x11940, 0x11940}, + {0x11942, 0x11943}, + {0x119D1, 0x119D7}, + {0x119DA, 0x119E0}, + {0x119E4, 0x119E4}, + {0x11A01, 0x11A0A}, + {0x11A33, 0x11A39}, + {0x11A3B, 0x11A3E}, + {0x11A47, 0x11A47}, + {0x11A51, 0x11A5B}, + {0x11A8A, 0x11A99}, + {0x11B60, 0x11B67}, + {0x11C2F, 0x11C36}, + {0x11C38, 0x11C3F}, + {0x11C92, 0x11CA7}, + {0x11CA9, 0x11CB6}, + {0x11D31, 0x11D36}, + {0x11D3A, 0x11D3A}, + {0x11D3C, 0x11D3D}, + {0x11D3F, 0x11D45}, + {0x11D47, 0x11D47}, + {0x11D8A, 0x11D8E}, + {0x11D90, 0x11D91}, + {0x11D93, 0x11D97}, + {0x11EF3, 0x11EF6}, + {0x11F00, 0x11F01}, + {0x11F03, 0x11F03}, + {0x11F34, 0x11F3A}, + {0x11F3E, 0x11F42}, + {0x11F5A, 0x11F5A}, + {0x13440, 0x13440}, + {0x13447, 0x13455}, + {0x1611E, 0x1612F}, + {0x16AF0, 0x16AF4}, + {0x16B30, 0x16B36}, + {0x16F4F, 0x16F4F}, + {0x16F51, 0x16F87}, + {0x16F8F, 0x16F92}, + {0x16FE4, 0x16FE4}, + {0x16FF0, 0x16FF1}, + {0x1BC9D, 0x1BC9E}, + {0x1CF00, 0x1CF2D}, + {0x1CF30, 0x1CF46}, + {0x1D165, 0x1D169}, + {0x1D16D, 0x1D172}, + {0x1D17B, 0x1D182}, + {0x1D185, 0x1D18B}, + {0x1D1AA, 0x1D1AD}, + {0x1D242, 0x1D244}, + {0x1DA00, 0x1DA36}, + {0x1DA3B, 0x1DA6C}, + {0x1DA75, 0x1DA75}, + {0x1DA84, 0x1DA84}, + {0x1DA9B, 0x1DA9F}, + {0x1DAA1, 0x1DAAF}, + {0x1E000, 0x1E006}, + {0x1E008, 0x1E018}, + {0x1E01B, 0x1E021}, + {0x1E023, 0x1E024}, + {0x1E026, 0x1E02A}, + {0x1E08F, 0x1E08F}, + {0x1E130, 0x1E136}, + {0x1E2AE, 0x1E2AE}, + {0x1E2EC, 0x1E2EF}, + {0x1E4EC, 0x1E4EF}, + {0x1E5EE, 0x1E5EF}, + {0x1E6E3, 0x1E6E3}, + {0x1E6E6, 0x1E6E6}, + {0x1E6EE, 0x1E6EF}, + {0x1E6F5, 0x1E6F5}, + {0x1E8D0, 0x1E8D6}, + {0x1E944, 0x1E94A}, + {0xE0100, 0xE01EF} +}; + +/* Width 0 combining letters. */ +static const struct widechar_range widechar_combiningletters_table[] = { + {0x01160, 0x011FF}, + {0x0D7B0, 0x0D7FF} +}; + +/* Width 2 characters. */ +static const struct widechar_range widechar_doublewide_table[] = { + {0x01100, 0x0115F}, + {0x02329, 0x0232A}, + {0x02630, 0x02637}, + {0x0268A, 0x0268F}, + {0x02E80, 0x02E99}, + {0x02E9B, 0x02EF3}, + {0x02F00, 0x02FD5}, + {0x02FF0, 0x0303E}, + {0x03041, 0x03096}, + {0x03099, 0x030FF}, + {0x03105, 0x0312F}, + {0x03131, 0x0318E}, + {0x03190, 0x031E5}, + {0x031EF, 0x0321E}, + {0x03220, 0x03247}, + {0x03250, 0x0A48C}, + {0x0A490, 0x0A4C6}, + {0x0A960, 0x0A97C}, + {0x0AC00, 0x0D7A3}, + {0x0F900, 0x0FAFF}, + {0x0FE10, 0x0FE19}, + {0x0FE30, 0x0FE52}, + {0x0FE54, 0x0FE66}, + {0x0FE68, 0x0FE6B}, + {0x0FF01, 0x0FF60}, + {0x0FFE0, 0x0FFE6}, + {0x16FE0, 0x16FE4}, + {0x16FF0, 0x16FF6}, + {0x17000, 0x18CD5}, + {0x18CFF, 0x18D1E}, + {0x18D80, 0x18DF2}, + {0x1AFF0, 0x1AFF3}, + {0x1AFF5, 0x1AFFB}, + {0x1AFFD, 0x1AFFE}, + {0x1B000, 0x1B122}, + {0x1B132, 0x1B132}, + {0x1B150, 0x1B152}, + {0x1B155, 0x1B155}, + {0x1B164, 0x1B167}, + {0x1B170, 0x1B2FB}, + {0x1D300, 0x1D356}, + {0x1D360, 0x1D376}, + {0x1F200, 0x1F200}, + {0x1F202, 0x1F202}, + {0x1F210, 0x1F219}, + {0x1F21B, 0x1F22E}, + {0x1F230, 0x1F231}, + {0x1F237, 0x1F237}, + {0x1F23B, 0x1F23B}, + {0x1F240, 0x1F248}, + {0x1F260, 0x1F265}, + {0x1F57A, 0x1F57A}, + {0x1F5A4, 0x1F5A4}, + {0x1F6D1, 0x1F6D2}, + {0x1F6D5, 0x1F6D8}, + {0x1F6DC, 0x1F6DF}, + {0x1F6F4, 0x1F6FC}, + {0x1F7E0, 0x1F7EB}, + {0x1F7F0, 0x1F7F0}, + {0x1F90C, 0x1F90F}, + {0x1F919, 0x1F93A}, + {0x1F93C, 0x1F945}, + {0x1F947, 0x1F97F}, + {0x1F985, 0x1F9BF}, + {0x1F9C1, 0x1F9FF}, + {0x1FA70, 0x1FA7C}, + {0x1FA80, 0x1FA8A}, + {0x1FA8E, 0x1FAC6}, + {0x1FAC8, 0x1FAC8}, + {0x1FACD, 0x1FADC}, + {0x1FADF, 0x1FAEA}, + {0x1FAEF, 0x1FAF8}, + {0x20000, 0x2FFFD}, + {0x30000, 0x3FFFD} +}; + +/* Ambiguous-width characters. */ +static const struct widechar_range widechar_ambiguous_table[] = { + {0x000A1, 0x000A1}, + {0x000A4, 0x000A4}, + {0x000A7, 0x000A8}, + {0x000AA, 0x000AA}, + {0x000AD, 0x000AE}, + {0x000B0, 0x000B4}, + {0x000B6, 0x000BA}, + {0x000BC, 0x000BF}, + {0x000C6, 0x000C6}, + {0x000D0, 0x000D0}, + {0x000D7, 0x000D8}, + {0x000DE, 0x000E1}, + {0x000E6, 0x000E6}, + {0x000E8, 0x000EA}, + {0x000EC, 0x000ED}, + {0x000F0, 0x000F0}, + {0x000F2, 0x000F3}, + {0x000F7, 0x000FA}, + {0x000FC, 0x000FC}, + {0x000FE, 0x000FE}, + {0x00101, 0x00101}, + {0x00111, 0x00111}, + {0x00113, 0x00113}, + {0x0011B, 0x0011B}, + {0x00126, 0x00127}, + {0x0012B, 0x0012B}, + {0x00131, 0x00133}, + {0x00138, 0x00138}, + {0x0013F, 0x00142}, + {0x00144, 0x00144}, + {0x00148, 0x0014B}, + {0x0014D, 0x0014D}, + {0x00152, 0x00153}, + {0x00166, 0x00167}, + {0x0016B, 0x0016B}, + {0x001CE, 0x001CE}, + {0x001D0, 0x001D0}, + {0x001D2, 0x001D2}, + {0x001D4, 0x001D4}, + {0x001D6, 0x001D6}, + {0x001D8, 0x001D8}, + {0x001DA, 0x001DA}, + {0x001DC, 0x001DC}, + {0x00251, 0x00251}, + {0x00261, 0x00261}, + {0x002C4, 0x002C4}, + {0x002C7, 0x002C7}, + {0x002C9, 0x002CB}, + {0x002CD, 0x002CD}, + {0x002D0, 0x002D0}, + {0x002D8, 0x002DB}, + {0x002DD, 0x002DD}, + {0x002DF, 0x002DF}, + {0x00300, 0x0036F}, + {0x00391, 0x003A1}, + {0x003A3, 0x003A9}, + {0x003B1, 0x003C1}, + {0x003C3, 0x003C9}, + {0x00401, 0x00401}, + {0x00410, 0x0044F}, + {0x00451, 0x00451}, + {0x02010, 0x02010}, + {0x02013, 0x02016}, + {0x02018, 0x02019}, + {0x0201C, 0x0201D}, + {0x02020, 0x02022}, + {0x02024, 0x02027}, + {0x02030, 0x02030}, + {0x02032, 0x02033}, + {0x02035, 0x02035}, + {0x0203B, 0x0203B}, + {0x0203E, 0x0203E}, + {0x02074, 0x02074}, + {0x0207F, 0x0207F}, + {0x02081, 0x02084}, + {0x020AC, 0x020AC}, + {0x02103, 0x02103}, + {0x02105, 0x02105}, + {0x02109, 0x02109}, + {0x02113, 0x02113}, + {0x02116, 0x02116}, + {0x02121, 0x02122}, + {0x02126, 0x02126}, + {0x0212B, 0x0212B}, + {0x02153, 0x02154}, + {0x0215B, 0x0215E}, + {0x02160, 0x0216B}, + {0x02170, 0x02179}, + {0x02189, 0x02189}, + {0x02190, 0x02199}, + {0x021B8, 0x021B9}, + {0x021D2, 0x021D2}, + {0x021D4, 0x021D4}, + {0x021E7, 0x021E7}, + {0x02200, 0x02200}, + {0x02202, 0x02203}, + {0x02207, 0x02208}, + {0x0220B, 0x0220B}, + {0x0220F, 0x0220F}, + {0x02211, 0x02211}, + {0x02215, 0x02215}, + {0x0221A, 0x0221A}, + {0x0221D, 0x02220}, + {0x02223, 0x02223}, + {0x02225, 0x02225}, + {0x02227, 0x0222C}, + {0x0222E, 0x0222E}, + {0x02234, 0x02237}, + {0x0223C, 0x0223D}, + {0x02248, 0x02248}, + {0x0224C, 0x0224C}, + {0x02252, 0x02252}, + {0x02260, 0x02261}, + {0x02264, 0x02267}, + {0x0226A, 0x0226B}, + {0x0226E, 0x0226F}, + {0x02282, 0x02283}, + {0x02286, 0x02287}, + {0x02295, 0x02295}, + {0x02299, 0x02299}, + {0x022A5, 0x022A5}, + {0x022BF, 0x022BF}, + {0x02312, 0x02312}, + {0x02460, 0x024E9}, + {0x024EB, 0x0254B}, + {0x02550, 0x02573}, + {0x02580, 0x0258F}, + {0x02592, 0x02595}, + {0x025A0, 0x025A1}, + {0x025A3, 0x025A9}, + {0x025B2, 0x025B3}, + {0x025B6, 0x025B7}, + {0x025BC, 0x025BD}, + {0x025C0, 0x025C1}, + {0x025C6, 0x025C8}, + {0x025CB, 0x025CB}, + {0x025CE, 0x025D1}, + {0x025E2, 0x025E5}, + {0x025EF, 0x025EF}, + {0x02605, 0x02606}, + {0x02609, 0x02609}, + {0x0260E, 0x0260F}, + {0x0261C, 0x0261C}, + {0x0261E, 0x0261E}, + {0x02640, 0x02640}, + {0x02642, 0x02642}, + {0x02660, 0x02661}, + {0x02663, 0x02665}, + {0x02667, 0x0266A}, + {0x0266C, 0x0266D}, + {0x0266F, 0x0266F}, + {0x0269E, 0x0269F}, + {0x026BF, 0x026BF}, + {0x026C6, 0x026CD}, + {0x026CF, 0x026D3}, + {0x026D5, 0x026E1}, + {0x026E3, 0x026E3}, + {0x026E8, 0x026E9}, + {0x026EB, 0x026F1}, + {0x026F4, 0x026F4}, + {0x026F6, 0x026F9}, + {0x026FB, 0x026FC}, + {0x026FE, 0x026FF}, + {0x0273D, 0x0273D}, + {0x02776, 0x0277F}, + {0x02B56, 0x02B59}, + {0x03248, 0x0324F}, + {0x0E000, 0x0F8FF}, + {0x0FE00, 0x0FE0F}, + {0x0FFFD, 0x0FFFD}, + {0x1F100, 0x1F10A}, + {0x1F110, 0x1F12D}, + {0x1F130, 0x1F169}, + {0x1F170, 0x1F18D}, + {0x1F18F, 0x1F190}, + {0x1F19B, 0x1F1AC}, + {0xE0100, 0xE01EF}, + {0xF0000, 0xFFFFD}, + {0x100000, 0x10FFFD} +}; + +/* Unassigned characters. */ +static const struct widechar_range widechar_unassigned_table[] = { + {0x00378, 0x00379}, + {0x00380, 0x00383}, + {0x0038B, 0x0038B}, + {0x0038D, 0x0038D}, + {0x003A2, 0x003A2}, + {0x00530, 0x00530}, + {0x00557, 0x00558}, + {0x0058B, 0x0058C}, + {0x00590, 0x00590}, + {0x005C8, 0x005CF}, + {0x005EB, 0x005EE}, + {0x005F5, 0x005FF}, + {0x0070E, 0x0070E}, + {0x0074B, 0x0074C}, + {0x007B2, 0x007BF}, + {0x007FB, 0x007FC}, + {0x0082E, 0x0082F}, + {0x0083F, 0x0083F}, + {0x0085C, 0x0085D}, + {0x0085F, 0x0085F}, + {0x0086B, 0x0086F}, + {0x00892, 0x00896}, + {0x00984, 0x00984}, + {0x0098D, 0x0098E}, + {0x00991, 0x00992}, + {0x009A9, 0x009A9}, + {0x009B1, 0x009B1}, + {0x009B3, 0x009B5}, + {0x009BA, 0x009BB}, + {0x009C5, 0x009C6}, + {0x009C9, 0x009CA}, + {0x009CF, 0x009D6}, + {0x009D8, 0x009DB}, + {0x009DE, 0x009DE}, + {0x009E4, 0x009E5}, + {0x009FF, 0x00A00}, + {0x00A04, 0x00A04}, + {0x00A0B, 0x00A0E}, + {0x00A11, 0x00A12}, + {0x00A29, 0x00A29}, + {0x00A31, 0x00A31}, + {0x00A34, 0x00A34}, + {0x00A37, 0x00A37}, + {0x00A3A, 0x00A3B}, + {0x00A3D, 0x00A3D}, + {0x00A43, 0x00A46}, + {0x00A49, 0x00A4A}, + {0x00A4E, 0x00A50}, + {0x00A52, 0x00A58}, + {0x00A5D, 0x00A5D}, + {0x00A5F, 0x00A65}, + {0x00A77, 0x00A80}, + {0x00A84, 0x00A84}, + {0x00A8E, 0x00A8E}, + {0x00A92, 0x00A92}, + {0x00AA9, 0x00AA9}, + {0x00AB1, 0x00AB1}, + {0x00AB4, 0x00AB4}, + {0x00ABA, 0x00ABB}, + {0x00AC6, 0x00AC6}, + {0x00ACA, 0x00ACA}, + {0x00ACE, 0x00ACF}, + {0x00AD1, 0x00ADF}, + {0x00AE4, 0x00AE5}, + {0x00AF2, 0x00AF8}, + {0x00B00, 0x00B00}, + {0x00B04, 0x00B04}, + {0x00B0D, 0x00B0E}, + {0x00B11, 0x00B12}, + {0x00B29, 0x00B29}, + {0x00B31, 0x00B31}, + {0x00B34, 0x00B34}, + {0x00B3A, 0x00B3B}, + {0x00B45, 0x00B46}, + {0x00B49, 0x00B4A}, + {0x00B4E, 0x00B54}, + {0x00B58, 0x00B5B}, + {0x00B5E, 0x00B5E}, + {0x00B64, 0x00B65}, + {0x00B78, 0x00B81}, + {0x00B84, 0x00B84}, + {0x00B8B, 0x00B8D}, + {0x00B91, 0x00B91}, + {0x00B96, 0x00B98}, + {0x00B9B, 0x00B9B}, + {0x00B9D, 0x00B9D}, + {0x00BA0, 0x00BA2}, + {0x00BA5, 0x00BA7}, + {0x00BAB, 0x00BAD}, + {0x00BBA, 0x00BBD}, + {0x00BC3, 0x00BC5}, + {0x00BC9, 0x00BC9}, + {0x00BCE, 0x00BCF}, + {0x00BD1, 0x00BD6}, + {0x00BD8, 0x00BE5}, + {0x00BFB, 0x00BFF}, + {0x00C0D, 0x00C0D}, + {0x00C11, 0x00C11}, + {0x00C29, 0x00C29}, + {0x00C3A, 0x00C3B}, + {0x00C45, 0x00C45}, + {0x00C49, 0x00C49}, + {0x00C4E, 0x00C54}, + {0x00C57, 0x00C57}, + {0x00C5B, 0x00C5B}, + {0x00C5E, 0x00C5F}, + {0x00C64, 0x00C65}, + {0x00C70, 0x00C76}, + {0x00C8D, 0x00C8D}, + {0x00C91, 0x00C91}, + {0x00CA9, 0x00CA9}, + {0x00CB4, 0x00CB4}, + {0x00CBA, 0x00CBB}, + {0x00CC5, 0x00CC5}, + {0x00CC9, 0x00CC9}, + {0x00CCE, 0x00CD4}, + {0x00CD7, 0x00CDB}, + {0x00CDF, 0x00CDF}, + {0x00CE4, 0x00CE5}, + {0x00CF0, 0x00CF0}, + {0x00CF4, 0x00CFF}, + {0x00D0D, 0x00D0D}, + {0x00D11, 0x00D11}, + {0x00D45, 0x00D45}, + {0x00D49, 0x00D49}, + {0x00D50, 0x00D53}, + {0x00D64, 0x00D65}, + {0x00D80, 0x00D80}, + {0x00D84, 0x00D84}, + {0x00D97, 0x00D99}, + {0x00DB2, 0x00DB2}, + {0x00DBC, 0x00DBC}, + {0x00DBE, 0x00DBF}, + {0x00DC7, 0x00DC9}, + {0x00DCB, 0x00DCE}, + {0x00DD5, 0x00DD5}, + {0x00DD7, 0x00DD7}, + {0x00DE0, 0x00DE5}, + {0x00DF0, 0x00DF1}, + {0x00DF5, 0x00E00}, + {0x00E3B, 0x00E3E}, + {0x00E5C, 0x00E80}, + {0x00E83, 0x00E83}, + {0x00E85, 0x00E85}, + {0x00E8B, 0x00E8B}, + {0x00EA4, 0x00EA4}, + {0x00EA6, 0x00EA6}, + {0x00EBE, 0x00EBF}, + {0x00EC5, 0x00EC5}, + {0x00EC7, 0x00EC7}, + {0x00ECF, 0x00ECF}, + {0x00EDA, 0x00EDB}, + {0x00EE0, 0x00EFF}, + {0x00F48, 0x00F48}, + {0x00F6D, 0x00F70}, + {0x00F98, 0x00F98}, + {0x00FBD, 0x00FBD}, + {0x00FCD, 0x00FCD}, + {0x00FDB, 0x00FFF}, + {0x010C6, 0x010C6}, + {0x010C8, 0x010CC}, + {0x010CE, 0x010CF}, + {0x01249, 0x01249}, + {0x0124E, 0x0124F}, + {0x01257, 0x01257}, + {0x01259, 0x01259}, + {0x0125E, 0x0125F}, + {0x01289, 0x01289}, + {0x0128E, 0x0128F}, + {0x012B1, 0x012B1}, + {0x012B6, 0x012B7}, + {0x012BF, 0x012BF}, + {0x012C1, 0x012C1}, + {0x012C6, 0x012C7}, + {0x012D7, 0x012D7}, + {0x01311, 0x01311}, + {0x01316, 0x01317}, + {0x0135B, 0x0135C}, + {0x0137D, 0x0137F}, + {0x0139A, 0x0139F}, + {0x013F6, 0x013F7}, + {0x013FE, 0x013FF}, + {0x0169D, 0x0169F}, + {0x016F9, 0x016FF}, + {0x01716, 0x0171E}, + {0x01737, 0x0173F}, + {0x01754, 0x0175F}, + {0x0176D, 0x0176D}, + {0x01771, 0x01771}, + {0x01774, 0x0177F}, + {0x017DE, 0x017DF}, + {0x017EA, 0x017EF}, + {0x017FA, 0x017FF}, + {0x0181A, 0x0181F}, + {0x01879, 0x0187F}, + {0x018AB, 0x018AF}, + {0x018F6, 0x018FF}, + {0x0191F, 0x0191F}, + {0x0192C, 0x0192F}, + {0x0193C, 0x0193F}, + {0x01941, 0x01943}, + {0x0196E, 0x0196F}, + {0x01975, 0x0197F}, + {0x019AC, 0x019AF}, + {0x019CA, 0x019CF}, + {0x019DB, 0x019DD}, + {0x01A1C, 0x01A1D}, + {0x01A5F, 0x01A5F}, + {0x01A7D, 0x01A7E}, + {0x01A8A, 0x01A8F}, + {0x01A9A, 0x01A9F}, + {0x01AAE, 0x01AAF}, + {0x01ADE, 0x01ADF}, + {0x01AEC, 0x01AFF}, + {0x01B4D, 0x01B4D}, + {0x01BF4, 0x01BFB}, + {0x01C38, 0x01C3A}, + {0x01C4A, 0x01C4C}, + {0x01C8B, 0x01C8F}, + {0x01CBB, 0x01CBC}, + {0x01CC8, 0x01CCF}, + {0x01CFB, 0x01CFF}, + {0x01F16, 0x01F17}, + {0x01F1E, 0x01F1F}, + {0x01F46, 0x01F47}, + {0x01F4E, 0x01F4F}, + {0x01F58, 0x01F58}, + {0x01F5A, 0x01F5A}, + {0x01F5C, 0x01F5C}, + {0x01F5E, 0x01F5E}, + {0x01F7E, 0x01F7F}, + {0x01FB5, 0x01FB5}, + {0x01FC5, 0x01FC5}, + {0x01FD4, 0x01FD5}, + {0x01FDC, 0x01FDC}, + {0x01FF0, 0x01FF1}, + {0x01FF5, 0x01FF5}, + {0x01FFF, 0x01FFF}, + {0x02065, 0x02065}, + {0x02072, 0x02073}, + {0x0208F, 0x0208F}, + {0x0209D, 0x0209F}, + {0x020C2, 0x020CF}, + {0x020F1, 0x020FF}, + {0x0218C, 0x0218F}, + {0x0242A, 0x0243F}, + {0x0244B, 0x0245F}, + {0x02B74, 0x02B75}, + {0x02CF4, 0x02CF8}, + {0x02D26, 0x02D26}, + {0x02D28, 0x02D2C}, + {0x02D2E, 0x02D2F}, + {0x02D68, 0x02D6E}, + {0x02D71, 0x02D7E}, + {0x02D97, 0x02D9F}, + {0x02DA7, 0x02DA7}, + {0x02DAF, 0x02DAF}, + {0x02DB7, 0x02DB7}, + {0x02DBF, 0x02DBF}, + {0x02DC7, 0x02DC7}, + {0x02DCF, 0x02DCF}, + {0x02DD7, 0x02DD7}, + {0x02DDF, 0x02DDF}, + {0x02E5E, 0x02E7F}, + {0x02E9A, 0x02E9A}, + {0x02EF4, 0x02EFF}, + {0x02FD6, 0x02FEF}, + {0x03040, 0x03040}, + {0x03097, 0x03098}, + {0x03100, 0x03104}, + {0x03130, 0x03130}, + {0x0318F, 0x0318F}, + {0x031E6, 0x031EE}, + {0x0321F, 0x0321F}, + {0x03401, 0x04DBE}, + {0x04E01, 0x09FFE}, + {0x0A48D, 0x0A48F}, + {0x0A4C7, 0x0A4CF}, + {0x0A62C, 0x0A63F}, + {0x0A6F8, 0x0A6FF}, + {0x0A7DD, 0x0A7F0}, + {0x0A82D, 0x0A82F}, + {0x0A83A, 0x0A83F}, + {0x0A878, 0x0A87F}, + {0x0A8C6, 0x0A8CD}, + {0x0A8DA, 0x0A8DF}, + {0x0A954, 0x0A95E}, + {0x0A97D, 0x0A97F}, + {0x0A9CE, 0x0A9CE}, + {0x0A9DA, 0x0A9DD}, + {0x0A9FF, 0x0A9FF}, + {0x0AA37, 0x0AA3F}, + {0x0AA4E, 0x0AA4F}, + {0x0AA5A, 0x0AA5B}, + {0x0AAC3, 0x0AADA}, + {0x0AAF7, 0x0AB00}, + {0x0AB07, 0x0AB08}, + {0x0AB0F, 0x0AB10}, + {0x0AB17, 0x0AB1F}, + {0x0AB27, 0x0AB27}, + {0x0AB2F, 0x0AB2F}, + {0x0AB6C, 0x0AB6F}, + {0x0ABEE, 0x0ABEF}, + {0x0ABFA, 0x0ABFF}, + {0x0AC01, 0x0D7A2}, + {0x0D7A4, 0x0D7AF}, + {0x0D7C7, 0x0D7CA}, + {0x0D7FC, 0x0D7FF}, + {0x0FA6E, 0x0FA6F}, + {0x0FADA, 0x0FAFF}, + {0x0FB07, 0x0FB12}, + {0x0FB18, 0x0FB1C}, + {0x0FB37, 0x0FB37}, + {0x0FB3D, 0x0FB3D}, + {0x0FB3F, 0x0FB3F}, + {0x0FB42, 0x0FB42}, + {0x0FB45, 0x0FB45}, + {0x0FE1A, 0x0FE1F}, + {0x0FE53, 0x0FE53}, + {0x0FE67, 0x0FE67}, + {0x0FE6C, 0x0FE6F}, + {0x0FE75, 0x0FE75}, + {0x0FEFD, 0x0FEFE}, + {0x0FF00, 0x0FF00}, + {0x0FFBF, 0x0FFC1}, + {0x0FFC8, 0x0FFC9}, + {0x0FFD0, 0x0FFD1}, + {0x0FFD8, 0x0FFD9}, + {0x0FFDD, 0x0FFDF}, + {0x0FFE7, 0x0FFE7}, + {0x0FFEF, 0x0FFF8}, + {0x1000C, 0x1000C}, + {0x10027, 0x10027}, + {0x1003B, 0x1003B}, + {0x1003E, 0x1003E}, + {0x1004E, 0x1004F}, + {0x1005E, 0x1007F}, + {0x100FB, 0x100FF}, + {0x10103, 0x10106}, + {0x10134, 0x10136}, + {0x1018F, 0x1018F}, + {0x1019D, 0x1019F}, + {0x101A1, 0x101CF}, + {0x101FE, 0x1027F}, + {0x1029D, 0x1029F}, + {0x102D1, 0x102DF}, + {0x102FC, 0x102FF}, + {0x10324, 0x1032C}, + {0x1034B, 0x1034F}, + {0x1037B, 0x1037F}, + {0x1039E, 0x1039E}, + {0x103C4, 0x103C7}, + {0x103D6, 0x103FF}, + {0x1049E, 0x1049F}, + {0x104AA, 0x104AF}, + {0x104D4, 0x104D7}, + {0x104FC, 0x104FF}, + {0x10528, 0x1052F}, + {0x10564, 0x1056E}, + {0x1057B, 0x1057B}, + {0x1058B, 0x1058B}, + {0x10593, 0x10593}, + {0x10596, 0x10596}, + {0x105A2, 0x105A2}, + {0x105B2, 0x105B2}, + {0x105BA, 0x105BA}, + {0x105BD, 0x105BF}, + {0x105F4, 0x105FF}, + {0x10737, 0x1073F}, + {0x10756, 0x1075F}, + {0x10768, 0x1077F}, + {0x10786, 0x10786}, + {0x107B1, 0x107B1}, + {0x107BB, 0x107FF}, + {0x10806, 0x10807}, + {0x10809, 0x10809}, + {0x10836, 0x10836}, + {0x10839, 0x1083B}, + {0x1083D, 0x1083E}, + {0x10856, 0x10856}, + {0x1089F, 0x108A6}, + {0x108B0, 0x108DF}, + {0x108F3, 0x108F3}, + {0x108F6, 0x108FA}, + {0x1091C, 0x1091E}, + {0x1093A, 0x1093E}, + {0x1095A, 0x1097F}, + {0x109B8, 0x109BB}, + {0x109D0, 0x109D1}, + {0x10A04, 0x10A04}, + {0x10A07, 0x10A0B}, + {0x10A14, 0x10A14}, + {0x10A18, 0x10A18}, + {0x10A36, 0x10A37}, + {0x10A3B, 0x10A3E}, + {0x10A49, 0x10A4F}, + {0x10A59, 0x10A5F}, + {0x10AA0, 0x10ABF}, + {0x10AE7, 0x10AEA}, + {0x10AF7, 0x10AFF}, + {0x10B36, 0x10B38}, + {0x10B56, 0x10B57}, + {0x10B73, 0x10B77}, + {0x10B92, 0x10B98}, + {0x10B9D, 0x10BA8}, + {0x10BB0, 0x10BFF}, + {0x10C49, 0x10C7F}, + {0x10CB3, 0x10CBF}, + {0x10CF3, 0x10CF9}, + {0x10D28, 0x10D2F}, + {0x10D3A, 0x10D3F}, + {0x10D66, 0x10D68}, + {0x10D86, 0x10D8D}, + {0x10D90, 0x10E5F}, + {0x10E7F, 0x10E7F}, + {0x10EAA, 0x10EAA}, + {0x10EAE, 0x10EAF}, + {0x10EB2, 0x10EC1}, + {0x10EC8, 0x10ECF}, + {0x10ED9, 0x10EF9}, + {0x10F28, 0x10F2F}, + {0x10F5A, 0x10F6F}, + {0x10F8A, 0x10FAF}, + {0x10FCC, 0x10FDF}, + {0x10FF7, 0x10FFF}, + {0x1104E, 0x11051}, + {0x11076, 0x1107E}, + {0x110C3, 0x110CC}, + {0x110CE, 0x110CF}, + {0x110E9, 0x110EF}, + {0x110FA, 0x110FF}, + {0x11135, 0x11135}, + {0x11148, 0x1114F}, + {0x11177, 0x1117F}, + {0x111E0, 0x111E0}, + {0x111F5, 0x111FF}, + {0x11212, 0x11212}, + {0x11242, 0x1127F}, + {0x11287, 0x11287}, + {0x11289, 0x11289}, + {0x1128E, 0x1128E}, + {0x1129E, 0x1129E}, + {0x112AA, 0x112AF}, + {0x112EB, 0x112EF}, + {0x112FA, 0x112FF}, + {0x11304, 0x11304}, + {0x1130D, 0x1130E}, + {0x11311, 0x11312}, + {0x11329, 0x11329}, + {0x11331, 0x11331}, + {0x11334, 0x11334}, + {0x1133A, 0x1133A}, + {0x11345, 0x11346}, + {0x11349, 0x1134A}, + {0x1134E, 0x1134F}, + {0x11351, 0x11356}, + {0x11358, 0x1135C}, + {0x11364, 0x11365}, + {0x1136D, 0x1136F}, + {0x11375, 0x1137F}, + {0x1138A, 0x1138A}, + {0x1138C, 0x1138D}, + {0x1138F, 0x1138F}, + {0x113B6, 0x113B6}, + {0x113C1, 0x113C1}, + {0x113C3, 0x113C4}, + {0x113C6, 0x113C6}, + {0x113CB, 0x113CB}, + {0x113D6, 0x113D6}, + {0x113D9, 0x113E0}, + {0x113E3, 0x113FF}, + {0x1145C, 0x1145C}, + {0x11462, 0x1147F}, + {0x114C8, 0x114CF}, + {0x114DA, 0x1157F}, + {0x115B6, 0x115B7}, + {0x115DE, 0x115FF}, + {0x11645, 0x1164F}, + {0x1165A, 0x1165F}, + {0x1166D, 0x1167F}, + {0x116BA, 0x116BF}, + {0x116CA, 0x116CF}, + {0x116E4, 0x116FF}, + {0x1171B, 0x1171C}, + {0x1172C, 0x1172F}, + {0x11747, 0x117FF}, + {0x1183C, 0x1189F}, + {0x118F3, 0x118FE}, + {0x11907, 0x11908}, + {0x1190A, 0x1190B}, + {0x11914, 0x11914}, + {0x11917, 0x11917}, + {0x11936, 0x11936}, + {0x11939, 0x1193A}, + {0x11947, 0x1194F}, + {0x1195A, 0x1199F}, + {0x119A8, 0x119A9}, + {0x119D8, 0x119D9}, + {0x119E5, 0x119FF}, + {0x11A48, 0x11A4F}, + {0x11AA3, 0x11AAF}, + {0x11AF9, 0x11AFF}, + {0x11B0A, 0x11B5F}, + {0x11B68, 0x11BBF}, + {0x11BE2, 0x11BEF}, + {0x11BFA, 0x11BFF}, + {0x11C09, 0x11C09}, + {0x11C37, 0x11C37}, + {0x11C46, 0x11C4F}, + {0x11C6D, 0x11C6F}, + {0x11C90, 0x11C91}, + {0x11CA8, 0x11CA8}, + {0x11CB7, 0x11CFF}, + {0x11D07, 0x11D07}, + {0x11D0A, 0x11D0A}, + {0x11D37, 0x11D39}, + {0x11D3B, 0x11D3B}, + {0x11D3E, 0x11D3E}, + {0x11D48, 0x11D4F}, + {0x11D5A, 0x11D5F}, + {0x11D66, 0x11D66}, + {0x11D69, 0x11D69}, + {0x11D8F, 0x11D8F}, + {0x11D92, 0x11D92}, + {0x11D99, 0x11D9F}, + {0x11DAA, 0x11DAF}, + {0x11DDC, 0x11DDF}, + {0x11DEA, 0x11EDF}, + {0x11EF9, 0x11EFF}, + {0x11F11, 0x11F11}, + {0x11F3B, 0x11F3D}, + {0x11F5B, 0x11FAF}, + {0x11FB1, 0x11FBF}, + {0x11FF2, 0x11FFE}, + {0x1239A, 0x123FF}, + {0x1246F, 0x1246F}, + {0x12475, 0x1247F}, + {0x12544, 0x12F8F}, + {0x12FF3, 0x12FFF}, + {0x13456, 0x1345F}, + {0x143FB, 0x143FF}, + {0x14647, 0x160FF}, + {0x1613A, 0x167FF}, + {0x16A39, 0x16A3F}, + {0x16A5F, 0x16A5F}, + {0x16A6A, 0x16A6D}, + {0x16ABF, 0x16ABF}, + {0x16ACA, 0x16ACF}, + {0x16AEE, 0x16AEF}, + {0x16AF6, 0x16AFF}, + {0x16B46, 0x16B4F}, + {0x16B5A, 0x16B5A}, + {0x16B62, 0x16B62}, + {0x16B78, 0x16B7C}, + {0x16B90, 0x16D3F}, + {0x16D7A, 0x16E3F}, + {0x16E9B, 0x16E9F}, + {0x16EB9, 0x16EBA}, + {0x16ED4, 0x16EFF}, + {0x16F4B, 0x16F4E}, + {0x16F88, 0x16F8E}, + {0x16FA0, 0x16FDF}, + {0x16FE5, 0x16FEF}, + {0x16FF7, 0x16FFF}, + {0x17001, 0x187FE}, + {0x18CD6, 0x18CFE}, + {0x18D01, 0x18D1D}, + {0x18D1F, 0x18D7F}, + {0x18DF3, 0x1AFEF}, + {0x1AFF4, 0x1AFF4}, + {0x1AFFC, 0x1AFFC}, + {0x1AFFF, 0x1AFFF}, + {0x1B123, 0x1B131}, + {0x1B133, 0x1B14F}, + {0x1B153, 0x1B154}, + {0x1B156, 0x1B163}, + {0x1B168, 0x1B16F}, + {0x1B2FC, 0x1BBFF}, + {0x1BC6B, 0x1BC6F}, + {0x1BC7D, 0x1BC7F}, + {0x1BC89, 0x1BC8F}, + {0x1BC9A, 0x1BC9B}, + {0x1BCA4, 0x1CBFF}, + {0x1CCFD, 0x1CCFF}, + {0x1CEB4, 0x1CEB9}, + {0x1CED1, 0x1CEDF}, + {0x1CEF1, 0x1CEFF}, + {0x1CF2E, 0x1CF2F}, + {0x1CF47, 0x1CF4F}, + {0x1CFC4, 0x1CFFF}, + {0x1D0F6, 0x1D0FF}, + {0x1D127, 0x1D128}, + {0x1D1EB, 0x1D1FF}, + {0x1D246, 0x1D2BF}, + {0x1D2D4, 0x1D2DF}, + {0x1D2F4, 0x1D2FF}, + {0x1D357, 0x1D35F}, + {0x1D379, 0x1D3FF}, + {0x1D455, 0x1D455}, + {0x1D49D, 0x1D49D}, + {0x1D4A0, 0x1D4A1}, + {0x1D4A3, 0x1D4A4}, + {0x1D4A7, 0x1D4A8}, + {0x1D4AD, 0x1D4AD}, + {0x1D4BA, 0x1D4BA}, + {0x1D4BC, 0x1D4BC}, + {0x1D4C4, 0x1D4C4}, + {0x1D506, 0x1D506}, + {0x1D50B, 0x1D50C}, + {0x1D515, 0x1D515}, + {0x1D51D, 0x1D51D}, + {0x1D53A, 0x1D53A}, + {0x1D53F, 0x1D53F}, + {0x1D545, 0x1D545}, + {0x1D547, 0x1D549}, + {0x1D551, 0x1D551}, + {0x1D6A6, 0x1D6A7}, + {0x1D7CC, 0x1D7CD}, + {0x1DA8C, 0x1DA9A}, + {0x1DAA0, 0x1DAA0}, + {0x1DAB0, 0x1DEFF}, + {0x1DF1F, 0x1DF24}, + {0x1DF2B, 0x1DFFF}, + {0x1E007, 0x1E007}, + {0x1E019, 0x1E01A}, + {0x1E022, 0x1E022}, + {0x1E025, 0x1E025}, + {0x1E02B, 0x1E02F}, + {0x1E06E, 0x1E08E}, + {0x1E090, 0x1E0FF}, + {0x1E12D, 0x1E12F}, + {0x1E13E, 0x1E13F}, + {0x1E14A, 0x1E14D}, + {0x1E150, 0x1E28F}, + {0x1E2AF, 0x1E2BF}, + {0x1E2FA, 0x1E2FE}, + {0x1E300, 0x1E4CF}, + {0x1E4FA, 0x1E5CF}, + {0x1E5FB, 0x1E5FE}, + {0x1E600, 0x1E6BF}, + {0x1E6DF, 0x1E6DF}, + {0x1E6F6, 0x1E6FD}, + {0x1E700, 0x1E7DF}, + {0x1E7E7, 0x1E7E7}, + {0x1E7EC, 0x1E7EC}, + {0x1E7EF, 0x1E7EF}, + {0x1E7FF, 0x1E7FF}, + {0x1E8C5, 0x1E8C6}, + {0x1E8D7, 0x1E8FF}, + {0x1E94C, 0x1E94F}, + {0x1E95A, 0x1E95D}, + {0x1E960, 0x1EC70}, + {0x1ECB5, 0x1ED00}, + {0x1ED3E, 0x1EDFF}, + {0x1EE04, 0x1EE04}, + {0x1EE20, 0x1EE20}, + {0x1EE23, 0x1EE23}, + {0x1EE25, 0x1EE26}, + {0x1EE28, 0x1EE28}, + {0x1EE33, 0x1EE33}, + {0x1EE38, 0x1EE38}, + {0x1EE3A, 0x1EE3A}, + {0x1EE3C, 0x1EE41}, + {0x1EE43, 0x1EE46}, + {0x1EE48, 0x1EE48}, + {0x1EE4A, 0x1EE4A}, + {0x1EE4C, 0x1EE4C}, + {0x1EE50, 0x1EE50}, + {0x1EE53, 0x1EE53}, + {0x1EE55, 0x1EE56}, + {0x1EE58, 0x1EE58}, + {0x1EE5A, 0x1EE5A}, + {0x1EE5C, 0x1EE5C}, + {0x1EE5E, 0x1EE5E}, + {0x1EE60, 0x1EE60}, + {0x1EE63, 0x1EE63}, + {0x1EE65, 0x1EE66}, + {0x1EE6B, 0x1EE6B}, + {0x1EE73, 0x1EE73}, + {0x1EE78, 0x1EE78}, + {0x1EE7D, 0x1EE7D}, + {0x1EE7F, 0x1EE7F}, + {0x1EE8A, 0x1EE8A}, + {0x1EE9C, 0x1EEA0}, + {0x1EEA4, 0x1EEA4}, + {0x1EEAA, 0x1EEAA}, + {0x1EEBC, 0x1EEEF}, + {0x1EEF2, 0x1EFFF}, + {0x1F02C, 0x1F02F}, + {0x1F094, 0x1F09F}, + {0x1F0AF, 0x1F0B0}, + {0x1F0C0, 0x1F0C0}, + {0x1F0D0, 0x1F0D0}, + {0x1F0F6, 0x1F0FF}, + {0x1F1AE, 0x1F1E5}, + {0x1F203, 0x1F20F}, + {0x1F23C, 0x1F23F}, + {0x1F249, 0x1F24F}, + {0x1F252, 0x1F25F}, + {0x1F266, 0x1F2FF}, + {0x1F6D9, 0x1F6DB}, + {0x1F6ED, 0x1F6EF}, + {0x1F6FD, 0x1F6FF}, + {0x1F7DA, 0x1F7DF}, + {0x1F7EC, 0x1F7EF}, + {0x1F7F1, 0x1F7FF}, + {0x1F80C, 0x1F80F}, + {0x1F848, 0x1F84F}, + {0x1F85A, 0x1F85F}, + {0x1F888, 0x1F88F}, + {0x1F8AE, 0x1F8AF}, + {0x1F8BC, 0x1F8BF}, + {0x1F8C2, 0x1F8CF}, + {0x1F8D9, 0x1F8FF}, + {0x1FA58, 0x1FA5F}, + {0x1FA6E, 0x1FA6F}, + {0x1FA7D, 0x1FA7F}, + {0x1FA8B, 0x1FA8D}, + {0x1FAC7, 0x1FAC7}, + {0x1FAC9, 0x1FACC}, + {0x1FADD, 0x1FADE}, + {0x1FAEB, 0x1FAEE}, + {0x1FAF9, 0x1FAFF}, + {0x1FB93, 0x1FB93}, + {0x1FBFB, 0x1FFFD}, + {0x20001, 0x2A6DE}, + {0x2A6E0, 0x2A6FF}, + {0x2A701, 0x2B73E}, + {0x2B741, 0x2B81C}, + {0x2B81E, 0x2B81F}, + {0x2B821, 0x2CEAC}, + {0x2CEAE, 0x2CEAF}, + {0x2CEB1, 0x2EBDF}, + {0x2EBE1, 0x2EBEF}, + {0x2EBF1, 0x2EE5C}, + {0x2EE5E, 0x2F7FF}, + {0x2FA1E, 0x2FFFD}, + {0x30001, 0x31349}, + {0x3134B, 0x3134F}, + {0x31351, 0x323AE}, + {0x323B1, 0x33478}, + {0x3347A, 0x3FFFD}, + {0x40000, 0x4FFFD}, + {0x50000, 0x5FFFD}, + {0x60000, 0x6FFFD}, + {0x70000, 0x7FFFD}, + {0x80000, 0x8FFFD}, + {0x90000, 0x9FFFD}, + {0xA0000, 0xAFFFD}, + {0xB0000, 0xBFFFD}, + {0xC0000, 0xCFFFD}, + {0xD0000, 0xDFFFD}, + {0xE0000, 0xE0000}, + {0xE0002, 0xE001F}, + {0xE0080, 0xE00FF}, + {0xE01F0, 0xEFFFD} +}; + +/* Non-characters. */ +static const struct widechar_range widechar_nonchar_table[] = { + {0x0FDD0, 0x0FDEF}, + {0x0FFFE, 0x0FFFF}, + {0x1FFFE, 0x1FFFF}, + {0x2FFFE, 0x2FFFF}, + {0x3FFFE, 0x3FFFF}, + {0x4FFFE, 0x4FFFF}, + {0x5FFFE, 0x5FFFF}, + {0x6FFFE, 0x6FFFF}, + {0x7FFFE, 0x7FFFF}, + {0x8FFFE, 0x8FFFF}, + {0x9FFFE, 0x9FFFF}, + {0xAFFFE, 0xAFFFF}, + {0xBFFFE, 0xBFFFF}, + {0xCFFFE, 0xCFFFF}, + {0xDFFFE, 0xDFFFF}, + {0xEFFFE, 0xEFFFF}, + {0xFFFFE, 0xFFFFF}, + {0x10FFFE, 0x10FFFF} +}; + +/* Characters that were widened from width 1 to 2 in Unicode 9. */ +static const struct widechar_range widechar_widened_table[] = { + {0x0231A, 0x0231B}, + {0x023E9, 0x023EC}, + {0x023F0, 0x023F0}, + {0x023F3, 0x023F3}, + {0x025FD, 0x025FE}, + {0x02614, 0x02615}, + {0x02648, 0x02653}, + {0x0267F, 0x0267F}, + {0x02693, 0x02693}, + {0x026A1, 0x026A1}, + {0x026AA, 0x026AB}, + {0x026BD, 0x026BE}, + {0x026C4, 0x026C5}, + {0x026CE, 0x026CE}, + {0x026D4, 0x026D4}, + {0x026EA, 0x026EA}, + {0x026F2, 0x026F3}, + {0x026F5, 0x026F5}, + {0x026FA, 0x026FA}, + {0x026FD, 0x026FD}, + {0x02705, 0x02705}, + {0x0270A, 0x0270B}, + {0x02728, 0x02728}, + {0x0274C, 0x0274C}, + {0x0274E, 0x0274E}, + {0x02753, 0x02755}, + {0x02757, 0x02757}, + {0x02795, 0x02797}, + {0x027B0, 0x027B0}, + {0x027BF, 0x027BF}, + {0x02B1B, 0x02B1C}, + {0x02B50, 0x02B50}, + {0x02B55, 0x02B55}, + {0x1F004, 0x1F004}, + {0x1F0CF, 0x1F0CF}, + {0x1F18E, 0x1F18E}, + {0x1F191, 0x1F19A}, + {0x1F201, 0x1F201}, + {0x1F21A, 0x1F21A}, + {0x1F22F, 0x1F22F}, + {0x1F232, 0x1F236}, + {0x1F238, 0x1F23A}, + {0x1F250, 0x1F251}, + {0x1F300, 0x1F320}, + {0x1F32D, 0x1F335}, + {0x1F337, 0x1F37C}, + {0x1F37E, 0x1F393}, + {0x1F3A0, 0x1F3CA}, + {0x1F3CF, 0x1F3D3}, + {0x1F3E0, 0x1F3F0}, + {0x1F3F4, 0x1F3F4}, + {0x1F3F8, 0x1F43E}, + {0x1F440, 0x1F440}, + {0x1F442, 0x1F4FC}, + {0x1F4FF, 0x1F53D}, + {0x1F54B, 0x1F54E}, + {0x1F550, 0x1F567}, + {0x1F595, 0x1F596}, + {0x1F5FB, 0x1F64F}, + {0x1F680, 0x1F6C5}, + {0x1F6CC, 0x1F6CC}, + {0x1F6D0, 0x1F6D0}, + {0x1F6EB, 0x1F6EC}, + {0x1F910, 0x1F918}, + {0x1F980, 0x1F984}, + {0x1F9C0, 0x1F9C0} +}; + +template +bool widechar_in_table(const Collection &arr, uint32_t c) { + auto where = std::lower_bound(std::begin(arr), std::end(arr), c, + [](widechar_range p, uint32_t c) { return p.hi < c; }); + return where != std::end(arr) && where->lo <= c; +} + +/* Return the width of character c, or a special negative value. */ +int widechar_wcwidth(uint32_t c) { + if (widechar_in_table(widechar_ascii_table, c)) + return 1; + if (widechar_in_table(widechar_private_table, c)) + return widechar_private_use; + if (widechar_in_table(widechar_nonprint_table, c)) + return widechar_nonprint; + if (widechar_in_table(widechar_nonchar_table, c)) + return widechar_non_character; + if (widechar_in_table(widechar_combining_table, c)) + return widechar_combining; + if (widechar_in_table(widechar_combiningletters_table, c)) + return widechar_combining; + if (widechar_in_table(widechar_doublewide_table, c)) + return 2; + if (widechar_in_table(widechar_ambiguous_table, c)) + return widechar_ambiguous; + if (widechar_in_table(widechar_unassigned_table, c)) + return widechar_unassigned; + if (widechar_in_table(widechar_widened_table, c)) + return widechar_widened_in_9; + return 1; +} + +} // namespace +#endif // WIDECHAR_WIDTH_H \ No newline at end of file diff --git a/vendor/btop/src/btop.cpp b/vendor/btop/src/btop.cpp new file mode 100644 index 000000000..01e20d991 --- /dev/null +++ b/vendor/btop/src/btop.cpp @@ -0,0 +1,1189 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include "btop.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef __FreeBSD__ + #include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __APPLE__ + #include + #include + #include +#endif + +#ifdef __NetBSD__ + #include + #include + #include +#endif + +#include +#include + +#include "btop_cli.hpp" +#include "btop_config.hpp" +#include "btop_draw.hpp" +#include "btop_input.hpp" +#include "btop_log.hpp" +#include "btop_menu.hpp" +#include "btop_shared.hpp" +#include "btop_theme.hpp" +#include "btop_tools.hpp" + +using std::atomic; +using std::cout; +using std::flush; +using std::min; +using std::string; +using std::string_view; +using std::to_string; +using std::vector; + +namespace fs = std::filesystem; + +using namespace Tools; +using namespace std::chrono_literals; +using namespace std::literals; + +namespace Global { + const vector> Banner_src = { + {"#E62525", "██████╗ ████████╗ ██████╗ ██████╗"}, + {"#CD2121", "██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗ ██╗ ██╗"}, + {"#B31D1D", "██████╔╝ ██║ ██║ ██║██████╔╝ ██████╗██████╗"}, + {"#9A1919", "██╔══██╗ ██║ ██║ ██║██╔═══╝ ╚═██╔═╝╚═██╔═╝"}, + {"#801414", "██████╔╝ ██║ ╚██████╔╝██║ ╚═╝ ╚═╝"}, + {"#000000", "╚═════╝ ╚═╝ ╚═════╝ ╚═╝"}, + }; + const string Version = "1.4.8"; + + int coreCount; + string overlay; + string clock; + + string fg_white = "\x1b[1;97m"; + string fg_green = "\x1b[1;92m"; + string fg_red = "\x1b[1;91m"; + + uid_t real_uid, set_uid; + + fs::path self_path; + + string exit_error_msg; + atomic thread_exception (false); + + bool debug{}; + + uint64_t start_time; + + atomic resized (false); + atomic quitting (false); + atomic should_quit (false); + atomic should_sleep (false); + atomic _runner_started (false); + atomic init_conf (false); + atomic reload_conf (false); +} + +namespace Runner { + static pthread_t runner_id; +} // namespace Runner + +//* Handler for SIGWINCH and general resizing events, does nothing if terminal hasn't been resized unless force=true +void term_resize(bool force) { + static atomic resizing (false); + if (Input::polling) { + Global::resized = true; + Input::interrupt(); + return; + } + atomic_lock lck(resizing, true); + if (auto refreshed = Term::refresh(true); refreshed or force) { + if (force and refreshed) force = false; + } + else return; +#ifdef GPU_SUPPORT + static const array all_boxes = {"gpu5", "cpu", "mem", "net", "proc", "gpu0", "gpu1", "gpu2", "gpu3", "gpu4"}; +#else + static const array all_boxes = {"", "cpu", "mem", "net", "proc"}; +#endif + Global::resized = true; + if (Runner::active) Runner::stop(); + Term::refresh(); + Config::unlock(); + + auto boxes = Config::getS("shown_boxes"); + auto min_size = Term::get_min_size(boxes); + auto minWidth = min_size.at(0), minHeight = min_size.at(1); + + while (not force or (Term::width < minWidth or Term::height < minHeight)) { + sleep_ms(100); + if (Term::width < minWidth or Term::height < minHeight) { + int width = Term::width, height = Term::height; + cout << fmt::format("{clear}{fg_white}" + "{mv1}Terminal size too small:" + "{mv2} Width = {fg_width}{width} {fg_white}Height = {fg_height}{height}" + "{mv3}{fg_white}Needed for current config:" + "{mv4}Width = {minWidth} Height = {minHeight}", + "clear"_a = Term::clear, "fg_white"_a = Global::fg_white, + "mv1"_a = Mv::to((height / 2) - 2, (width / 2) - 11), + "mv2"_a = Mv::to((height / 2) - 1, (width / 2) - 10), + "fg_width"_a = (width < minWidth ? Global::fg_red : Global::fg_green), + "width"_a = width, + "fg_height"_a = (height < minHeight ? Global::fg_red : Global::fg_green), + "height"_a = height, + "mv3"_a = Mv::to((height / 2) + 1, (width / 2) - 12), + "mv4"_a = Mv::to((height / 2) + 2, (width / 2) - 10), + "minWidth"_a = minWidth, + "minHeight"_a = minHeight + ) << std::flush; + + bool got_key = false; + for (; not Term::refresh() and not got_key; got_key = Input::poll(10)); + if (got_key) { + auto key = Input::get(); + if (key == "q") + clean_quit(0); + else if (key.size() == 1 and isint(key)) { + auto intKey = stoi(key); + #ifdef GPU_SUPPORT + if ((intKey == 0 and Gpu::count >= 5) or (intKey >= 5 and intKey - 4 <= Gpu::count)) { + #else + if (intKey > 0 and intKey < 5) { + #endif + const auto& box = all_boxes.at(intKey); + Config::current_preset.reset(); + Config::toggle_box(box); + boxes = Config::getS("shown_boxes"); + } + } + } + min_size = Term::get_min_size(boxes); + minWidth = min_size.at(0); + minHeight = min_size.at(1); + } + else if (not Term::refresh()) break; + } + + Input::interrupt(); +} + +//* Exit handler; stops threads, restores terminal and saves config changes +void clean_quit(int sig) { + if (Global::quitting) return; + Global::quitting = true; + Runner::stop(); + if (Global::_runner_started) { + #if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__ + if (pthread_join(Runner::runner_id, nullptr) != 0) { + Logger::warning("Failed to join _runner thread on exit!"); + } + #else + constexpr struct timespec ts { .tv_sec = 5, .tv_nsec = 0 }; + if (pthread_timedjoin_np(Runner::runner_id, nullptr, &ts) != 0) { + Logger::warning("Failed to join _runner thread on exit!"); + } + #endif + } + +#ifdef GPU_SUPPORT + Gpu::Nvml::shutdown(); + Gpu::Rsmi::shutdown(); + Gpu::Asysfs::shutdown(); + #ifdef __APPLE__ + Gpu::AppleSilicon::shutdown(); + #endif +#endif + + + if (Config::getB("save_config_on_exit")) { + Config::write(); + } + + if (Term::initialized) { + Input::clear(); + Term::restore(); + } + + if (not Global::exit_error_msg.empty()) { + sig = 1; + Logger::error("{}", Global::exit_error_msg); + fmt::println(std::cerr, "{}ERROR: {}{}{}", Global::fg_red, Global::fg_white, Global::exit_error_msg, Fx::reset); + } + Logger::info("Quitting! Runtime: {}", sec_to_dhms(time_s() - Global::start_time)); + + const auto excode = (sig != -1 ? sig : 0); + +#if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__ + _Exit(excode); +#else + quick_exit(excode); +#endif +} + +//* Handler for SIGTSTP; stops threads, restores terminal and sends SIGSTOP +static void _sleep() { + Runner::stop(); + Term::restore(); + std::raise(SIGSTOP); +} + +//* Handler for SIGCONT; re-initialize terminal and force a resize event +static void _resume() { + Term::init(); + term_resize(true); +} + +static void _exit_handler() { + clean_quit(-1); +} + +static void _crash_handler(const int sig) { + // Restore terminal before crashing + if (Term::initialized) { + Term::restore(); + } + // Re-raise the signal to get default behavior (core dump) + std::signal(sig, SIG_DFL); + std::raise(sig); +} + +static void _signal_handler(const int sig) { + switch (sig) { + case SIGINT: + Global::should_quit = true; + if (Runner::active) Runner::stopping = true; + Input::interrupt(); + break; + case SIGTSTP: + if (Runner::active) { + Global::should_sleep = true; + Runner::stopping = true; + Input::interrupt(); + } + else { + _sleep(); + } + break; + case SIGCONT: + _resume(); + break; + case SIGWINCH: + Global::resized = true; + Input::interrupt(); + break; + case SIGUSR1: + // Input::poll interrupt + break; + case SIGUSR2: + Global::reload_conf = true; + Input::interrupt(); + break; + } +} + +//* Config init +void init_config(bool low_color, std::optional& filter) { + atomic_lock lck(Global::init_conf); + vector load_warnings; + Config::load(Config::conf_file, load_warnings); + Config::set("lowcolor", (low_color ? true : not Config::getB("truecolor"))); + + static bool first_init = true; + + if (Global::debug and first_init) { + Logger::set_log_level(Logger::Level::DEBUG); + Logger::debug("Running in DEBUG mode!"); + } + else Logger::set_log_level(Config::getS("log_level")); + + if (filter.has_value()) { + Config::set("proc_filter", filter.value()); + } + + static string log_level; + if (const string current_level = Config::getS("log_level"); log_level != current_level) { + log_level = current_level; + Logger::info("Logger set to {}", (Global::debug ? "DEBUG" : log_level)); + } + + for (const auto& err_str : load_warnings) Logger::warning("{}", err_str); + first_init = false; +} + +//* Manages secondary thread for collection and drawing of boxes +namespace Runner { + atomic_waiting_lock active; + atomic stopping (false); + atomic waiting (false); + atomic redraw (false); + atomic coreNum_reset (false); + + static inline auto set_active(bool value) noexcept { + active.store(value); + } + + //* Setup semaphore for triggering thread to do work + // TODO: This can be made a local without too much effort. + std::binary_semaphore do_work { 0 }; + inline void thread_wait() { do_work.acquire(); } + inline void thread_trigger() { do_work.release(); } + + //* Wrapper for raising privileges when using SUID bit + class gain_priv { + int status = -1; + public: + gain_priv() { + if (Global::real_uid != Global::set_uid) + this->status = seteuid(Global::set_uid); + } + ~gain_priv() noexcept { + if (status == 0) + status = seteuid(Global::real_uid); + } + gain_priv(const gain_priv& other) = delete; + gain_priv& operator=(const gain_priv& other) = delete; + gain_priv(gain_priv&& other) = delete; + gain_priv& operator=(gain_priv&& other) = delete; + }; + + string output; + string empty_bg; + bool pause_output{}; + sigset_t mask; + std::mutex mtx; + + enum debug_actions { + collect_begin, + collect_done, + draw_begin, + draw_begin_only, + draw_done + }; + + enum debug_array { + collect, + draw + }; + + string debug_bg; + std::unordered_map> debug_times; + + class MyNumPunct : public std::numpunct + { + protected: + virtual char do_thousands_sep() const override { return '\''; } + virtual std::string do_grouping() const override { return "\03"; } + }; + + + struct runner_conf { + vector boxes; + bool no_update; + bool force_redraw; + bool background_update; + string overlay; + string clock; + }; + + struct runner_conf current_conf; + + static void debug_timer(const char* name, const int action) { + switch (action) { + case collect_begin: + debug_times[name].at(collect) = time_micros(); + return; + case collect_done: + debug_times[name].at(collect) = time_micros() - debug_times[name].at(collect); + debug_times["total"].at(collect) += debug_times[name].at(collect); + return; + case draw_begin_only: + debug_times[name].at(draw) = time_micros(); + return; + case draw_begin: + debug_times[name].at(draw) = time_micros(); + debug_times[name].at(collect) = debug_times[name].at(draw) - debug_times[name].at(collect); + debug_times["total"].at(collect) += debug_times[name].at(collect); + return; + case draw_done: + debug_times[name].at(draw) = time_micros() - debug_times[name].at(draw); + debug_times["total"].at(draw) += debug_times[name].at(draw); + return; + } + } + + //? ------------------------------- Secondary thread: async launcher and drawing ---------------------------------- + static void * _runner(void *) { + //? Block some signals in this thread to avoid deadlock from any signal handlers trying to stop this thread + sigemptyset(&mask); + // sigaddset(&mask, SIGINT); + // sigaddset(&mask, SIGTSTP); + sigaddset(&mask, SIGWINCH); + sigaddset(&mask, SIGTERM); + pthread_sigmask(SIG_BLOCK, &mask, nullptr); + + // TODO: On first glance it looks redudant with `Runner::active`. + std::lock_guard lock {mtx}; + + //* ----------------------------------------------- THREAD LOOP ----------------------------------------------- + while (not Global::quitting) { + thread_wait(); + atomic_wait_for(active, true, 30'000); + if (active) { + Global::exit_error_msg = "Runner thread failed to get active lock (30s)!"; + Global::thread_exception = true; + Input::interrupt(); + stopping = true; + } + if (stopping or Global::resized) { + sleep_ms(1); + continue; + } + + //? Atomic lock used for blocking non thread-safe actions in main thread + auto lck = active.lock(); + + //? Set effective user if SUID bit is set + gain_priv powers{}; + + auto& conf = current_conf; + + //! DEBUG stats + if (Global::debug) { + if (debug_bg.empty() or redraw) + Runner::debug_bg = Draw::createBox(2, 2, 33, + #ifdef GPU_SUPPORT + 9, + #else + 8, + #endif + "", true, "μs"); + + debug_times.clear(); + debug_times["total"] = {0, 0}; + } + + output.clear(); + + //* Run collection and draw functions for all boxes + try { +#if defined(GPU_SUPPORT) + //? GPU data collection + const bool gpu_in_cpu_panel = Gpu::gpu_names.size() > 0 and ( + Config::getS("cpu_graph_lower").starts_with("gpu-") + or (Config::getS("cpu_graph_lower") == "Auto") + or Config::getS("cpu_graph_upper").starts_with("gpu-") + or (Gpu::shown == 0 and Config::getS("show_gpu_info") != "Off") + ); + + vector gpu_panels = {}; + for (auto& box : conf.boxes) + if (box.starts_with("gpu")) + gpu_panels.push_back(box.back()-'0'); + + vector gpus; + if (gpu_in_cpu_panel or not gpu_panels.empty()) { + if (Global::debug) debug_timer("gpu", collect_begin); + gpus = Gpu::collect(conf.no_update); + if (Global::debug) debug_timer("gpu", collect_done); + } + auto& gpus_ref = gpus; +#endif // GPU_SUPPORT + + //? CPU + if (v_contains(conf.boxes, "cpu")) { + try { + if (Global::debug) debug_timer("cpu", collect_begin); + + //? Start collect + auto cpu = Cpu::collect(conf.no_update); + + if (coreNum_reset) { + coreNum_reset = false; + Cpu::core_mapping = Cpu::get_core_mapping(); + Global::resized = true; + Input::interrupt(); + continue; + } + + if (Global::debug) debug_timer("cpu", draw_begin); + + //? Draw box + if (not pause_output) { + output += Cpu::draw( + cpu, +#if defined(GPU_SUPPORT) + gpus_ref, +#endif // GPU_SUPPORT + conf.force_redraw, + conf.no_update + ); + } + + if (Global::debug) debug_timer("cpu", draw_done); + } + catch (const std::exception& e) { + throw std::runtime_error("Cpu:: -> " + string{e.what()}); + } + } + #ifdef GPU_SUPPORT + //? GPU + if (not gpu_panels.empty() and not gpus_ref.empty()) { + try { + if (Global::debug) debug_timer("gpu", draw_begin_only); + + //? Draw box + if (not pause_output) + for (unsigned long i = 0; i < gpu_panels.size(); ++i) + output += Gpu::draw(gpus_ref[gpu_panels[i]], i, conf.force_redraw, conf.no_update); + + if (Global::debug) debug_timer("gpu", draw_done); + } + catch (const std::exception& e) { + throw std::runtime_error("Gpu:: -> " + string{e.what()}); + } + } + #endif + //? MEM + if (v_contains(conf.boxes, "mem")) { + try { + if (Global::debug) debug_timer("mem", collect_begin); + + //? Start collect + auto mem = Mem::collect(conf.no_update); + + if (Global::debug) debug_timer("mem", draw_begin); + + //? Draw box + if (not pause_output) output += Mem::draw(mem, conf.force_redraw, conf.no_update); + + if (Global::debug) debug_timer("mem", draw_done); + } + catch (const std::exception& e) { + throw std::runtime_error("Mem:: -> " + string{e.what()}); + } + } + + //? NET + if (v_contains(conf.boxes, "net")) { + try { + if (Global::debug) debug_timer("net", collect_begin); + + //? Start collect + auto net = Net::collect(conf.no_update); + + if (Global::debug) debug_timer("net", draw_begin); + + //? Draw box + if (not pause_output) output += Net::draw(net, conf.force_redraw, conf.no_update); + + if (Global::debug) debug_timer("net", draw_done); + } + catch (const std::exception& e) { + throw std::runtime_error("Net:: -> " + string{e.what()}); + } + } + + //? PROC + if (v_contains(conf.boxes, "proc")) { + try { + if (Global::debug) debug_timer("proc", collect_begin); + + //? Start collect + auto proc = Proc::collect(conf.no_update); + + if (Global::debug) debug_timer("proc", draw_begin); + + //? Draw box + if (not pause_output) output += Proc::draw(proc, conf.force_redraw, conf.no_update); + + if (Global::debug) debug_timer("proc", draw_done); + } + catch (const std::exception& e) { + throw std::runtime_error("Proc:: -> " + string{e.what()}); + } + } + + } + catch (const std::exception& e) { + Global::exit_error_msg = fmt::format("Exception in runner thread -> {}", e.what()); + Global::thread_exception = true; + Input::interrupt(); + stopping = true; + } + + if (stopping) { + continue; + } + + if (redraw or conf.force_redraw) { + empty_bg.clear(); + redraw = false; + } + + if (not pause_output) output += conf.clock; + if (not conf.overlay.empty() and not conf.background_update) pause_output = true; + if (output.empty() and not pause_output) { + if (empty_bg.empty()) { + const int x = Term::width / 2 - 10, y = Term::height / 2 - 10; + output += Term::clear; + empty_bg = fmt::format( + "{banner}" + "{mv1}{titleFg}{b}No boxes shown!" + "{mv2}{hiFg}1 {mainFg}| Show CPU box" + "{mv3}{hiFg}2 {mainFg}| Show MEM box" + "{mv4}{hiFg}3 {mainFg}| Show NET box" + "{mv5}{hiFg}4 {mainFg}| Show PROC box" + "{mv6}{hiFg}5-0 {mainFg}| Show GPU boxes" + "{mv7}{hiFg}esc {mainFg}| Show menu" + "{mv8}{hiFg}q {mainFg}| Quit", + "banner"_a = Draw::banner_gen(y, 0, true), + "titleFg"_a = Theme::c("title"), "b"_a = Fx::b, "hiFg"_a = Theme::c("hi_fg"), "mainFg"_a = Theme::c("main_fg"), + "mv1"_a = Mv::to(y+6, x), + "mv2"_a = Mv::to(y+8, x), + "mv3"_a = Mv::to(y+9, x), + "mv4"_a = Mv::to(y+10, x), + "mv5"_a = Mv::to(y+11, x), + "mv6"_a = Mv::to(y+12, x-2), + "mv7"_a = Mv::to(y+13, x-2), + "mv8"_a = Mv::to(y+14, x) + ); + } + output += empty_bg; + } + + //! DEBUG stats --> + if (Global::debug and not Menu::active) { + output += fmt::format("{pre}{box:5.5} {collect:>12.12} {draw:>12.12}{post}", + "pre"_a = debug_bg + Theme::c("title") + Fx::b, + "box"_a = "box", "collect"_a = "collect", "draw"_a = "draw", + "post"_a = Theme::c("main_fg") + Fx::ub + ); + static auto loc = std::locale(std::locale::classic(), new MyNumPunct); + #ifdef GPU_SUPPORT + for (const string name : {"cpu", "mem", "net", "proc", "gpu", "total"}) { + #else + for (const string name : {"cpu", "mem", "net", "proc", "total"}) { + #endif + if (not debug_times.contains(name)) debug_times[name] = {0,0}; + const auto& [time_collect, time_draw] = debug_times.at(name); + if (name == "total") output += Fx::b; + output += fmt::format(loc, "{mvLD}{name:5.5} {collect:12L} {draw:12L}", + "mvLD"_a = Mv::l(31) + Mv::d(1), + "name"_a = name, + "collect"_a = time_collect, + "draw"_a = time_draw + ); + } + } + + //? If overlay isn't empty, print output without color and then print overlay on top + const bool term_sync = Config::getB("terminal_sync"); + cout << (term_sync ? Term::sync_start : "") << (conf.overlay.empty() + ? output + : (output.empty() ? "" : Fx::ub + Theme::c("inactive_fg") + Fx::uncolor(output)) + conf.overlay) + << (term_sync ? Term::sync_end : "") << flush; + } + //* ----------------------------------------------- THREAD LOOP ----------------------------------------------- + return {}; + } + //? ------------------------------------------ Secondary thread end ----------------------------------------------- + + //* Runs collect and draw in a secondary thread, unlocks and locks config to update cached values + void run(const string& box, bool no_update, bool force_redraw) { + atomic_wait_for(active, true, 10'000); + if (active) { + Logger::warning("Runner thread slow (>10s), waiting up to 30s..."); + atomic_wait_for(active, true, 20'000); + } + if (active) { + Global::exit_error_msg = "Runner thread stalled for 30s, exiting."; + clean_quit(1); + } + if (stopping or Global::resized) return; + + if (box == "overlay") { + const bool term_sync = Config::getB("terminal_sync"); + cout << (term_sync ? Term::sync_start : "") << Global::overlay << (term_sync ? Term::sync_end : "") << flush; + } + else if (box == "clock") { + const bool term_sync = Config::getB("terminal_sync"); + cout << (term_sync ? Term::sync_start : "") << Global::clock << (term_sync ? Term::sync_end : "") << flush; + } + else { + Config::unlock(); + Config::lock(); + + current_conf = { + (box == "all" ? Config::current_boxes : vector{box}), + no_update, force_redraw, + (not Config::getB("tty_mode") and Config::getB("background_update")), + Global::overlay, + Global::clock + }; + + if (Menu::active and not current_conf.background_update) Global::overlay.clear(); + + thread_trigger(); + atomic_wait_for(active, false, 10); + } + + + } + + //* Stops any work being done in runner thread and checks for thread errors + void stop() { + stopping = true; + auto lock = std::unique_lock {mtx, std::defer_lock}; + const auto is_runner_busy = !lock.try_lock(); + if (!is_runner_busy and not Global::quitting) { + if (active) { + set_active(false); + } + Global::exit_error_msg = "Runner thread died unexpectedly!"; + clean_quit(1); + } else if (is_runner_busy) { + atomic_wait_for(active, true, 30'000); + if (active) { + set_active(false); + if (Global::quitting) { + return; + } + else { + Global::exit_error_msg = "No response from Runner thread (30s), quitting!"; + clean_quit(1); + } + } + thread_trigger(); + atomic_wait_for(active, false, 100); + atomic_wait_for(active, true, 100); + } + stopping = false; + } + +} + +static auto configure_tty_mode(std::optional force_tty) { + if (force_tty.has_value()) { + Config::set("tty_mode", force_tty.value()); + Logger::debug("TTY mode set via command line"); + } + else if (Config::getB("force_tty")) { + Config::set("tty_mode", true); + Logger::debug("TTY mode set via config"); + } + +#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__NetBSD__) + else if (Term::current_tty.starts_with("/dev/tty")) { + Config::set("tty_mode", true); + Logger::debug("Auto detect real TTY"); + } +#endif + + Logger::debug("TTY mode enabled: {}", Config::getB("tty_mode")); +} + + +//* --------------------------------------------- Main starts here! --------------------------------------------------- +[[nodiscard]] auto btop_main(const std::span args) -> int { + + //? ------------------------------------------------ INIT --------------------------------------------------------- + + Global::start_time = time_s(); + + //? Save real and effective userid's and drop privileges until needed if running with SUID bit set + Global::real_uid = getuid(); + Global::set_uid = geteuid(); + if (Global::real_uid != Global::set_uid) { + if (seteuid(Global::real_uid) != 0) { + Global::real_uid = Global::set_uid; + Global::exit_error_msg = "Failed to change effective user ID. Unset btop SUID bit to ensure security on this system. Quitting!"; + clean_quit(1); + } + } + + Cli::Cli cli; + { + // Get the cli options or return with an exit code + auto result = Cli::parse(args); + if (result.has_value()) { + cli = result.value(); + } else { + auto error = result.error(); + if (error != 0) { + Cli::usage(); + Cli::help_hint(); + } + return error; + } + } + + Global::debug = cli.debug; + + { + const auto config_dir = Config::get_config_dir(); + + if (cli.config_file.has_value()) { + Config::conf_file = cli.config_file.value(); + } else if (config_dir.has_value()) { + Config::conf_dir = config_dir.value(); + Config::conf_file = Config::conf_dir / "btop.conf"; + + auto log_file = Config::get_log_file(); + if (log_file.has_value()) { + Logger::init(log_file.value()); + } + + Theme::user_theme_dir = Config::conf_dir / "themes"; + + // If necessary create the user theme directory + std::error_code error; + if (not fs::exists(Theme::user_theme_dir, error) and not fs::create_directories(Theme::user_theme_dir, error)) { + Theme::user_theme_dir.clear(); + Logger::warning("Failed to create user theme directory: {}", error.message()); + } + } + } + + //? Try to find global btop theme path relative to binary path +#ifdef __linux__ + { std::error_code ec; + Global::self_path = fs::read_symlink("/proc/self/exe", ec).remove_filename(); + } +#elif __APPLE__ + { + char buf [PATH_MAX]; + uint32_t bufsize = PATH_MAX; + if(!_NSGetExecutablePath(buf, &bufsize)) + Global::self_path = fs::path(buf).remove_filename(); + } +#elif __NetBSD__ + { + int mib[4]; + char buf[PATH_MAX]; + size_t bufsize = sizeof buf; + + mib[0] = CTL_KERN; + mib[1] = KERN_PROC_ARGS; + mib[2] = getpid(); + mib[3] = KERN_PROC_PATHNAME; + if (sysctl(mib, 4, buf, &bufsize, NULL, 0) == 0) + Global::self_path = fs::path(buf).remove_filename(); + } +#endif + if (std::error_code ec; not Global::self_path.empty()) { + Theme::theme_dir = fs::canonical(Global::self_path / "../share/btop/themes", ec); + if (ec or not fs::is_directory(Theme::theme_dir) or access(Theme::theme_dir.c_str(), R_OK) == -1) Theme::theme_dir.clear(); + } + //? If relative path failed, check two most common absolute paths + if (Theme::theme_dir.empty()) { + for (auto theme_path : {"/usr/local/share/btop/themes", "/usr/share/btop/themes"}) { + if (fs::is_directory(fs::path(theme_path)) and access(theme_path, R_OK) != -1) { + Theme::theme_dir = fs::path(theme_path); + break; + } + } + } + + //? Set custom themes directory from command line if provided + if (cli.themes_dir.has_value()) { + Theme::custom_theme_dir = cli.themes_dir.value(); + Logger::info("Using custom themes directory: {}", Theme::custom_theme_dir.string()); + } + + //? Config init + init_config(cli.low_color, cli.filter); + + //? Try to find and set a UTF-8 locale + if (std::setlocale(LC_ALL, "") != nullptr and not std::string_view { std::setlocale(LC_ALL, "") }.contains(";") + and str_to_upper(s_replace((string)std::setlocale(LC_ALL, ""), "-", "")).ends_with("UTF8")) { + Logger::debug("Using locale {}", std::locale().name()); + } + else { + string found; + bool set_failure{}; + for (const auto loc_env : array{"LANG", "LC_ALL", "LC_CTYPE"}) { + if (std::getenv(loc_env) != nullptr and str_to_upper(s_replace((string)std::getenv(loc_env), "-", "")).ends_with("UTF8")) { + found = std::getenv(loc_env); + if (std::setlocale(LC_ALL, found.c_str()) == nullptr) { + set_failure = true; + Logger::warning("Failed to set locale {} continuing anyway.", found); + } + } + } + if (found.empty()) { + if (setenv("LC_ALL", "", 1) == 0 and setenv("LANG", "", 1) == 0) { + try { + if (const auto loc = std::locale("").name(); not loc.empty() and loc != "*") { + for (auto& l : ssplit(loc, ';')) { + if (str_to_upper(s_replace(l, "-", "")).ends_with("UTF8")) { + found = l.substr(l.find('=') + 1); + if (std::setlocale(LC_ALL, found.c_str()) != nullptr) { + break; + } + } + } + } + } + catch (...) { found.clear(); } + } + } + // + #ifdef __APPLE__ + if (found.empty()) { + CFLocaleRef cflocale = CFLocaleCopyCurrent(); + CFStringRef id_value = (CFStringRef)CFLocaleGetValue(cflocale, kCFLocaleIdentifier); + auto loc_id = CFStringGetCStringPtr(id_value, kCFStringEncodingUTF8); + CFRelease(cflocale); + std::string cur_locale = (loc_id != nullptr ? loc_id : ""); + if (cur_locale.empty()) { + Logger::warning("No UTF-8 locale detected! Some symbols might not display correctly."); + } + else if (std::setlocale(LC_ALL, string(cur_locale + ".UTF-8").c_str()) != nullptr) { + Logger::debug("Setting LC_ALL={}.UTF-8", cur_locale); + } + else if(std::setlocale(LC_ALL, "en_US.UTF-8") != nullptr) { + Logger::debug("Setting LC_ALL=en_US.UTF-8"); + } + else { + Logger::warning("Failed to set macos locale, continuing anyway."); + } + } + #else + if (found.empty() and cli.force_utf) { + Logger::warning("No UTF-8 locale detected! Forcing start with --force-utf argument."); + } else if (found.empty()) { + Global::exit_error_msg = "No UTF-8 locale detected!\nUse --force-utf argument to force start if you're sure your terminal can handle it."; + clean_quit(1); + } + #endif + else if (not set_failure) { + Logger::debug("Setting LC_ALL={}", found); + } + } + + //? Initialize terminal and set options + if (not Term::init()) { + Global::exit_error_msg = "No tty detected!\nbtop++ needs an interactive shell to run."; + clean_quit(1); + } + + if (Term::current_tty != "unknown") { + Logger::info("Running on {}", Term::current_tty); + } + + configure_tty_mode(cli.force_tty); + + //? Check for valid terminal dimensions + { + int t_count = 0; + while (Term::width <= 0 or Term::width > 10000 or Term::height <= 0 or Term::height > 10000) { + sleep_ms(10); + Term::refresh(); + if (++t_count == 100) { + Global::exit_error_msg = "Failed to get size of terminal!"; + clean_quit(1); + } + } + } + + //? Platform dependent init and error check + try { + Shared::init(); + } + catch (const std::exception& e) { + Global::exit_error_msg = fmt::format("Exception in Shared::init() -> {}", e.what()); + clean_quit(1); + } + + if (not Config::set_boxes(Config::getS("shown_boxes"))) { + Config::set_boxes("cpu mem net proc"); + Config::set("shown_boxes", "cpu mem net proc"s); + } + + //? Update list of available themes and generate the selected theme + Theme::updateThemes(); + Theme::setTheme(); + + //? Setup signal handlers for CTRL-C, CTRL-Z, resume and terminal resize + std::atexit(_exit_handler); + std::signal(SIGINT, _signal_handler); + std::signal(SIGTSTP, _signal_handler); + std::signal(SIGCONT, _signal_handler); + std::signal(SIGWINCH, _signal_handler); + std::signal(SIGUSR1, _signal_handler); + std::signal(SIGUSR2, _signal_handler); + // Add crash handlers to restore terminal on crash + std::signal(SIGSEGV, _crash_handler); + std::signal(SIGABRT, _crash_handler); + std::signal(SIGTRAP, _crash_handler); + std::signal(SIGBUS, _crash_handler); + std::signal(SIGILL, _crash_handler); + + sigset_t mask; + sigemptyset(&mask); + sigaddset(&mask, SIGUSR1); + pthread_sigmask(SIG_BLOCK, &mask, &Input::signal_mask); + + if (pthread_create(&Runner::runner_id, nullptr, &Runner::_runner, nullptr) != 0) { + Global::exit_error_msg = "Failed to create _runner thread!"; + clean_quit(1); + } + else { + Global::_runner_started = true; + } + + //? Calculate sizes of all boxes + Config::presetsValid(Config::getS("presets")); + if (cli.preset.has_value()) { + Config::current_preset = min(static_cast(cli.preset.value()), static_cast(Config::preset_list.size() - 1)); + Config::apply_preset(Config::preset_list.at(Config::current_preset.value())); + } + + { + const auto [x, y] = Term::get_min_size(Config::getS("shown_boxes")); + if (Term::height < y or Term::width < x) { + pthread_sigmask(SIG_SETMASK, &Input::signal_mask, &mask); + term_resize(true); + pthread_sigmask(SIG_SETMASK, &mask, nullptr); + Global::resized = false; + } + + } + + Draw::calcSizes(); + + //? Print out box outlines + const bool term_sync = Config::getB("terminal_sync"); + cout << (term_sync ? Term::sync_start : "") << Cpu::box << Mem::box << Net::box << Proc::box << (term_sync ? Term::sync_end : "") << flush; + + + //? ------------------------------------------------ MAIN LOOP ---------------------------------------------------- + + if (cli.updates.has_value()) { + Config::set("update_ms", static_cast(cli.updates.value())); + } + uint64_t update_ms = Config::getI("update_ms"); + auto future_time = time_ms(); + + try { + while (not true not_eq not false) { + //? Check for exceptions in secondary thread and exit with fail signal if true + if (Global::thread_exception) { + clean_quit(1); + } + else if (Global::should_quit) { + clean_quit(0); + } + else if (Global::should_sleep) { + Global::should_sleep = false; + _sleep(); + } + //? Hot reload config from CTRL + R or SIGUSR2 + else if (Global::reload_conf) { + Global::reload_conf = false; + if (Runner::active) Runner::stop(); + Config::unlock(); + init_config(cli.low_color, cli.filter); + Theme::updateThemes(); + Theme::setTheme(); + Draw::banner_gen(0, 0, false, true); + Global::resized = true; + } + + //? Make sure terminal size hasn't changed (in case of SIGWINCH not working properly) + term_resize(Global::resized); + + //? Trigger secondary thread to redraw if terminal has been resized + if (Global::resized) { + Draw::calcSizes(); + Draw::update_clock(true); + Global::resized = false; + if (Menu::active) Menu::process(); + else Runner::run("all", true, true); + atomic_wait_for(Runner::active, true, 1000); + } + + //? Update clock if needed + if (Draw::update_clock() and not Menu::active) { + Runner::run("clock"); + } + + //? Start secondary collect & draw thread at the interval set by config value + if (time_ms() >= future_time and not Global::resized) { + Runner::run("all"); + update_ms = Config::getI("update_ms"); + future_time = time_ms() + update_ms; + } + + //? Loop over input polling and input action processing + for (auto current_time = time_ms(); current_time < future_time; current_time = time_ms()) { + + //? Check for external clock changes and for changes to the update timer + if (std::cmp_not_equal(update_ms, Config::getI("update_ms"))) { + update_ms = Config::getI("update_ms"); + future_time = time_ms() + update_ms; + } + else if (future_time - current_time > update_ms) { + future_time = current_time; + } + //? Poll for input and process any input detected + else if (Input::poll(min((uint64_t)1000, future_time - current_time))) { + if (not Runner::active) Config::unlock(); + + if (Menu::active) Menu::process(Input::get()); + else Input::process(Input::get()); + } + + //? Break the loop at 1000ms intervals or if input polling was interrupted + else break; + + } + + } + } + catch (const std::exception& e) { + Global::exit_error_msg = fmt::format("Exception in main loop -> {}", e.what()); + clean_quit(1); + } + return 0; +} diff --git a/vendor/btop/src/btop.hpp b/vendor/btop/src/btop.hpp new file mode 100644 index 000000000..5ecfd38d9 --- /dev/null +++ b/vendor/btop/src/btop.hpp @@ -0,0 +1,4 @@ +#include +#include + +[[nodiscard]] auto btop_main(std::span args) -> int; diff --git a/vendor/btop/src/btop_cli.cpp b/vendor/btop/src/btop_cli.cpp new file mode 100644 index 000000000..a5f7f7cb5 --- /dev/null +++ b/vendor/btop/src/btop_cli.cpp @@ -0,0 +1,272 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "btop_cli.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include "btop_config.hpp" +#include "btop_shared.hpp" +#include "config.h" + +using namespace std::string_view_literals; + +static constexpr auto BOLD = "\033[1m"sv; +static constexpr auto BOLD_UNDERLINE = "\033[1;4m"sv; +static constexpr auto BOLD_RED = "\033[1;31m"sv; +static constexpr auto BOLD_GREEN = "\033[1;32m"sv; +static constexpr auto BOLD_YELLOW = "\033[1;33m"sv; +static constexpr auto BOLD_BRIGHT_BLACK = "\033[1;90m"sv; +static constexpr auto YELLOW = "\033[33m"sv; +static constexpr auto RESET = "\033[0m"sv; + +static void version() noexcept { + if constexpr (GIT_COMMIT.empty()) { + fmt::println("btop version: {}{}{}", BOLD, Global::Version, RESET); + } else { + fmt::println("btop version: {}{}+{}{}", BOLD, Global::Version, GIT_COMMIT, RESET); + } +} + +static void build_info() noexcept { + fmt::println("Compiled with: {} ({})", COMPILER, COMPILER_VERSION); + fmt::println("Configured with: {}", CONFIGURE_COMMAND); +} + +static void error(std::string_view msg) noexcept { + fmt::println("{}error:{} {}\n", BOLD_RED, RESET, msg); +} + +namespace Cli { + [[nodiscard]] auto parse(const std::span args) noexcept -> Result { + Cli cli {}; + + for (auto it = args.begin(); it != args.end(); ++it) { + auto arg = *it; + + if (arg == "--default-config") { + return default_config(); + } + if (arg == "-h" || arg == "--help") { + usage(); + help(); + return std::unexpected { 0 }; + } + if (arg == "-v" || arg == "-V") { + version(); + return std::unexpected { 0 }; + } + if (arg == "--version") { + version(); + build_info(); + return std::unexpected { 0 }; + } + + if (arg == "-d" || arg == "--debug") { + cli.debug = true; + continue; + } + if (arg == "--force-utf") { + cli.force_utf = true; + continue; + } + if (arg == "-l" || arg == "--low-color") { + cli.low_color = true; + continue; + } + if (arg == "-t" || arg == "--tty") { + if (cli.force_tty.has_value()) { + error("tty mode can't be set twice"); + return std::unexpected { 1 }; + } + cli.force_tty = std::make_optional(true); + continue; + } + if (arg == "--no-tty") { + if (cli.force_tty.has_value()) { + error("tty mode can't be set twice"); + return std::unexpected { 1 }; + } + cli.force_tty = std::make_optional(false); + continue; + } + + if (arg == "-c" || arg == "--config") { + // This flag requires an argument. + if (++it == args.end()) { + error("Config requires an argument"); + return std::unexpected { 1 }; + } + + auto arg = *it; + auto config_file = stdfs::path { arg }; + + if (stdfs::is_directory(config_file)) { + error("Config file can't be a directory"); + return std::unexpected { 1 }; + } + + cli.config_file = std::make_optional(config_file); + continue; + } + if (arg == "-f" || arg == "--filter") { + // This flag requires an argument. + if (++it == args.end()) { + error("Filter requires an argument"); + return std::unexpected { 1 }; + } + + auto arg = *it; + cli.filter = std::make_optional(arg); + continue; + } + if (arg == "-p" || arg == "--preset") { + // This flag requires an argument. + if (++it == args.end()) { + error("Preset requires an argument"); + return std::unexpected { 1 }; + } + + auto arg = *it; + try { + auto preset_id = std::clamp(std::stoi(arg.data()), 0, 9); + cli.preset = std::make_optional(preset_id); + } catch (std::invalid_argument& e) { + error("Preset must be a positive number"); + return std::unexpected { 1 }; + } catch (std::out_of_range& e) { + error(fmt::format("Preset argument is out of range: {}", arg.data())); + return std::unexpected { 1 }; + } + continue; + } + if (arg == "--themes-dir") { + // This flag requires an argument. + if (++it == args.end()) { + error("Themes directory requires an argument"); + return std::unexpected { 1 }; + } + + auto arg = *it; + auto themes_dir = stdfs::path { arg }; + + if (not stdfs::is_directory(themes_dir)) { + error("Themes directory does not exist or is not a directory"); + return std::unexpected { 1 }; + } + + cli.themes_dir = std::make_optional(themes_dir); + continue; + } + if (arg == "-u" || arg == "--update") { + // This flag requires an argument. + if (++it == args.end()) { + error("Update requires an argument"); + return std::unexpected { 1 }; + } + + auto arg = *it; + try { + auto refresh_rate = std::max(std::stoi(arg.data()), 100); + cli.updates = refresh_rate; + } catch (std::invalid_argument& e) { + error("Update must be a positive number"); + return std::unexpected { 1 }; + } catch (std::out_of_range& e) { + error(fmt::format("Update argument is out of range: {}", arg.data())); + return std::unexpected { 1 }; + } + continue; + } + + error(fmt::format("Unknown argument '{}{}{}'", YELLOW, arg, RESET)); + return std::unexpected { 1 }; + } + return cli; + } + + auto default_config() noexcept -> Result { + // The idea of using `current_config` is that the CLI parser is run before loading the actual config and thus + // provides default values. + auto config = Config::current_config(); + + if (isatty(STDOUT_FILENO)) { + std::string buffer {}; + // The config buffer ends in `\n`. `std::views::split` will then create an empty element after the last + // newline, which we would write as an additional empty line at the very end. + auto trimmed_config = config.substr(0, config.length() - 1); + for (const auto line : std::views::split(trimmed_config, '\n')) { + auto line_view = std::string_view { line }; + if (line_view.starts_with("#")) { + fmt::format_to( + std::back_inserter(buffer), "{1}{0}{2}\n", line_view, BOLD_BRIGHT_BLACK, RESET + ); + } else if (!line_view.empty()) { + auto pos = line_view.find("="); + if (pos == line_view.npos) { + error("invalid default config: '=' not found"); + return std::unexpected { 1 }; + } + auto name = line_view.substr(0, pos); + auto value = line_view.substr(pos + 1); + fmt::format_to( + std::back_inserter(buffer), + "{2}{0}{4}={3}{1}{4}\n", + name, + value, + BOLD_YELLOW, + BOLD_GREEN, + RESET + ); + } else { + fmt::format_to(std::back_inserter(buffer), "\n"); + } + } + fmt::print("{}", buffer); + } else { + fmt::print("{}", config); + } + return std::unexpected { 0 }; + } + + void usage() noexcept { + fmt::println("{0}Usage:{1} {2}btop{1} [OPTIONS]\n", BOLD_UNDERLINE, RESET, BOLD); + } + + void help() noexcept { + fmt::print( + "{0}Options:{1}\n" + " {2}-c, --config{1} Path to a config file\n" + " {2}-d, --debug{1} Start in debug mode with additional logs and metrics\n" + " {2}-f, --filter{1} Set an initial process filter\n" + " {2} --force-utf{1} Override automatic UTF locale detection\n" + " {2}-l, --low-color{1} Disable true color, 256 colors only\n" + " {2}-p, --preset{1} Start with a preset (0-9)\n" + " {2}-t, --tty{1} Force tty mode with ANSI graph symbols and 16 colors only\n" + " {2} --themes-dir{1}

Path to a custom themes directory\n" + " {2} --no-tty{1} Force disable tty mode\n" + " {2}-u, --update{1} Set an initial update rate in milliseconds\n" + " {2} --default-config{1} Print default config to standard output\n" + " {2}-h, --help{1} Show this help message and exit\n" + " {2}-V, --version{1} Show a version message and exit (more with --version)\n", + BOLD_UNDERLINE, RESET, BOLD + ); + } + + void help_hint() noexcept { + fmt::println("For more information, try '{}--help{}'", BOLD, RESET); + } +} // namespace Cli diff --git a/vendor/btop/src/btop_cli.hpp b/vendor/btop/src/btop_cli.hpp new file mode 100644 index 000000000..69e1f9dbd --- /dev/null +++ b/vendor/btop/src/btop_cli.hpp @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Cli { + namespace stdfs = std::filesystem; + + // Configuration options set via the command line. + struct Cli { + // Alternate path to a configuration file + std::optional config_file; + // Enable debug mode with additional logs and metrics + bool debug {}; + // Set an initial process filter. + std::optional filter; + // Only use ANSI supported graph symbols and colors + std::optional force_tty; + // Use UTF-8 locale even if not detected + bool force_utf {}; + // Disable true color and only use 256 color mode + bool low_color {}; + // Start with one of the provided presets + std::optional preset; + // Path to a custom themes directory + std::optional themes_dir; + // The initial refresh rate + std::optional updates; + }; + + using Result = std::expected; + + // Parse the command line arguments + [[nodiscard]] auto parse(std::span args) noexcept -> Result; + + // Print default config to standard output + [[nodiscard]] auto default_config() noexcept -> Result; + + // Print a usage header + void usage() noexcept; + + // Print a help message + void help() noexcept; + + // Print a hint on how to show more help + void help_hint() noexcept; +} // namespace Cli diff --git a/vendor/btop/src/btop_config.cpp b/vendor/btop/src/btop_config.cpp new file mode 100644 index 000000000..3f0b0b00c --- /dev/null +++ b/vendor/btop/src/btop_config.cpp @@ -0,0 +1,901 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "btop_config.hpp" +#include "btop_log.hpp" +#include "btop_shared.hpp" +#include "btop_tools.hpp" + +using std::array; +using std::atomic; +using std::string_view; + +namespace fs = std::filesystem; +namespace rng = std::ranges; + +using namespace std::literals; +using namespace Tools; + +const vector Config::valid_graph_symbols = { "braille", "block", "tty" }; +const vector Config::valid_graph_symbols_def = { "default", "braille", "block", "tty" }; +const vector Config::valid_boxes = { + "cpu", "mem", "net", "proc" +#ifdef GPU_SUPPORT + ,"gpu0", "gpu1", "gpu2", "gpu3", "gpu4", "gpu5" +#endif +}; +const vector Config::temp_scales = { "celsius", "fahrenheit", "kelvin", "rankine" }; +#ifdef __linux__ +const vector Config::freq_modes = { "first", "range", "lowest", "highest", "average" }; +#endif +#ifdef GPU_SUPPORT +const vector Config::show_gpu_values = { "Auto", "On", "Off" }; +#endif +const vector Config::base_10_bitrate_values = { "Auto", "True", "False" }; +const vector Config::disable_preset_options = { "Off", "Default", "Custom", "All" }; + +//* Functions and variables for reading and writing the btop config file +namespace Config { + + atomic locked (false); + atomic writelock (false); + bool write_new; + + const vector> descriptions = { + {"color_theme", "#* Name of a btop++/bpytop/bashtop formatted \".theme\" file, \"Default\" and \"TTY\" for builtin themes.\n" + "#* Themes should be placed in \"../share/btop/themes\" relative to binary or \"$HOME/.config/btop/themes\""}, + + {"theme_background", "#* If the theme set background should be shown, set to False if you want terminal background transparency."}, + + {"truecolor", "#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false."}, + + {"force_tty", "#* Set to true to force tty mode regardless if a real tty has been detected or not.\n" + "#* Will force 16-color mode and TTY theme, set all graph symbols to \"tty\" and swap out other non tty friendly symbols."}, + + {"disable_presets", "#* Option to disable presets. Either the default preset, custom presets, or all presets.\n" + "#* \"Off\" All presets are enabled.\n" + "#* \"Default\" preset is disabled." + "#* \"Custom\" presets are disabled." + "#* \"All\" presets are disabled."}, + + {"presets", "#* Define presets for the layout of the boxes. Preset 0 is always all boxes shown with default settings. Max 9 presets.\n" + "#* Format: \"box_name:P:G,box_name:P:G\" P=(0 or 1) for alternate positions, G=graph symbol to use for box.\n" + "#* Use whitespace \" \" as separator between different presets.\n" + "#* Example: \"cpu:0:default,mem:0:tty,proc:1:default cpu:0:braille,proc:0:tty\""}, + + {"vim_keys", "#* Set to True to enable \"h,j,k,l,g,G\" keys for directional control in lists.\n" + "#* Conflicting keys for h:\"help\" and k:\"kill\" is accessible while holding shift."}, + + {"disable_mouse", "#* Disable all mouse events."}, + {"rounded_corners", "#* Rounded corners on boxes, is ignored if TTY mode is ON."}, + + {"terminal_sync", "#* Use terminal synchronized output sequences to reduce flickering on supported terminals."}, + + {"graph_symbol", "#* Default symbols to use for graph creation, \"braille\", \"block\" or \"tty\".\n" + "#* \"braille\" offers the highest resolution but might not be included in all fonts.\n" + "#* \"block\" has half the resolution of braille but uses more common characters.\n" + "#* \"tty\" uses only 3 different symbols but will work with most fonts and should work in a real TTY.\n" + "#* Note that \"tty\" only has half the horizontal resolution of the other two, so will show a shorter historical view."}, + + {"graph_symbol_cpu", "# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."}, +#ifdef GPU_SUPPORT + {"graph_symbol_gpu", "# Graph symbol to use for graphs in gpu box, \"default\", \"braille\", \"block\" or \"tty\"."}, +#endif + {"graph_symbol_mem", "# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."}, + + {"graph_symbol_net", "# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."}, + + {"graph_symbol_proc", "# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."}, + + {"shown_boxes", "#* Manually set which boxes to show. Available values are \"cpu mem net proc\" and \"gpu0\" through \"gpu5\", separate values with whitespace."}, + + {"update_ms", "#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs."}, + + {"proc_sorting", "#* Processes sorting, \"pid\" \"program\" \"arguments\" \"threads\" \"user\" \"memory\" \"cpu lazy\" \"cpu direct\",\n" + "#* \"cpu lazy\" sorts top process over time (easier to follow), \"cpu direct\" updates top process directly."}, + + {"proc_reversed", "#* Reverse sorting order, True or False."}, + + {"proc_tree", "#* Show processes as a tree."}, + + {"proc_colors", "#* Use the cpu graph colors in the process list."}, + + {"proc_gradient", "#* Use a darkening gradient in the process list."}, + + {"proc_per_core", "#* If process cpu usage should be of the core it's running on or usage of the total available cpu power."}, + + {"proc_mem_bytes", "#* Show process memory as bytes instead of percent."}, + + {"proc_cpu_graphs", "#* Show cpu graph for each process."}, + + {"proc_info_smaps", "#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate)"}, + + {"proc_left", "#* Show proc box on left side of screen instead of right."}, + + {"proc_filter_kernel", "#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop)."}, + + {"proc_follow_detailed", "#* Should the process list follow the selected process when detailed view is open."}, + + {"proc_aggregate", "#* In tree-view, always accumulate child process resources in the parent process."}, + + {"proc_tree_auto_collapse", "#* In tree-view, auto-collapse processes with this many or more direct children when\n" + "#* entering tree mode. 0 to disable. Useful for collapsing multi-process apps like browsers."}, + + {"keep_dead_proc_usage", "#* Should cpu and memory usage display be preserved for dead processes when paused."}, + + {"cpu_graph_upper", "#* Sets the CPU stat shown in upper half of the CPU graph, \"total\" is always available.\n" + "#* Select from a list of detected attributes from the options menu."}, + + {"cpu_graph_lower", "#* Sets the CPU stat shown in lower half of the CPU graph, \"total\" is always available.\n" + "#* Select from a list of detected attributes from the options menu."}, + #ifdef GPU_SUPPORT + {"show_gpu_info", "#* If gpu info should be shown in the cpu box. Available values = \"Auto\", \"On\" and \"Off\"."}, + #endif + {"cpu_invert_lower", "#* Toggles if the lower CPU graph should be inverted."}, + + {"cpu_single_graph", "#* Set to True to completely disable the lower CPU graph."}, + + {"cpu_bottom", "#* Show cpu box at bottom of screen instead of top."}, + + {"show_uptime", "#* Shows the system uptime in the CPU box."}, + + {"show_cpu_watts", "#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo."}, + + {"check_temp", "#* Show cpu temperature."}, + + {"cpu_sensor", "#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors."}, + + {"show_coretemp", "#* Show temperatures for cpu cores also if check_temp is True and sensors has been found."}, + + {"cpu_core_map", "#* Set a custom mapping between core and coretemp, can be needed on certain cpus to get correct temperature for correct core.\n" + "#* Use lm-sensors or similar to see which cores are reporting temperatures on your machine.\n" + "#* Format \"x:y\" x=core with wrong temp, y=core with correct temp, use space as separator between multiple entries.\n" + "#* Example: \"4:0 5:1 6:3\""}, + + {"temp_scale", "#* Which temperature scale to use, available values: \"celsius\", \"fahrenheit\", \"kelvin\" and \"rankine\"."}, + + {"base_10_sizes", "#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024."}, + + {"show_cpu_freq", "#* Show CPU frequency."}, + #ifdef __linux__ + {"freq_mode", "#* How to calculate CPU frequency, available values: \"first\", \"range\", \"lowest\", \"highest\" and \"average\"."}, + #endif + {"clock_format", "#* Draw a clock at top of screen, formatting according to strftime, empty string to disable.\n" + "#* Special formatting: /host = hostname | /user = username | /uptime = system uptime"}, + + {"background_update", "#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort."}, + + {"custom_cpu_name", "#* Custom cpu model name, empty string to disable."}, + + {"disks_filter", "#* Optional filter for shown disks, should be full path of a mountpoint, separate multiple values with whitespace \" \".\n" + "#* Only disks matching the filter will be shown. Prepend exclude= to only show disks not matching the filter. Examples: disks_filter=\"/boot /home/user\", disks_filter=\"exclude=/boot /home/user\""}, + + {"mem_graphs", "#* Show graphs instead of meters for memory values."}, + + {"mem_below_net", "#* Show mem box below net box instead of above."}, + + {"zfs_arc_cached", "#* Count ZFS ARC in cached and available memory."}, + + {"show_swap", "#* If swap memory should be shown in memory box."}, + + {"swap_disk", "#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk."}, + + {"show_disks", "#* If mem box should be split to also show disks info."}, + + {"only_physical", "#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar."}, + + {"use_fstab", "#* Read disks list from /etc/fstab. This also disables only_physical."}, + + {"zfs_hide_datasets", "#* Setting this to True will hide all datasets, and only show ZFS pools. (IO stats will be calculated per-pool)"}, + + {"disk_free_priv", "#* Set to true to show available disk space for privileged users."}, + + {"show_io_stat", "#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view."}, + + {"io_mode", "#* Toggles io mode for disks, showing big graphs for disk read/write speeds."}, + + {"io_graph_combined", "#* Set to True to show combined read/write io graphs in io mode."}, + + {"io_graph_speeds", "#* Set the top speed for the io graphs in MiB/s (100 by default), use format \"mountpoint:speed\" separate disks with whitespace \" \".\n" + "#* Example: \"/mnt/media:100 /:20 /boot:1\"."}, + + {"swap_upload_download", "#* Swap the positions of the upload and download speed graphs. When true, upload will be on top."}, + + {"net_download", "#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False."}, + + {"net_upload", ""}, + + {"net_auto", "#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest."}, + + {"net_sync", "#* Sync the auto scaling for download and upload to whichever currently has the highest scale."}, + + {"net_iface", "#* Starts with the Network Interface specified here."}, + + {"base_10_bitrate", "#* \"True\" shows bitrates in base 10 (Kbps, Mbps). \"False\" shows bitrates in binary sizes (Kibps, Mibps, etc.). \"Auto\" uses base_10_sizes."}, + + {"show_battery", "#* Show battery stats in top right if battery is present."}, + + {"selected_battery", "#* Which battery to use if multiple are present. \"Auto\" for auto detection."}, + + {"show_battery_watts", "#* Show power stats of battery next to charge indicator."}, + + {"log_level", "#* Set loglevel for \"~/.local/state/btop.log\" levels are: \"ERROR\" \"WARNING\" \"INFO\" \"DEBUG\".\n" + "#* The level set includes all lower levels, i.e. \"DEBUG\" will show all logging info."}, + {"save_config_on_exit", "#* Automatically save current settings to config file on exit."}, + #ifdef GPU_SUPPORT + + {"nvml_measure_pcie_speeds", + "#* Measure PCIe throughput on NVIDIA cards, may impact performance on certain cards."}, + {"rsmi_measure_pcie_speeds", + "#* Measure PCIe throughput on AMD cards, may impact performance on certain cards."}, + {"gpu_mirror_graph", "#* Horizontally mirror the GPU graph."}, + {"shown_gpus", "#* Set which GPU vendors to show. Available values are \"nvidia amd intel apple\""}, + {"custom_gpu_name0", "#* Custom gpu0 model name, empty string to disable."}, + {"custom_gpu_name1", "#* Custom gpu1 model name, empty string to disable."}, + {"custom_gpu_name2", "#* Custom gpu2 model name, empty string to disable."}, + {"custom_gpu_name3", "#* Custom gpu3 model name, empty string to disable."}, + {"custom_gpu_name4", "#* Custom gpu4 model name, empty string to disable."}, + {"custom_gpu_name5", "#* Custom gpu5 model name, empty string to disable."}, + #endif + }; + + std::unordered_map strings = { + {"color_theme", "Default"}, + {"shown_boxes", "cpu mem net proc"}, + {"graph_symbol", "braille"}, + {"disable_presets", "Off"}, + {"presets", "cpu:1:default,proc:0:default cpu:0:default,mem:0:default,net:0:default cpu:0:block,net:0:tty"}, + {"graph_symbol_cpu", "default"}, + {"graph_symbol_gpu", "default"}, + {"graph_symbol_mem", "default"}, + {"graph_symbol_net", "default"}, + {"graph_symbol_proc", "default"}, + {"proc_sorting", "cpu lazy"}, + {"cpu_graph_upper", "Auto"}, + {"cpu_graph_lower", "Auto"}, + {"cpu_sensor", "Auto"}, + {"selected_battery", "Auto"}, + {"cpu_core_map", ""}, + {"temp_scale", "celsius"}, + #ifdef __linux__ + {"freq_mode", "first"}, + #endif + {"clock_format", "%X"}, + {"custom_cpu_name", ""}, + {"disks_filter", ""}, + {"io_graph_speeds", ""}, + {"net_iface", ""}, + {"base_10_bitrate", "Auto"}, + {"log_level", "WARNING"}, + {"proc_filter", ""}, + {"proc_command", ""}, + {"selected_name", ""}, + #ifdef GPU_SUPPORT + {"custom_gpu_name0", ""}, + {"custom_gpu_name1", ""}, + {"custom_gpu_name2", ""}, + {"custom_gpu_name3", ""}, + {"custom_gpu_name4", ""}, + {"custom_gpu_name5", ""}, + {"show_gpu_info", "Auto"}, + {"shown_gpus", "nvidia amd intel apple"} + #endif + }; + std::unordered_map stringsTmp; + + std::unordered_map bools = { + {"theme_background", true}, + {"truecolor", true}, + {"rounded_corners", true}, + {"proc_reversed", false}, + {"proc_tree", false}, + {"proc_colors", true}, + {"proc_gradient", true}, + {"proc_per_core", false}, + {"proc_mem_bytes", true}, + {"proc_cpu_graphs", true}, + {"proc_info_smaps", false}, + {"proc_left", false}, + {"proc_filter_kernel", false}, + {"cpu_invert_lower", true}, + {"cpu_single_graph", false}, + {"cpu_bottom", false}, + {"show_uptime", true}, + {"show_cpu_watts", true}, + {"check_temp", true}, + {"show_coretemp", true}, + {"show_cpu_freq", true}, + {"background_update", true}, + {"mem_graphs", true}, + {"mem_below_net", false}, + {"zfs_arc_cached", true}, + {"show_swap", true}, + {"swap_disk", true}, + {"show_disks", true}, + {"only_physical", true}, + {"use_fstab", true}, + {"zfs_hide_datasets", false}, + {"show_io_stat", true}, + {"io_mode", false}, + {"swap_upload_download", false}, + {"base_10_sizes", false}, + {"io_graph_combined", false}, + {"net_auto", true}, + {"net_sync", true}, + {"show_battery", true}, + {"show_battery_watts", true}, + {"vim_keys", false}, + {"tty_mode", false}, + {"disk_free_priv", false}, + {"force_tty", false}, + {"lowcolor", false}, + {"show_detailed", false}, + {"proc_filtering", false}, + {"proc_aggregate", false}, + {"pause_proc_list", false}, + {"keep_dead_proc_usage", false}, + {"proc_banner_shown", false}, + {"proc_follow_detailed", true}, + {"follow_process", false}, + {"update_following", false}, + {"should_selection_return_to_followed", false}, + #ifdef GPU_SUPPORT + {"nvml_measure_pcie_speeds", true}, + {"rsmi_measure_pcie_speeds", true}, + {"gpu_mirror_graph", true}, + #endif + {"terminal_sync", true}, + {"save_config_on_exit", true}, + {"disable_mouse", false}, + }; + std::unordered_map boolsTmp; + + std::unordered_map ints = { + {"update_ms", 2000}, + {"net_download", 100}, + {"net_upload", 100}, + {"proc_tree_auto_collapse", 0}, + {"detailed_pid", 0}, + {"restore_detailed_pid", 0}, + {"selected_pid", 0}, + {"followed_pid", 0}, + {"selected_depth", 0}, + {"proc_start", 0}, + {"proc_selected", 0}, + {"proc_last_selected", 0}, + {"proc_followed", 0}, + }; + std::unordered_map intsTmp; + + // Returns a valid config dir or an empty optional + // The config dir might be read only, a warning is printed, but a path is returned anyway + [[nodiscard]] std::optional get_config_dir() noexcept { + fs::path config_dir; + { + std::error_code error; + if (const auto xdg_config_home = std::getenv("XDG_CONFIG_HOME"); xdg_config_home != nullptr) { + if (fs::exists(xdg_config_home, error)) { + config_dir = fs::path(xdg_config_home) / "btop"; + } + } else if (const auto home = std::getenv("HOME"); home != nullptr) { + error.clear(); + if (fs::exists(home, error)) { + config_dir = fs::path(home) / ".config" / "btop"; + } + if (error) { + fmt::print(stderr, "\033[0;31mWarning: \033[0m{} could not be accessed: {}\n", config_dir.string(), error.message()); + config_dir = ""; + } + } + } + + // FIXME: This warnings can be noisy if the user deliberately has a non-writable config dir + // offer an alternative | disable messages by default | disable messages if config dir is not writable | disable messages with a flag + // FIXME: Make happy path not branch + if (not config_dir.empty()) { + std::error_code error; + if (fs::exists(config_dir, error)) { + if (fs::is_directory(config_dir, error)) { + struct statvfs stats {}; + if ((fs::status(config_dir, error).permissions() & fs::perms::owner_write) == fs::perms::owner_write and + statvfs(config_dir.c_str(), &stats) == 0 and (stats.f_flag & ST_RDONLY) == 0) { + return config_dir; + } else { + fmt::print(stderr, "\033[0;31mWarning: \033[0m`{}` is not writable\n", fs::absolute(config_dir).string()); + // If the config is readable we can still use the provided config, but changes will not be persistent + if ((fs::status(config_dir, error).permissions() & fs::perms::owner_read) == fs::perms::owner_read) { + fmt::print(stderr, "\033[0;31mWarning: \033[0mLogging is disabled, config changes are not persistent\n"); + return config_dir; + } + } + } else { + fmt::print(stderr, "\033[0;31mWarning: \033[0m`{}` is not a directory\n", fs::absolute(config_dir).string()); + } + } else { + // Doesn't exist + if (fs::create_directories(config_dir, error)) { + return config_dir; + } else { + fmt::print(stderr, "\033[0;31mWarning: \033[0m`{}` could not be created: {}\n", fs::absolute(config_dir).string(), error.message()); + } + } + } else { + fmt::print(stderr, "\033[0;31mWarning: \033[0mCould not determine config path: Make sure `$XDG_CONFIG_HOME` or `$HOME` is set\n"); + } + fmt::print(stderr, "\033[0;31mWarning: \033[0mLogging is disabled, config changes are not persistent\n"); + return {}; + } + + bool _locked(const std::string_view name) { + atomic_wait(writelock, true); + if (not write_new and rng::find_if(descriptions, [&name](const auto& a) { return a.at(0) == name; }) != descriptions.end()) + write_new = true; + return locked.load(); + } + + fs::path conf_dir; + fs::path conf_file; + + vector available_batteries = {"Auto"}; + + vector current_boxes; + vector preset_list = {"cpu:0:default,mem:0:default,net:0:default,proc:0:default"}; + std::optional current_preset; + + bool presetsValid(const string& presets) { + vector new_presets = {preset_list.at(0)}; + + for (int x = 0; const auto& preset : ssplit(presets)) { + if (++x > 9) { + validError = "Too many presets entered!"; + return false; + } + for (int y = 0; const auto& box : ssplit(preset, ',')) { + if (++y > 4) { + validError = "Too many boxes entered for preset!"; + return false; + } + const auto& vals = ssplit(box, ':'); + if (vals.size() != 3) { + validError = "Malformatted preset in config value presets!"; + return false; + } + if (not is_in(vals.at(0), "cpu", "mem", "net", "proc", "gpu0", "gpu1", "gpu2", "gpu3", "gpu4", "gpu5")) { + validError = "Invalid box name in config value presets!"; + return false; + } + if (not is_in(vals.at(1), "0", "1")) { + validError = "Invalid position value in config value presets!"; + return false; + } + if (not v_contains(valid_graph_symbols_def, vals.at(2))) { + validError = "Invalid graph name in config value presets!"; + return false; + } + } + new_presets.push_back(preset); + } + + preset_list = std::move(new_presets); + return true; + } + + //* Apply selected preset + bool apply_preset(const string& preset) { + string boxes; + + for (const auto& box : ssplit(preset, ',')) { + const auto& vals = ssplit(box, ':'); + boxes += vals.at(0) + ' '; + } + if (not boxes.empty()) boxes.pop_back(); + + auto min_size = Term::get_min_size(boxes); + if (Term::width < min_size.at(0) or Term::height < min_size.at(1)) { + return false; + } + + for (const auto& box : ssplit(preset, ',')) { + const auto& vals = ssplit(box, ':'); + if (vals.at(0) == "cpu") { + set("cpu_bottom", (vals.at(1) != "0")); + } else if (vals.at(0) == "mem") { + set("mem_below_net", (vals.at(1) != "0")); + } else if (vals.at(0) == "proc") { + set("proc_left", (vals.at(1) != "0")); + } + if (vals.at(0).starts_with("gpu")) { + set("graph_symbol_gpu", vals.at(2)); + } else { + set(strings.find("graph_symbol_" + vals.at(0))->first, vals.at(2)); + } + } + + if (set_boxes(boxes)) { + set("shown_boxes", boxes); + return true; + } + return false; + } + + void lock() { + atomic_wait(writelock); + locked = true; + } + + string validError; + + bool intValid(const std::string_view name, const string& value) { + int i_value; + try { + i_value = stoi(value); + } + catch (const std::invalid_argument&) { + validError = "Invalid numerical value!"; + return false; + } + catch (const std::out_of_range&) { + validError = "Value out of range!"; + return false; + } + catch (const std::exception& e) { + validError = string{e.what()}; + return false; + } + + if (name == "update_ms" and i_value < 100) + validError = "Config value update_ms set too low (<100)."; + + else if (name == "update_ms" and i_value > ONE_DAY_MILLIS) + validError = fmt::format("Config value update_ms set too high (>{}).", ONE_DAY_MILLIS); + + else if (name == "proc_tree_auto_collapse" and i_value < 0) + validError = "Config value proc_tree_auto_collapse must be >= 0."; + + else if (name == "proc_tree_auto_collapse" and i_value > 10000) + validError = "Config value proc_tree_auto_collapse set too high (>10000)."; + + else + return true; + + return false; + } + + bool validBoxSizes(const string& boxes) { + auto min_size = Term::get_min_size(boxes); + return (Term::width >= min_size.at(0) and Term::height >= min_size.at(1)); + } + + bool stringValid(const std::string_view name, const string& value) { + if (name == "log_level" and not v_contains(Logger::log_levels, value)) + validError = "Invalid log_level: " + value; + + else if (name == "graph_symbol" and not v_contains(valid_graph_symbols, value)) + validError = "Invalid graph symbol identifier: " + value; + + else if (name.starts_with("graph_symbol_") and (value != "default" and not v_contains(valid_graph_symbols, value))) + validError = fmt::format("Invalid graph symbol identifier for {}: {}", name, value); + + else if (name == "shown_boxes" and not Global::init_conf) { + if (value.empty()) + validError = "No boxes selected!"; + else if (not validBoxSizes(value)) + validError = "Terminal too small to display entered boxes!"; + else if (not set_boxes(value)) + validError = "Invalid box name(s) in shown_boxes!"; + else + return true; + } + + #ifdef GPU_SUPPORT + else if (name == "show_gpu_info" and not v_contains(show_gpu_values, value)) + validError = "Invalid value for show_gpu_info: " + value; + #endif + + else if (name == "presets" and not presetsValid(value)) + return false; + + else if (name == "cpu_core_map") { + const auto maps = ssplit(value); + bool all_good = true; + for (const auto& map : maps) { + const auto map_split = ssplit(map, ':'); + if (map_split.size() != 2) + all_good = false; + else if (not isint(map_split.at(0)) or not isint(map_split.at(1))) + all_good = false; + + if (not all_good) { + validError = "Invalid formatting of cpu_core_map!"; + return false; + } + } + return true; + } + else if (name == "io_graph_speeds") { + const auto maps = ssplit(value); + bool all_good = true; + for (const auto& map : maps) { + const auto map_split = ssplit(map, ':'); + if (map_split.size() != 2) + all_good = false; + else if (map_split.at(0).empty() or not isint(map_split.at(1))) + all_good = false; + + if (not all_good) { + validError = "Invalid formatting of io_graph_speeds!"; + return false; + } + } + return true; + } + + else + return true; + + return false; + } + + string getAsString(const std::string_view name) { + if (auto it = bools.find(name); it != bools.end()) + return it->second ? "True" : "False"; + if (auto it = ints.find(name); it != ints.end()) + return to_string(it->second); + if (auto it = strings.find(name); it != strings.end()) + return it->second; + return ""; + } + + void flip(const std::string_view name) { + if (_locked(name)) { + if (boolsTmp.contains(name)) boolsTmp.at(name) = not boolsTmp.at(name); + else boolsTmp.insert_or_assign(name, (not bools.at(name))); + } + else bools.at(name) = not bools.at(name); + } + + void unlock() { + if (not locked) return; + atomic_wait(Runner::active); + atomic_lock lck(writelock, true); + try { + if (Proc::shown) { + ints.at("selected_pid") = Proc::selected_pid; + strings.at("selected_name") = Proc::selected_name; + ints.at("proc_start") = Proc::start; + ints.at("proc_selected") = Proc::selected; + ints.at("selected_depth") = Proc::selected_depth; + } + + for (auto& item : stringsTmp) { + strings.at(item.first) = item.second; + } + stringsTmp.clear(); + + for (auto& item : intsTmp) { + ints.at(item.first) = item.second; + } + intsTmp.clear(); + + for (auto& item : boolsTmp) { + bools.at(item.first) = item.second; + } + boolsTmp.clear(); + } + catch (const std::exception& e) { + Global::exit_error_msg = fmt::format("Exception during Config::unlock() : {}", e.what()); + clean_quit(1); + } + + locked = false; + } + + bool set_boxes(const string& boxes) { + auto new_boxes = ssplit(boxes); + for (auto& box : new_boxes) { + if (not v_contains(valid_boxes, box)) return false; + #ifdef GPU_SUPPORT + if (box.starts_with("gpu")) { + int gpu_num = stoi(box.substr(3)) + 1; + if (gpu_num > Gpu::count) return false; + } + #endif + } + current_boxes = std::move(new_boxes); + return true; + } + + bool toggle_box(const string& box) { + auto old_boxes = current_boxes; + auto box_pos = rng::find(current_boxes, box); + if (box_pos == current_boxes.end()) + current_boxes.push_back(box); + else + current_boxes.erase(box_pos); + + string new_boxes; + if (not current_boxes.empty()) { + for (const auto& b : current_boxes) new_boxes += b + ' '; + new_boxes.pop_back(); + } + + auto min_size = Term::get_min_size(new_boxes); + + if (Term::width < min_size.at(0) or Term::height < min_size.at(1)) { + current_boxes = old_boxes; + return false; + } + + Config::set("shown_boxes", new_boxes); + return true; + } + + void load(const fs::path& conf_file, vector& load_warnings) { + std::error_code error; + if (conf_file.empty()) + return; + else if (not fs::exists(conf_file, error)) { + write_new = true; + return; + } + if (error) { + return; + } + + std::ifstream cread(conf_file); + if (cread.good()) { + vector valid_names; + valid_names.reserve(descriptions.size()); + for (const auto &n : descriptions) + valid_names.push_back(n[0]); + if (string v_string; cread.peek() != '#' or (getline(cread, v_string, '\n') and not v_string.contains(Global::Version))) + write_new = true; + while (not cread.eof()) { + cread >> std::ws; + if (cread.peek() == '#') { + cread.ignore(SSmax, '\n'); + continue; + } + string name, value; + getline(cread, name, '='); + if (name.ends_with(' ')) name = trim(name); + if (not v_contains(valid_names, name)) { + cread.ignore(SSmax, '\n'); + continue; + } + cread >> std::ws; + + if (bools.contains(name)) { + cread >> value; + if (not isbool(value)) + load_warnings.push_back("Got an invalid bool value for config name: " + name); + else + bools.at(name) = stobool(value); + } + else if (ints.contains(name)) { + cread >> value; + if (not isint(value)) + load_warnings.push_back("Got an invalid integer value for config name: " + name); + else if (not intValid(name, value)) { + load_warnings.push_back(validError); + } + else + ints.at(name) = stoi(value); + } + else if (strings.contains(name)) { + if (cread.peek() == '"') { + cread.ignore(1); + getline(cread, value, '"'); + } + else cread >> value; + + if (not stringValid(name, value)) + load_warnings.push_back(validError); + else + strings.at(name) = value; + } + + cread.ignore(SSmax, '\n'); + } + + if (not load_warnings.empty()) write_new = true; + } + } + + void write() { + if (conf_file.empty() or not write_new) return; + Logger::debug("Writing new config file"); + if (geteuid() != Global::real_uid and seteuid(Global::real_uid) != 0) return; + std::ofstream cwrite(conf_file, std::ios::trunc); + // TODO: Report error when stream is in a bad state. + if (cwrite.good()) { + cwrite << current_config(); + } + } + + static constexpr auto get_xdg_state_dir() -> std::optional { + std::optional xdg_state_home; + + { + const auto* xdg_state_home_ptr = std::getenv("XDG_STATE_HOME"); + if (xdg_state_home_ptr != nullptr) { + xdg_state_home = std::make_optional(fs::path(xdg_state_home_ptr)); + } else { + const auto* home_ptr = std::getenv("HOME"); + if (home_ptr != nullptr) { + xdg_state_home = std::make_optional(fs::path(home_ptr) / ".local" / "state"); + } + } + } + + if (xdg_state_home.has_value()) { + std::error_code err; + fs::create_directories(xdg_state_home.value(), err); + if (err) { + return std::nullopt; + } + return xdg_state_home; + } + return std::nullopt; + } + + auto get_log_file() -> std::optional { + return get_xdg_state_dir().transform([](auto&& state_home) -> auto { return state_home / "btop.log"; }); + } + + auto current_config() -> std::string { + auto buffer = std::string {}; + fmt::format_to(std::back_inserter(buffer), "#? Config file for btop v.{}\n", Global::Version); + + for (const auto& [name, description] : descriptions) { + // Write a description comment if available. + fmt::format_to(std::back_inserter(buffer), "\n"); + if (!description.empty()) { + fmt::format_to(std::back_inserter(buffer), "{}\n", description); + } + + fmt::format_to(std::back_inserter(buffer), "{} = ", name); + // Lookup default value by name and write it out. + if (strings.contains(name)) { + fmt::format_to(std::back_inserter(buffer), R"("{}")", strings[name]); + } else if (ints.contains(name)) { + fmt::format_to(std::back_inserter(buffer), std::locale::classic(), "{:L}", ints[name]); + } else if (bools.contains(name)) { + fmt::format_to(std::back_inserter(buffer), "{}", bools[name] ? "true" : "false"); + } + fmt::format_to(std::back_inserter(buffer), "\n"); + } + return buffer; + } +} diff --git a/vendor/btop/src/btop_config.hpp b/vendor/btop/src/btop_config.hpp new file mode 100644 index 000000000..24e9ff28e --- /dev/null +++ b/vendor/btop/src/btop_config.hpp @@ -0,0 +1,137 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#include +#include +#include +#include + +#include + +using std::string; +using std::vector; + +//* Functions and variables for reading and writing the btop config file +namespace Config { + + extern std::filesystem::path conf_dir; + extern std::filesystem::path conf_file; + + extern std::unordered_map strings; + extern std::unordered_map stringsTmp; + extern std::unordered_map bools; + extern std::unordered_map boolsTmp; + extern std::unordered_map ints; + extern std::unordered_map intsTmp; + + extern const vector valid_graph_symbols; + extern const vector valid_graph_symbols_def; + extern const vector valid_boxes; + + extern const vector temp_scales; +#ifdef __linux__ + extern const vector freq_modes; +#endif +#ifdef GPU_SUPPORT + extern const vector show_gpu_values; +#endif + extern const vector base_10_bitrate_values; + extern vector current_boxes; + extern vector preset_list; + extern const vector disable_preset_options; + extern vector available_batteries; + extern std::optional current_preset; + + extern bool write_new; + + constexpr int ONE_DAY_MILLIS = 1000 * 60 * 60 * 24; + + [[nodiscard]] std::optional get_config_dir() noexcept; + + //* Check if string only contains space separated valid names for boxes and set current_boxes + bool set_boxes(const string& boxes); + + bool validBoxSizes(const string& boxes); + + //* Toggle box and update config string shown_boxes + bool toggle_box(const string& box); + + //* Parse and setup config value presets + bool presetsValid(const string& presets); + + //* Apply selected preset + bool apply_preset(const string& preset); + + bool _locked(const std::string_view name); + + //* Return bool for config key + inline bool getB(const std::string_view name) { return bools.at(name); } + + //* Return integer for config key + inline const int& getI(const std::string_view name) { return ints.at(name); } + + //* Return string for config key + inline const string& getS(const std::string_view name) { return strings.at(name); } + + string getAsString(const std::string_view name); + + extern string validError; + + bool intValid(const std::string_view name, const string& value); + bool stringValid(const std::string_view name, const string& value); + + //* Set config key to bool + inline void set(const std::string_view name, bool value) { + if (_locked(name)) boolsTmp.insert_or_assign(name, value); + else bools.at(name) = value; + } + + //* Set config key to int + inline void set(const std::string_view name, const int value) { + if (_locked(name)) intsTmp.insert_or_assign(name, value); + else ints.at(name) = value; + } + + //* Set config key to string + inline void set(const std::string_view name, const string& value) { + if (_locked(name)) stringsTmp.insert_or_assign(name, value); + else strings.at(name) = value; + } + + //* Flip config key bool + void flip(const std::string_view name); + + //* Lock config and cache changes until unlocked + void lock(); + + //* Unlock config and write any cached values to config + void unlock(); + + //* Load the config file from disk + void load(const std::filesystem::path& conf_file, vector& load_warnings); + + //* Write the config file to disk + void write(); + + auto get_log_file() -> std::optional; + + // Write default config to an in-memory buffer + [[nodiscard]] auto current_config() -> std::string; +} diff --git a/vendor/btop/src/btop_draw.cpp b/vendor/btop/src/btop_draw.cpp new file mode 100644 index 000000000..1c3b1bc23 --- /dev/null +++ b/vendor/btop/src/btop_draw.cpp @@ -0,0 +1,2551 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "btop_config.hpp" +#include "btop_draw.hpp" +#include "btop_input.hpp" +#include "btop_log.hpp" +#include "btop_menu.hpp" +#include "btop_shared.hpp" +#include "btop_theme.hpp" +#include "btop_tools.hpp" + +using std::array; +using std::clamp; +using std::cmp_equal; +using std::cmp_greater; +using std::cmp_less; +using std::cmp_less_equal; +using std::floor; +using std::max; +using std::min; +using std::round; +using std::to_string; +using std::views::iota; + +using namespace Tools; +using namespace std::literals; // for operator""s +namespace rng = std::ranges; + +const string Symbols::h_line = "─"; +const string Symbols::v_line = "│"; +const string Symbols::dotted_v_line = "╎"; +const string Symbols::left_up = "┌"; +const string Symbols::right_up = "┐"; +const string Symbols::left_down = "└"; +const string Symbols::right_down = "┘"; +const string Symbols::round_left_up = "╭"; +const string Symbols::round_right_up = "╮"; +const string Symbols::round_left_down = "╰"; +const string Symbols::round_right_down = "╯"; +const string Symbols::title_left_down = "┘"; +const string Symbols::title_right_down = "└"; +const string Symbols::title_left = "┐"; +const string Symbols::title_right = "┌"; +const string Symbols::div_right = "┤"; +const string Symbols::div_left = "├"; +const string Symbols::div_up = "┬"; +const string Symbols::div_down = "┴"; + + +const string Symbols::up = "↑"; +const string Symbols::down = "↓"; +const string Symbols::left = "←"; +const string Symbols::right = "→"; +const string Symbols::enter = "↵"; + +namespace Symbols { + const string meter = "■"; + + const array superscript = { "⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹" }; + + const std::unordered_map> graph_symbols = { + { "braille_up", { + " ", "⢀", "⢠", "⢰", "⢸", + "⡀", "⣀", "⣠", "⣰", "⣸", + "⡄", "⣄", "⣤", "⣴", "⣼", + "⡆", "⣆", "⣦", "⣶", "⣾", + "⡇", "⣇", "⣧", "⣷", "⣿" + }}, + {"braille_down", { + " ", "⠈", "⠘", "⠸", "⢸", + "⠁", "⠉", "⠙", "⠹", "⢹", + "⠃", "⠋", "⠛", "⠻", "⢻", + "⠇", "⠏", "⠟", "⠿", "⢿", + "⡇", "⡏", "⡟", "⡿", "⣿" + }}, + {"block_up", { + " ", "▗", "▗", "▐", "▐", + "▖", "▄", "▄", "▟", "▟", + "▖", "▄", "▄", "▟", "▟", + "▌", "▙", "▙", "█", "█", + "▌", "▙", "▙", "█", "█" + }}, + {"block_down", { + " ", "▝", "▝", "▐", "▐", + "▘", "▀", "▀", "▜", "▜", + "▘", "▀", "▀", "▜", "▜", + "▌", "▛", "▛", "█", "█", + "▌", "▛", "▛", "█", "█" + }}, + {"tty_up", { + " ", "░", "░", "▒", "▒", + "░", "░", "▒", "▒", "█", + "░", "▒", "▒", "▒", "█", + "▒", "▒", "▒", "█", "█", + "▒", "█", "█", "█", "█" + }}, + {"tty_down", { + " ", "░", "░", "▒", "▒", + "░", "░", "▒", "▒", "█", + "░", "▒", "▒", "▒", "█", + "▒", "▒", "▒", "█", "█", + "▒", "█", "█", "█", "█" + }} + }; + +} + +namespace Draw { + + string banner_gen(int y, int x, bool centered, bool redraw) { + static string banner; + static size_t width = 0; + if (redraw) banner.clear(); + if (banner.empty()) { + string b_color, bg, fg, oc, letter; + auto lowcolor = Config::getB("lowcolor"); + auto tty_mode = Config::getB("tty_mode"); + for (size_t z = 0; const auto& line : Global::Banner_src) { + if (const auto w = ulen(line[1]); w > width) width = w; + if (tty_mode) { + fg = (z > 2) ? "\x1b[31m" : "\x1b[91m"; + bg = (z > 2) ? "\x1b[90m" : "\x1b[37m"; + } + else { + fg = Theme::hex_to_color(line[0], lowcolor); + int bg_i = 120 - z * 12; + bg = Theme::dec_to_color(bg_i, bg_i, bg_i, lowcolor); + } + for (size_t i = 0; i < line[1].size(); i += 3) { + if (line[1][i] == ' ') { + letter = Mv::r(1); + i -= 2; + } + else + letter = line[1].substr(i, 3); + + b_color = (letter == "█") ? fg : bg; + if (b_color != oc) banner += b_color; + banner += letter; + oc = b_color; + } + if (++z < Global::Banner_src.size()) banner += Mv::l(ulen(line[1])) + Mv::d(1); + } + banner += Mv::r(18 - Global::Version.size()) + + Theme::c("main_fg") + Fx::b + Fx::i + "v" + Global::Version + Fx::reset; + } + if (redraw) return ""; + return (centered ? Mv::to(y, Term::width / 2 - width / 2) : Mv::to(y, x)) + banner; + } + + TextEdit::TextEdit() {} + TextEdit::TextEdit(string text, bool numeric) : numeric(numeric), text(std::move(text)) { + pos = this->text.size(); + upos = ulen(this->text); + } + + bool TextEdit::command(const std::string_view key) { + if (key == "left" and upos > 0) { + upos--; + pos = uresize(text, upos).size(); + } + else if (key == "right" and pos < text.size()) { + upos++; + pos = uresize(text, upos).size(); + } + else if (key == "home" and not text.empty() and pos > 0) { + pos = upos = 0; + } + else if (key == "end" and not text.empty() and pos < text.size()) { + pos = text.size(); + upos = ulen(text); + } + else if (key == "backspace" and pos > 0) { + if (pos == text.size()) { + text = uresize(text, --upos); + pos = text.size(); + } + else { + const string first = uresize(text, --upos); + pos = first.size(); + text = first + luresize(text.substr(pos), ulen(text) - upos - 1); + } + } + else if (key == "delete" and pos < text.size()) { + const string first = uresize(text, upos + 1); + text = uresize(first, ulen(first) - 1) + text.substr(first.size()); + } + else if (key == "space" and not numeric) { + text.insert(pos++, 1, ' '); + upos++; + } + else if (ulen(key) == 1 and text.size() < text.max_size() - 20) { + if (numeric and not isint(key)) return false; + if (key.size() == 1) { + text.insert(pos++, 1, key.at(0)); + upos++; + } + else { + const auto first = fmt::format("{}{}", uresize(text, upos), key); + text = first + text.substr(pos); + upos++; + pos = first.size(); + } + } + else + return false; + + return true; + } + + string TextEdit::operator()(const size_t limit) { + string out; + size_t c_upos = upos; + if (text.empty()) + return Fx::ul + " " + Fx::uul; + if (limit > 0 and ulen(text) + 1 > limit) { + try { + const size_t half = (size_t)round((double)limit / 2); + string first; + + if (upos + half > ulen(text)) + first = luresize(text.substr(0, pos), limit - (ulen(text) - upos)); + else if (upos - half < 1) + first = text.substr(0, pos); + else + first = luresize(text.substr(0, pos), half); + + out = first + uresize(text.substr(pos), limit - ulen(first)); + c_upos = ulen(first); + } + catch (const std::exception& e) { + Logger::error("In TextEdit::operator() : {}", e.what()); + return ""; + } + } + else + out = text; + + if (c_upos == 0) + return Fx::ul + uresize(out, 1) + Fx::uul + luresize(out, ulen(out) - 1); + else if (c_upos == ulen(out)) + return out + Fx::ul + " " + Fx::uul; + else + return uresize(out, c_upos) + Fx::ul + luresize(uresize(out, c_upos + 1), 1) + Fx::uul + luresize(out, ulen(out) - c_upos - 1); + } + + void TextEdit::clear() { + this->text.clear(); + } + + string createBox( + const int x, const int y, const int width, const int height, string line_color, bool fill, const std::string_view title, + const std::string_view title2, const int num + ) { + string out; + + if (line_color.empty()) + line_color = Theme::c("div_line"); + + auto tty_mode = Config::getB("tty_mode"); + auto rounded = Config::getB("rounded_corners"); + const string numbering = (num == 0) ? "" : Theme::c("hi_fg") + (tty_mode ? std::to_string(num) : Symbols::superscript.at(clamp(num, 0, 9))); + const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up); + const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up); + const auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down); + const auto& left_down = (tty_mode or not rounded ? Symbols::left_down : Symbols::round_left_down); + + out = Fx::reset + line_color; + + //? Draw horizontal lines + for (const int& hpos : {y, y + height - 1}) { + out += Mv::to(hpos, x) + Symbols::h_line * (width - 1); + } + + //? Draw vertical lines and fill if enabled + for (const int& hpos : iota(y + 1, y + height - 1)) { + out += Mv::to(hpos, x) + Symbols::v_line + + ((fill) ? string(width - 2, ' ') : Mv::r(width - 2)) + + Symbols::v_line; + } + + //? Draw corners + out += Mv::to(y, x) + left_up + + Mv::to(y, x + width - 1) + right_up + + Mv::to(y + height - 1, x) +left_down + + Mv::to(y + height - 1, x + width - 1) + right_down; + + //? Draw titles if defined + if (not title.empty()) { + out += fmt::format( + "{}{}{}{}{}{}{}{}{}", Mv::to(y, x + 2), Symbols::title_left, Fx::b, numbering, Theme::c("title"), title, Fx::ub, + line_color, Symbols::title_right + ); + } + if (not title2.empty()) { + out += fmt::format( + "{}{}{}{}{}{}{}{}{}", Mv::to(y + height - 1, x + 2), Symbols::title_left_down, Fx::b, numbering, Theme::c("title"), title2, Fx::ub, + line_color, Symbols::title_right_down + ); + } + + return out + Fx::reset + Mv::to(y + 1, x + 1); + } + + bool update_clock(bool force) { + const auto& clock_format = Config::getS("clock_format"); + if (not Cpu::shown or clock_format.empty()) { + if (clock_format.empty() and not Global::clock.empty()) Global::clock.clear(); + return false; + } + + static const std::unordered_map clock_custom_format = { + {"/user", Tools::username()}, + {"/host", Tools::hostname()}, + {"/uptime", ""} + }; + + static time_t c_time{}; + static size_t clock_len{}; + static string clock_str; + + if (auto n_time = time(nullptr); not force and n_time == c_time) + return false; + else { + c_time = n_time; + const auto new_clock = Tools::strf_time(clock_format); + if (not force and new_clock == clock_str) return false; + clock_str = new_clock; + } + + auto& out = Global::clock; + auto cpu_bottom = Config::getB("cpu_bottom"); + const auto& x = Cpu::x; + const auto y = (cpu_bottom ? Cpu::y + Cpu::height - 1 : Cpu::y); + const auto& width = Cpu::width; + const auto& title_left = (cpu_bottom ? Symbols::title_left_down : Symbols::title_left); + const auto& title_right = (cpu_bottom ? Symbols::title_right_down : Symbols::title_right); + + + for (const auto& [c_format, replacement] : clock_custom_format) { + if (clock_str.contains(c_format)) { + if (c_format == "/uptime") { + string upstr = sec_to_dhms(system_uptime()); + if (upstr.size() > 8) upstr.resize(upstr.size() - 3); + clock_str = s_replace(clock_str, c_format, upstr); + } + else { + clock_str = s_replace(clock_str, c_format, replacement); + } + } + + } + + clock_str = uresize(clock_str, std::max(10, width - 66 - (Term::width >= 100 and Config::getB("show_battery") and Cpu::has_battery ? 22 : 0))); + out.clear(); + + if (clock_str.size() != clock_len) { + if (not Global::resized and clock_len > 0) + out = Mv::to(y, x+(width / 2)-(clock_len / 2)) + Fx::ub + Theme::c("cpu_box") + Symbols::h_line * clock_len; + clock_len = clock_str.size(); + } + + out += Mv::to(y, x+(width / 2)-(clock_len / 2)) + Fx::ub + Theme::c("cpu_box") + title_left + + Theme::c("title") + Fx::b + clock_str + Theme::c("cpu_box") + Fx::ub + title_right; + + return true; + } + + //* Meter class ------------------------------------------------------------------------------------------------------------> + Meter::Meter() {} + + Meter::Meter(const int width, string color_gradient, bool invert) + : width(width), color_gradient(std::move(color_gradient)), invert(invert) {} + + string Meter::operator()(int value) { + if (width < 1) return ""; + value = clamp(value, 0, 100); + if (not cache.at(value).empty()) return cache.at(value); + auto& out = cache.at(value); + for (const int& i : iota(1, width + 1)) { + int y = round((double)i * 100.0 / width); + if (value >= y) + out += Theme::g(color_gradient).at(invert ? 100 - y : y) + Symbols::meter; + else { + out += Theme::c("meter_bg") + Symbols::meter * (width + 1 - i); + break; + } + } + out += Fx::reset; + return out; + } + + //* Graph class ------------------------------------------------------------------------------------------------------------> + void Graph::_create(const deque& data, int data_offset) { + bool mult = (data.size() - data_offset > 1); + const auto& graph_symbol = Symbols::graph_symbols.at(symbol + '_' + (invert ? "down" : "up")); + array result; + const float mod = (height == 1) ? 0.3 : 0.1; + long long data_value = 0; + if (mult and data_offset > 0) { + last = data.at(data_offset - 1); + if (max_value > 0) last = clamp((last + offset) * 100 / max_value, 0ll, 100ll); + } + + //? Horizontal iteration over values in + for (const int& i : iota(data_offset, (int)data.size())) { + // if (tty_mode and mult and i % 2 != 0) continue; + if (not tty_mode and mult) current = not current; + if (i < 0) { + data_value = 0; + last = 0; + } + else { + data_value = data.at(i); + if (max_value > 0) data_value = clamp((data_value + offset) * 100 / max_value, 0ll, 100ll); + } + + //? Vertical iteration over height of graph + for (const int& horizon : iota(0, height)) { + const int cur_high = (height > 1) ? round(100.0 * (height - horizon) / height) : 100; + const int cur_low = (height > 1) ? round(100.0 * (height - (horizon + 1)) / height) : 0; + //? Calculate previous + current value to fit two values in 1 braille character + for (int ai = 0; const auto& value : {last, data_value}) { + const int clamp_min = (no_zero and horizon == height - 1 and not (mult and i == data_offset and ai == 0)) ? 1 : 0; + if (value >= cur_high) + result[ai++] = 4; + else if (value <= cur_low) + result[ai++] = clamp_min; + else { + result[ai++] = clamp((int)round((float)(value - cur_low) * 4 / (cur_high - cur_low) + mod), clamp_min, 4); + } + } + //? Generate graph symbol from 5x5 2D vector + if (height == 1) { + if (result.at(0) + result.at(1) == 0) graphs.at(current).at(horizon) += Mv::r(1); + else { + if (not color_gradient.empty()) graphs.at(current).at(horizon) += Theme::g(color_gradient).at(clamp(max(last, data_value), 0ll, 100ll)); + graphs.at(current).at(horizon) += graph_symbol.at((result.at(0) * 5 + result.at(1))); + } + } + else graphs.at(current).at(horizon) += graph_symbol.at((result.at(0) * 5 + result.at(1))); + } + if (mult and i >= 0) last = data_value; + } + last = data_value; + out.clear(); + if (height == 1) { + //if (not color_gradient.empty()) + // out += (last < 1 ? Theme::c("inactive_fg") : Theme::g(color_gradient).at(clamp(last, 0ll, 100ll))); + out += graphs.at(current).at(0); + } + else { + for (const int& i : iota(1, height + 1)) { + if (i > 1) out += Mv::d(1) + Mv::l(width); + if (not color_gradient.empty()) + out += (invert) ? Theme::g(color_gradient).at(i * 100 / height) : Theme::g(color_gradient).at(100 - ((i - 1) * 100 / height)); + out += (invert) ? graphs.at(current).at(height - i) : graphs.at(current).at(i-1); + } + } + if (not color_gradient.empty()) out += Fx::reset; + } + + Graph::Graph() {} + + Graph::Graph(int width, int height, const string& color_gradient, + const deque& data, const string& symbol, + bool invert, bool no_zero, long long max_value, long long offset) + : width(width), height(height), color_gradient(color_gradient), + invert(invert), no_zero(no_zero), offset(offset) { + if (Config::getB("tty_mode") or symbol == "tty") this->symbol = "tty"; + else if (symbol != "default") this->symbol = symbol; + else this->symbol = Config::getS("graph_symbol"); + if (this->symbol == "tty") tty_mode = true; + + if (max_value == 0 and offset > 0) max_value = 100; + this->max_value = max_value; + const int value_width = (tty_mode ? data.size() : ceil((double)data.size() / 2)); + int data_offset = (value_width > width) ? data.size() - width * (tty_mode ? 1 : 2) : 0; + + if (not tty_mode and (data.size() - data_offset) % 2 != 0) { + data_offset--; + } + + //? Populate the two switching graph vectors and fill empty space if data size < width + for (const int& i : iota(0, height * 2)) { + if (tty_mode and i % 2 != current) continue; + graphs[(i % 2 != 0)].push_back((value_width < width) ? ((height == 1) ? Mv::r(1) : " "s) * (width - value_width) : ""); + } + if (data.size() == 0) return; + this->_create(data, data_offset); + } + + string& Graph::operator()(const deque& data, bool data_same) { + if (data_same) return out; + + //? Make room for new characters on graph + if (not tty_mode) current = not current; + for (const int& i : iota(0, height)) { + if (height == 1 and graphs.at(current).at(i).at(1) == '[') { + if (graphs.at(current).at(i).at(3) == 'C') graphs.at(current).at(i).erase(0, 4); + else graphs.at(current).at(i).erase(0, graphs.at(current).at(i).find_first_of('m') + 4); + } + else if (graphs.at(current).at(i).at(0) == ' ') graphs.at(current).at(i).erase(0, 1); + else graphs.at(current).at(i).erase(0, 3); + } + this->_create(data, (int)data.size() - 1); + return out; + } + + string& Graph::operator()() { + return out; + } + //*-------------------------------------------------------------------------------------------------------------------------> + +} + +namespace Cpu { + int width_p = 100, height_p = 32; + int min_width = 60, min_height = 8; + int x = 1, y = 1, width = 20, height; + int b_columns, b_column_size; + int b_x, b_y, b_width, b_height; + float max_observed_pwr = 1.0f; + + int graph_up_height, graph_low_height; + int graph_up_width, graph_low_width; + int gpu_meter_width; + bool shown = true, redraw = true, mid_line = false; + string box; + vector graphs_upper; + vector graphs_lower; + Draw::Meter cpu_meter; + vector gpu_meters; + vector core_graphs; + vector temp_graphs; + vector gpu_temp_graphs; + vector gpu_mem_graphs; + + string draw( + const cpu_info& cpu, +#if defined(GPU_SUPPORT) + const vector& gpus, +#endif // GPU_SUPPORT + bool force_redraw, + bool data_same + ) { + if (Runner::stopping) return ""; + if (force_redraw) redraw = true; + bool show_temps = (Config::getB("check_temp") and got_sensors); + bool show_watts = (Config::getB("show_cpu_watts") and supports_watts); + auto single_graph = Config::getB("cpu_single_graph"); + bool hide_cores = show_temps and (cpu_temp_only or not Config::getB("show_coretemp")); + const int extra_width = (hide_cores ? max(6, 6 * b_column_size) : (b_columns == 1 && !show_temps) ? 8 : 0); +#if defined(GPU_SUPPORT) + const auto& show_gpu_info = Config::getS("show_gpu_info"); + const bool gpu_always = show_gpu_info == "On"; + const bool gpu_auto = show_gpu_info == "Auto"; + const bool show_gpu = (gpus.size() > 0 and (gpu_always or (gpu_auto and Gpu::shown < Gpu::count))); +#endif // GPU_SUPPORT + auto graph_up_field = Config::getS("cpu_graph_upper"); + if (graph_up_field == "Auto" or not v_contains(Cpu::available_fields, graph_up_field)) + graph_up_field = "total"; + auto graph_lo_field = Config::getS("cpu_graph_lower"); + if (graph_lo_field == "Auto" or not v_contains(Cpu::available_fields, graph_lo_field)) { + #ifdef GPU_SUPPORT + graph_lo_field = show_gpu ? "gpu-totals" : graph_up_field; + #else + graph_lo_field = graph_up_field; + #endif + } + auto tty_mode = Config::getB("tty_mode"); + auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_cpu")); + auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6); + auto& temp_scale = Config::getS("temp_scale"); + auto cpu_bottom = Config::getB("cpu_bottom"); + const auto safe_cpu_temp_max = cpu.temp_max <= 0 ? 90 : cpu.temp_max; + + const string& title_left = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_left_down : Symbols::title_left); + const string& title_right = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_right_down : Symbols::title_right); + static int bat_pos = 0, bat_len = 0; + if (safeVal(cpu.cpu_percent, "total"s).empty() + or safeVal(cpu.core_percent, 0).empty() + or (show_temps and safeVal(cpu.temp, 0).empty())) return ""; + + string out; + out.reserve(width * height); + + //* Redraw elements not needed to be updated every cycle + if (redraw) { + mid_line = (not single_graph and graph_up_field != graph_lo_field); + graph_up_height = (single_graph ? height - 2 : ceil((double)(height - 2) / 2) - (mid_line and height % 2 != 0)); + graph_low_height = height - 2 - graph_up_height - mid_line; + const int button_y = cpu_bottom ? y + height - 1 : y; + const bool is_proc_focused = (Config::getB("follow_process") and Config::getI("followed_pid") == Config::getI("detailed_pid")) or Config::getI("proc_selected") > 0; + const bool is_proc_focused_and_in_tree = is_proc_focused and Config::getB("proc_tree"); + out += box; + + //? Buttons on title + out += Mv::to(button_y, x + 10) + title_left + Theme::c("hi_fg") + Fx::b + 'm' + Theme::c("title") + "enu" + Fx::ub + title_right; + Input::mouse_mappings["m"] = {button_y, x + 11, 1, 4}; + out += Mv::to(button_y, x + 16) + title_left + Theme::c("hi_fg") + Fx::b + 'p' + Theme::c("title") + "reset " + + (!Config::current_preset.has_value() ? "*" : to_string(Config::current_preset.value())) + Fx::ub + title_right; + Input::mouse_mappings["p"] = {button_y, x + 17, 1, 8}; + const string update = to_string(Config::getI("update_ms")) + "ms"; + fmt::format_to(std::back_inserter(out), "{}{}{}{}{}{}{}{}{}{}{}", + Mv::to(button_y, x + width - update.size() - 8), title_left, Fx::b, Theme::c(is_proc_focused_and_in_tree ? "inactive_fg" : "hi_fg"), "- ", + Theme::c(is_proc_focused_and_in_tree ? "inactive_fg" : "title"), update, + Theme::c(is_proc_focused_and_in_tree ? "inactive_fg" : "hi_fg"), " +", Fx::ub, title_right); + Input::mouse_mappings["-"] = {button_y, x + width - (int)update.size() - 7, 1, 2}; + Input::mouse_mappings["+"] = {button_y, x + width - 5, 1, 2}; + + // Draw container engine name + if (Cpu::container_engine.has_value()) { + fmt::format_to(std::back_inserter(out), "{}{}{}{}{}", Mv::to(button_y, x + 28), title_left, Theme::c("title"), Cpu::container_engine.value(), title_right); + } + + //? Graphs & meters + const int graph_default_width = x + width - b_width - 3; + + auto init_graphs = [&](vector& graphs, const int graph_height, int& graph_width, const string& graph_field, bool invert) { + #ifdef GPU_SUPPORT + if (graph_field.starts_with("gpu")) { + if (graph_field.find("totals") != string::npos) { + graphs.resize(gpus.size()); + gpu_temp_graphs.resize(gpus.size()); + gpu_mem_graphs.resize(gpus.size()); + gpu_meters.resize(gpus.size()); + const int gpu_draw_count = gpu_always ? Gpu::count : Gpu::count - Gpu::shown; + // Fairly distribute graph_default_width across gpu_draw_count GPUs, leaving 1 col per separator. + // Clamp to >=1 to avoid degenerate/negative widths reaching Draw::Graph::_create (#1118, #1017). + const int gpu_drawable_width = graph_default_width - max(0, gpu_draw_count - 1); + graph_width = gpu_draw_count <= 0 ? graph_default_width : max(1, gpu_drawable_width / gpu_draw_count); + for (size_t i = 0; i < gpus.size(); i++) { + if (gpu_auto and v_contains(Gpu::shown_panels, i)) + continue; + auto& gpu = gpus[i]; auto& graph = graphs[i]; + + //? GPU graphs + if (gpu.supported_functions.gpu_utilization) { + if (i + 1 < gpus.size()) { + graph = Draw::Graph{graph_width, graph_height, "cpu", safeVal(gpu.gpu_percent, graph_field), graph_symbol, invert, true}; + } + else { + graph = Draw::Graph{ + max(1, graph_width + (gpu_draw_count > 0 ? gpu_drawable_width % gpu_draw_count : 0)), + graph_height, "cpu", safeVal(gpu.gpu_percent, graph_field), graph_symbol, invert, true + }; + } + } + } + } else { + graphs.resize(1); + graph_width = graph_default_width; + graphs[0] = Draw::Graph{ graph_width, graph_height, "cpu", safeVal(Gpu::shared_gpu_percent, graph_field), graph_symbol, invert, true }; + } + } + else { + #endif + graphs.resize(1); + graph_width = graph_default_width; + graphs[0] = Draw::Graph{ graph_width, graph_height, "cpu", safeVal(cpu.cpu_percent, graph_field), graph_symbol, invert, true }; + #ifdef GPU_SUPPORT + } + #endif + }; + + init_graphs(graphs_upper, graph_up_height, graph_up_width, graph_up_field, false); + if (not single_graph) + init_graphs(graphs_lower, graph_low_height, graph_low_width, graph_lo_field, Config::getB("cpu_invert_lower")); + + #ifdef GPU_SUPPORT + if (show_gpu and b_columns > 1) { + gpu_temp_graphs.resize(gpus.size()); + gpu_mem_graphs.resize(gpus.size()); + gpu_meters.resize(gpus.size()); + + // Shrink gpu graph width in small boxes to prevent line width extending past box border + auto gpu_graph_width = b_width < 42 ? 4 : 5; + + for (size_t i = 0; i < gpus.size(); i++) { + if (gpu_auto and v_contains(Gpu::shown_panels, i)) + continue; + auto& gpu = gpus[i]; + + //? GPU graphs/meters + auto width_left = b_width - 10 - (gpus.size() > 9 ? 2 : gpus.size() > 1 ? 1 : 0); + if (gpu.supported_functions.temp_info and show_temps) { + gpu_temp_graphs[i] = Draw::Graph{ gpu_graph_width, 1, "temp", gpu.temp, graph_symbol, false, false, gpu.temp_max, -23 }; + width_left -= 11; + } + if (gpu.supported_functions.mem_used and gpu.supported_functions.mem_total and b_columns > 1) { + gpu_mem_graphs[i] = Draw::Graph{ gpu_graph_width, 1, "used", safeVal(gpu.gpu_percent, "gpu-vram-totals"s), graph_symbol }; + width_left -= 5; + } + width_left -= (gpu.supported_functions.mem_used ? 5 : 0); + width_left -= (gpu.supported_functions.mem_total ? 6 : 0); + width_left -= (gpu.supported_functions.pwr_usage ? 6 : 0); + if (gpu.supported_functions.gpu_utilization) { + gpu_meters[i] = Draw::Meter{width_left, "cpu" }; + } + } + } + #endif + + int cpu_meter_width = b_width - (show_temps ? 23 - (b_column_size <= 1 and b_columns == 1 ? 6 : 0) : 11); + if (show_watts) { + cpu_meter_width -= 6; + } + + cpu_meter = Draw::Meter{cpu_meter_width, "cpu"}; + + if (mid_line) { + out += Mv::to(y + graph_up_height + 1, x) + Fx::ub + Theme::c("cpu_box") + Symbols::div_left + Theme::c("div_line") + + Symbols::h_line * (width - b_width - 2) + Symbols::div_right + + Mv::to(y + graph_up_height + 1, x + ((width - b_width) / 2) - ((graph_up_field.size() + graph_lo_field.size()) / 2) - 4) + + Theme::c("main_fg") + graph_up_field + Mv::r(1) + "▲▼" + Mv::r(1) + graph_lo_field; + } + + if (b_column_size > 0 or extra_width > 0) { + core_graphs.clear(); + for (const auto& core_data : cpu.core_percent) { + core_graphs.emplace_back(5 * b_column_size + extra_width, 1, "cpu", core_data, graph_symbol); + } + } + + if (show_temps) { + temp_graphs.clear(); + temp_graphs.emplace_back(5, 1, "temp", safeVal(cpu.temp, 0), graph_symbol, false, false, safe_cpu_temp_max, -23); + if (not hide_cores and b_column_size > 1) { + for (const auto& i : iota((size_t)1, cpu.temp.size())) { + temp_graphs.emplace_back(5, 1, "temp", safeVal(cpu.temp, i), graph_symbol, false, false, safe_cpu_temp_max, -23); + } + } + } + } + + //? Draw battery if enabled and present + if (Config::getB("show_battery") and has_battery) { + static int old_percent{}; // defaults to = 0 + static long old_seconds{}; // defaults to = 0 + static float old_watts{}; // defaults to = 0 + static string old_status; + static Draw::Meter bat_meter {10, "cpu", true}; + static const std::unordered_map bat_symbols = { + {"charging", "▲"}, + {"discharging", "▼"}, + {"full", "■"}, + {"unknown", "○"} + }; + + const auto& [percent, watts, seconds, status] = current_bat; + + if (redraw or percent != old_percent or (watts != old_watts and Config::getB("show_battery_watts")) or seconds != old_seconds or status != old_status) { + old_percent = percent; + old_watts = watts; + old_seconds = seconds; + old_status = status; + const string str_time = (seconds > 0 ? sec_to_dhms(seconds, false, true) : ""); + const string str_percent = to_string(percent) + '%'; + const string str_watts = (watts != -1 and Config::getB("show_battery_watts") ? fmt::format("{:.2f}", watts) + 'W' : ""); + const auto& bat_symbol = bat_symbols.at((bat_symbols.contains(status) ? status : "unknown")); + const int current_len = (Term::width >= 100 ? 11 : 0) + str_time.size() + str_percent.size() + str_watts.size() + to_string(Config::getI("update_ms")).size(); + const int current_pos = Term::width - current_len - 17; + + if ((bat_pos != current_pos or bat_len != current_len) and bat_pos > 0 and not redraw) + out += Mv::to(y, bat_pos) + Fx::ub + Theme::c("cpu_box") + Symbols::h_line * (bat_len + 4); + bat_pos = current_pos; + bat_len = current_len; + + out += Mv::to(y, bat_pos) + title_left + Theme::c("title") + Fx::b + "BAT" + bat_symbol + ' ' + str_percent + + (Term::width >= 100 ? Fx::ub + ' ' + bat_meter(percent) + Fx::b : "") + + (not str_time.empty() ? ' ' + Theme::c("title") + str_time : "") + (not str_watts.empty() ? " " + Theme::c("title") + Fx::b + str_watts : "") + Fx::ub + title_right; + } + } + else if (bat_pos > 0) { + out += Mv::to(y, bat_pos) + Fx::ub + Theme::c("cpu_box") + Symbols::h_line * (bat_len + 4); + bat_pos = bat_len = 0; + } + + try { + //? Cpu/Gpu graphs + out += Fx::ub + Mv::to(y + 1, x + 1); + auto draw_graphs = [&](vector& graphs, const int graph_height, const int graph_width, const string& graph_field) { + #ifdef GPU_SUPPORT + if (graph_field.starts_with("gpu")) + if (graph_field.ends_with("totals")) { + int gpu_drawn = 0; + for (size_t i = 0; i < gpus.size(); i++) { + if (gpu_auto and v_contains(Gpu::shown_panels, i)) { + continue; + } + try { + const auto& gpu_percent = gpus[i].gpu_percent; + out += graphs[i](safeVal(gpu_percent, graph_field), (data_same or redraw)); + } catch (std::out_of_range& /* unused */) { + continue; + } + if (Gpu::count - (gpu_auto ? Gpu::shown : 0) > 1) { + auto i_str = to_string(i); + out += Mv::l(max(0, graph_width-1)) + Mv::u(graph_height/2) + (graph_width > 5 ? "GPU" : "") + i_str + + Mv::d(graph_height/2) + Mv::r(max(0, (int)(graph_width - 1 - (graph_width > 5)*3 - i_str.size()))); + } + + if (++gpu_drawn < Gpu::count - (gpu_auto ? Gpu::shown : 0)) + out += Theme::c("div_line") + (Symbols::v_line + Mv::l(1) + Mv::u(1))*graph_height + Mv::r(1) + Mv::d(1); + } + } + else + out += graphs[0](safeVal(Gpu::shared_gpu_percent, graph_field), (data_same or redraw)); + else + #else + (void)graph_height; + (void)graph_width; + #endif + out += graphs[0](safeVal(cpu.cpu_percent, graph_field), (data_same or redraw)); + }; + + draw_graphs(graphs_upper, graph_up_height, graph_up_width, graph_up_field); + if (not single_graph) { + out += Mv::to(y + graph_up_height + 1 + mid_line, x + 1); + draw_graphs(graphs_lower, graph_low_height, graph_low_width, graph_lo_field); + } + + //? Uptime + if (Config::getB("show_uptime")) { + string upstr = sec_to_dhms(system_uptime()); + if (upstr.size() > 8) { + upstr.resize(upstr.size() - 3); + upstr = trans(upstr); + } + out += Mv::to(y + (single_graph or not Config::getB("cpu_invert_lower") ? 1 : height - 2), x + 2) + + Theme::c("graph_text") + "up" + Mv::r(1) + upstr; + } + + #ifdef __linux__ + const bool freq_range = Config::getS("freq_mode") == "range"; + #else + const bool freq_range = false; + #endif + + //? Cpu clock and cpu meter + if (Config::getB("show_cpu_freq") and not cpuHz.empty()) + out += Mv::to(b_y, b_x + b_width - (freq_range ? 20 : 10)) + Fx::ub + Theme::c("div_line") + + Symbols::h_line * ((freq_range ? 17 : 7) - cpuHz.size()) + + Symbols::title_left + Fx::b + Theme::c("title") + cpuHz + Fx::ub + Theme::c("div_line") + Symbols::title_right; + + out += Mv::to(b_y + 1, b_x + 1) + Theme::c("main_fg") + Fx::b + "CPU " + cpu_meter(safeVal(cpu.cpu_percent, "total"s).back()) + + Theme::g("cpu").at(clamp(safeVal(cpu.cpu_percent, "total"s).back(), 0ll, 100ll)) + rjust(to_string(safeVal(cpu.cpu_percent, "total"s).back()), 4) + Theme::c("main_fg") + '%'; + if (show_temps) { + const auto [temp, unit] = celsius_to(safeVal(cpu.temp, 0).back(), temp_scale); + const auto temp_color = Theme::g("temp").at(clamp(safeVal(cpu.temp, 0).back() * 100 / safe_cpu_temp_max, 0ll, 100ll)); + if ((b_column_size > 1 or b_columns > 1) and temp_graphs.size() >= 1ll) + out += ' ' + Theme::c("inactive_fg") + graph_bg * 5 + Mv::l(5) + temp_color + + temp_graphs.at(0)(safeVal(cpu.temp, 0), data_same or redraw); + out += temp_color + rjust(to_string(temp), 4) + Theme::c("main_fg") + unit; + } + + if (show_watts) { + const auto clamped_watts = clamp(cpu.usage_watts, 0.0f, 999.0f); + string cwatts = fmt::format(" {:>4.{}f}", clamped_watts, clamped_watts < 9.995f ? 2 : clamped_watts < 99.95f ? 1 : 0); + string cwatts_post = "W"; + + max_observed_pwr = max(max_observed_pwr, clamped_watts); + out += Theme::g("cached").at(clamp(clamped_watts / max_observed_pwr * 100.0f, 0.0f, 100.0f)) + cwatts + Theme::c("main_fg") + cwatts_post; + } + + out += Theme::c("div_line") + Symbols::v_line; + } catch (const std::exception& e) { + throw std::runtime_error("graphs, clock, meter : " + string{e.what()}); + } + + int max_row = b_height - 3; // Subtracting one extra row for the load average (and power if enabled) + int n_gpus_to_show = 0; + #ifdef GPU_SUPPORT + n_gpus_to_show = show_gpu ? (gpus.size() - (gpu_always ? 0 : Gpu::shown)) : 0; + #endif + max_row -= n_gpus_to_show; + + auto is_cpu_enabled = [&cpu](const std::int32_t num) -> bool { + return !cpu.active_cpus.has_value() || std::ranges::find(cpu.active_cpus.value(), num) != cpu.active_cpus.value().end(); + }; + + //? Core text and graphs + int cx = 0, cy = 1, cc = 0, core_width = (b_column_size == 0 ? 2 : 3); + if (Shared::coreCount >= 100) core_width++; + for (const auto& n : iota(0, Shared::coreCount)) { + auto enabled = is_cpu_enabled(n); + out += Mv::to(b_y + cy + 1, b_x + cx + 1) + Theme::c(enabled ? "main_fg" : "inactive_fg") + (Shared::coreCount < 100 ? Fx::b + 'C' + Fx::ub : "") + + ljust(to_string(n), core_width); + if ((b_column_size > 0 or extra_width > 0) and cmp_less(n, core_graphs.size())) + out += Theme::c("inactive_fg") + graph_bg * (5 * b_column_size + extra_width) + Mv::l(5 * b_column_size + extra_width) + + core_graphs.at(n)(safeVal(cpu.core_percent, n), data_same or redraw); + + out += enabled ? Theme::g("cpu").at(clamp(safeVal(cpu.core_percent, n).back(), 0ll, 100ll)) : Theme::c("inactive_fg"); + out += rjust(to_string(safeVal(cpu.core_percent, n).back()), (b_column_size < 2 ? 3 : 4)) + Theme::c(enabled ? "main_fg" : "inactive_fg") + '%'; + + if (show_temps and not hide_cores) { + const auto core_temps = safeVal(cpu.temp, n + 1); + if (!core_temps.empty()) { + // FIXME: This should be checked during collection and just not be made available with + // something like `std::nullopt`. + const auto last_temp = core_temps.back(); + const auto [temp, unit] = celsius_to(last_temp, temp_scale); + const auto temp_color = enabled ? Theme::g("temp").at(clamp(last_temp * 100 / safe_cpu_temp_max, 0ll, 100ll)) : Theme::c("inactive_fg"); + if (b_column_size > 1 and std::cmp_greater_equal(temp_graphs.size(), n)) { + fmt::format_to( + std::back_inserter(out), + " {}{}{}{}", Theme::c("inactive_fg"), + graph_bg * 5, Mv::l(5), + temp_graphs.at(n + 1)(core_temps, data_same || redraw) + ); + } + fmt::format_to( + std::back_inserter(out), + "{}{}{}{}", + temp_color, + rjust(std::to_string(temp), 4), + Theme::c(enabled ? "main_fg" : "inactive_fg"), + unit + ); + } + } + + out += Theme::c("div_line") + Symbols::v_line; + + if ((++cy > ceil((double)Shared::coreCount / b_columns) or cy == max_row) and n != Shared::coreCount - 1) { + if (++cc >= b_columns) break; + cy = 1; cx = (b_width / b_columns) * cc; + } + } + + //? Load average + if (cy < b_height - 1 and cc <= b_columns) { + cy = b_height - 2 - n_gpus_to_show; + + string load_avg_pre = "Load avg:"; + string load_avg; + + for (const auto& val : cpu.load_avg) { + load_avg += fmt::format(" {:.2f}", val); + } + + int len = load_avg_pre.size() + load_avg.size(); + out += Mv::to(b_y + cy, b_x + 1) + string(max(b_width - len - 2, 0), ' ') + Theme::c("main_fg") + Fx::b + load_avg_pre + Fx::ub + load_avg; + } + + #ifdef GPU_SUPPORT + //? Gpu brief info + if (show_gpu) { + for (unsigned long i = 0; i < gpus.size(); ++i) { + if (gpu_auto and v_contains(Gpu::shown_panels, i)) + continue; + out += Mv::to(b_y + ++cy, b_x + 1) + Theme::c("main_fg") + Fx::b + "GPU"; + if (gpus.size() > 1) out += rjust(to_string(i), 1 + (gpus.size() > 9)); + if (gpus[i].supported_functions.gpu_utilization) { + out += ' '; + if (b_columns > 1) { + out += gpu_meters[i](safeVal(gpus[i].gpu_percent, "gpu-totals"s).back()) + + Theme::g("cpu").at(clamp(safeVal(gpus[i].gpu_percent, "gpu-totals"s).back(), 0ll, 100ll)); + } + out += rjust(to_string(safeVal(gpus[i].gpu_percent, "gpu-totals"s).back()), 3) + Theme::c("main_fg") + '%'; + if (b_columns == 1) + out += ' '; + } + if (gpus[i].supported_functions.mem_used and gpus[i].supported_functions.mem_total and b_columns > 1) { + out += ' ' + Theme::c("inactive_fg") + graph_bg * 5 + Mv::l(5) + Theme::g("used").at(safeVal(gpus[i].gpu_percent, "gpu-vram-totals"s).back()) + + gpu_mem_graphs[i](safeVal(gpus[i].gpu_percent, "gpu-vram-totals"s), data_same or redraw); + } + if (gpus[i].supported_functions.mem_used) { + out += Theme::c("main_fg") + + rjust(floating_humanizer(gpus[i].mem_used, true), 5); + } + if (gpus[i].supported_functions.mem_total) { + out += Theme::c("inactive_fg") + '/' + Theme::c("main_fg") + ljust(floating_humanizer(gpus[i].mem_total, true), 4); + } + if (show_temps and gpus[i].supported_functions.temp_info) { + const auto [temp, unit] = celsius_to(gpus[i].temp.back(), temp_scale); + out += ' '; + if (b_columns > 1) + out += Theme::c("inactive_fg") + graph_bg * 5 + Mv::l(5) + Theme::g("temp").at(clamp(gpus[i].temp.back() * 100 / gpus[i].temp_max, 0ll, 100ll)) + + gpu_temp_graphs[i](gpus[i].temp, data_same or redraw); + else out += Theme::g("temp").at(clamp(gpus[i].temp.back() * 100 / gpus[i].temp_max, 0ll, 100ll)); + out += rjust(to_string(temp), 3) + Theme::c("main_fg") + unit; + } + if (gpus[i].supported_functions.pwr_usage) { + out += ' ' + Theme::g("cached").at(clamp(safeVal(gpus[i].gpu_percent, "gpu-pwr-totals"s).back(), 0ll, 100ll)) + + fmt::format("{:>4.{}f}", gpus[i].pwr_usage / 1000.0, gpus[i].pwr_usage < 10'000 ? 2 : gpus[i].pwr_usage < 100'000 ? 1 : 0) + Theme::c("main_fg") + 'W'; + } + + if (cy > b_height - 1) break; + } + } + #endif + + redraw = false; + return out + Fx::reset; + } + +} + +#ifdef GPU_SUPPORT +namespace Gpu { + int width_p = 100, height_p = 32; + int min_width = 41, min_height = 8; + int width = 41, total_height; + vector x_vec = {}, y_vec = {}, b_height_vec = {}; + int b_width; + vector b_x_vec = {}, b_y_vec = {}; + vector redraw = {}; + int shown = 0; + int count = 0; + vector shown_panels = {}; + int graph_up_height; + vector graph_upper_vec = {}, graph_lower_vec = {}; + vector temp_graph_vec = {}; + vector mem_used_graph_vec = {}, mem_util_graph_vec = {}; + vector gpu_meter_vec = {}; + vector pwr_meter_vec = {}; + vector enc_meter_vec = {}; + vector box = {}; + + string draw(const gpu_info& gpu, unsigned long index, bool force_redraw, bool data_same) { + if (Runner::stopping) return ""; + + auto& b_x = b_x_vec[index]; + auto& b_y = b_y_vec[index]; + auto& x = x_vec[index]; + auto& y = y_vec[index]; + + auto& graph_upper = graph_upper_vec[index]; + auto& graph_lower = graph_lower_vec[index]; + auto& temp_graph = temp_graph_vec[index]; + auto& mem_used_graph = mem_used_graph_vec[index]; + auto& mem_util_graph = mem_util_graph_vec[index]; + auto& gpu_meter = gpu_meter_vec[index]; + auto& pwr_meter = pwr_meter_vec[index]; + auto& enc_meter = enc_meter_vec[index]; + + if (force_redraw) redraw[index] = true; + bool show_temps = gpu.supported_functions.temp_info and (Config::getB("check_temp")); + auto tty_mode = Config::getB("tty_mode"); + auto& temp_scale = Config::getS("temp_scale"); + auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_gpu")); + auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6); + auto single_graph = !Config::getB("gpu_mirror_graph"); + string out; + int height = gpu_b_height_offsets[index] + 4; + out.reserve(width * height); + + //* Redraw elements not needed to be updated every cycle + if (redraw[index]) { + out += box[index]; + + graph_up_height = single_graph ? b_height_vec[index] : (b_height_vec[index] + 1) / 2; + int graph_low_height = single_graph ? 0 : b_height_vec[index] - graph_up_height; + + if (gpu.supported_functions.gpu_utilization) { + graph_upper = Draw::Graph{x + width - b_width - 3, graph_up_height, "cpu", safeVal(gpu.gpu_percent, "gpu-totals"s), graph_symbol, false, true}; // TODO cpu -> gpu + if (not single_graph) { + graph_lower = Draw::Graph{ + x + width - b_width - 3, + graph_low_height, "cpu", + safeVal(gpu.gpu_percent, "gpu-totals"s), + graph_symbol, + Config::getB("cpu_invert_lower"), true + }; + } + gpu_meter = Draw::Meter{b_width - (show_temps ? 25 : 12), "cpu"}; + } + if (gpu.supported_functions.temp_info) + temp_graph = Draw::Graph{6, 1, "temp", gpu.temp, graph_symbol, false, false, gpu.temp_max, -23}; + if (gpu.supported_functions.pwr_usage) + pwr_meter = Draw::Meter{b_width - (gpu.supported_functions.pwr_state and gpu.pwr_state != 32 ? 25 : 12), "cached"}; + if (gpu.supported_functions.mem_utilization) + mem_util_graph = Draw::Graph{b_width/2 - 1, 2, "free", gpu.mem_utilization_percent, graph_symbol, 0, 0, 100, 4}; // offset so the graph isn't empty at 0-5% utilization + if (gpu.supported_functions.mem_used and gpu.supported_functions.mem_total) + mem_used_graph = Draw::Graph{b_width/2 - 2, 2 + 2*(gpu.supported_functions.mem_utilization), "used", safeVal(gpu.gpu_percent, "gpu-vram-totals"s), graph_symbol}; + if (gpu.supported_functions.encoder_utilization) + enc_meter = Draw::Meter{b_width/2 - 10, "cpu"}; + } + + + //* General GPU info + int rows_used = 1; + //? Gpu graph, meter & clock speed + if (gpu.supported_functions.gpu_utilization) { + out += Fx::ub + Mv::to(y + rows_used, x + 1) + graph_upper(safeVal(gpu.gpu_percent, "gpu-totals"s), (data_same or redraw[index])); + if (not single_graph) + out += Mv::to(y + rows_used + graph_up_height, x + 1) + graph_lower(safeVal(gpu.gpu_percent, "gpu-totals"s), (data_same or redraw[index])); + + out += Mv::to(b_y + rows_used, b_x + 1) + Theme::c("main_fg") + Fx::b + "GPU " + gpu_meter(safeVal(gpu.gpu_percent, "gpu-totals"s).back()) + + Theme::g("cpu").at(clamp(safeVal(gpu.gpu_percent, "gpu-totals"s).back(), 0ll, 100ll)) + rjust(to_string(safeVal(gpu.gpu_percent, "gpu-totals"s).back()), 5) + Theme::c("main_fg") + '%'; + + //? Temperature graph, I assume the device supports utilization if it supports temperature + if (show_temps) { + const auto [temp, unit] = celsius_to(gpu.temp.back(), temp_scale); + out += ' ' + Theme::c("inactive_fg") + graph_bg * 6 + Mv::l(6) + Theme::g("temp").at(clamp(gpu.temp.back() * 100 / gpu.temp_max, 0ll, 100ll)) + + temp_graph(gpu.temp, data_same or redraw[index]); + out += rjust(to_string(temp), 4) + Theme::c("main_fg") + unit; + } + out += Theme::c("div_line") + Symbols::v_line; + rows_used++; + } + + if (gpu.supported_functions.gpu_clock) { + string clock_speed_string = to_string(gpu.gpu_clock_speed); + out += Mv::to(b_y, b_x + b_width - 12) + Theme::c("div_line") + Symbols::h_line*(5-clock_speed_string.size()) + + Symbols::title_left + Fx::b + Theme::c("title") + clock_speed_string + " MHz" + Fx::ub + Theme::c("div_line") + Symbols::title_right; + } + + //? Power usage meter, power state + if (gpu.supported_functions.pwr_usage) { + out += Mv::to(b_y + rows_used, b_x + 1) + Theme::c("main_fg") + Fx::b + "PWR " + pwr_meter(safeVal(gpu.gpu_percent, "gpu-pwr-totals"s).back()) + + Theme::g("cached").at(clamp(safeVal(gpu.gpu_percent, "gpu-pwr-totals"s).back(), 0ll, 100ll)) + + fmt::format("{:>5.{}f}", gpu.pwr_usage / 1000.0, gpu.pwr_usage < 10'000 ? 2 : gpu.pwr_usage < 100'000 ? 1 : 0) + Theme::c("main_fg") + 'W'; + if (gpu.supported_functions.pwr_state and gpu.pwr_state != 32) // NVML_PSTATE_UNKNOWN; unsupported or non-nvidia card + out += std::string(" P-state: ") + (gpu.pwr_state > 9 ? "" : " ") + 'P' + Theme::g("cached").at(clamp(gpu.pwr_state, 0ll, 100ll)) + to_string(gpu.pwr_state); + rows_used++; + } + + //? Encode and Decode meters + bool drawnEncDec = gpu.supported_functions.encoder_utilization and gpu.supported_functions.decoder_utilization; + if (drawnEncDec) { + out += Mv::to(b_y + rows_used, b_x +1) + Theme::c("main_fg") + Fx::b + "ENC " + enc_meter(gpu.encoder_utilization) + + Theme::g("cpu").at(clamp(gpu.encoder_utilization, 0ll, 100ll)) + rjust(to_string(gpu.encoder_utilization), 4) + Theme::c("main_fg") + '%' + + Theme::c("div_line") + Symbols::v_line + Theme::c("main_fg") + Fx::b + "DEC " + enc_meter(gpu.decoder_utilization) + + Theme::g("cpu").at(clamp(gpu.decoder_utilization, 0ll, 100ll)) + rjust(to_string(gpu.decoder_utilization), 4) + Theme::c("main_fg") + '%'; + rows_used++; + } + + if (gpu.supported_functions.mem_total or gpu.supported_functions.mem_used) { + out += Mv::to(b_y + rows_used, b_x); + if (gpu.supported_functions.mem_total and gpu.supported_functions.mem_used) { + string used_memory_string = floating_humanizer(gpu.mem_used); + + auto offset = (gpu.supported_functions.mem_total or gpu.supported_functions.mem_used) + * (1 + 2*(gpu.supported_functions.mem_total and gpu.supported_functions.mem_used) + 2*gpu.supported_functions.mem_utilization); + + //? Used graph, memory section header, total vram + out += Theme::c("div_line") + Symbols::div_left + Symbols::h_line + Symbols::title_left + Fx::b + Theme::c("title") + "vram" + Theme::c("div_line") + Fx::ub + Symbols::title_right + + Symbols::h_line*(b_width/2-8) + Symbols::div_up + Mv::d(offset)+Mv::l(1) + Symbols::div_down + Mv::l(1)+Mv::u(1) + (Symbols::v_line + Mv::l(1)+Mv::u(1))*(offset-1) + Symbols::div_up + + Symbols::h_line + Theme::c("title") + "Used:" + Theme::c("div_line") + + Symbols::h_line*(b_width/2+b_width%2-9-used_memory_string.size()) + Theme::c("title") + used_memory_string + Theme::c("div_line") + Symbols::h_line + Symbols::div_right + + Mv::d(1) + Mv::l(b_width/2-1) + mem_used_graph(safeVal(gpu.gpu_percent, "gpu-vram-totals"s), (data_same or redraw[index])) + + Mv::l(b_width-3) + Mv::u(1+2*gpu.supported_functions.mem_utilization) + Theme::c("main_fg") + Fx::b + "Total:" + rjust(floating_humanizer(gpu.mem_total), b_width/2-9) + Fx::ub + + Mv::r(3) + rjust(to_string(safeVal(gpu.gpu_percent, "gpu-vram-totals"s).back()), 3) + '%'; + + //? Memory utilization + if (gpu.supported_functions.mem_utilization) + out += Mv::l(b_width/2+6) + Mv::d(1) + Theme::c("div_line") + Symbols::div_left+Symbols::h_line + Theme::c("title") + "Utilization:" + Theme::c("div_line") + Symbols::h_line*(b_width/2-14) + Symbols::div_right + + Mv::l(b_width/2) + Mv::d(1) + mem_util_graph(gpu.mem_utilization_percent, (data_same or redraw[index])) + + Mv::l(b_width/2-1) + Mv::u(1) + rjust(to_string(gpu.mem_utilization_percent.back()), 3) + '%'; + + //? Memory clock speed + if (gpu.supported_functions.mem_clock) { + string clock_speed_string = to_string(gpu.mem_clock_speed); + out += Mv::to(b_y + rows_used, b_x + b_width/2 - 11) + Theme::c("div_line") + Symbols::h_line*(5-clock_speed_string.size()) + + Symbols::title_left + Fx::b + Theme::c("title") + clock_speed_string + " MHz" + Fx::ub + Theme::c("div_line") + Symbols::title_right; + } + } else { + out += Theme::c("main_fg") + Mv::r(1); + if (gpu.supported_functions.mem_total) + out += "VRAM total:" + rjust(floating_humanizer(gpu.mem_total), b_width/(1 + gpu.supported_functions.mem_clock)-14); + else out += "VRAM usage:" + rjust(floating_humanizer(gpu.mem_used), b_width/(1 + gpu.supported_functions.mem_clock)-14); + + if (gpu.supported_functions.mem_clock) + out += " VRAM clock:" + rjust(to_string(gpu.mem_clock_speed) + " MHz", b_width/2-13); + } + } + + //? Processes section header + //out += Mv::to(b_y+8, b_x) + Theme::c("div_line") + Symbols::div_left + Symbols::h_line + Symbols::title_left + Theme::c("main_fg") + Fx::b + "gpu-proc" + Fx::ub + Theme::c("div_line") + // + Symbols::title_right + Symbols::h_line*(b_width/2-12) + Symbols::div_down + Symbols::h_line*(b_width/2-2) + Symbols::div_right; + + //? PCIe link throughput + // Negative RX/TX means that they are manually disabled, not that they are unsupported + if (gpu.supported_functions.pcie_txrx and not (gpu.pcie_rx < 0 or gpu.pcie_tx < 0)) { + string tx_string = floating_humanizer(gpu.pcie_tx, 0, 1, 0, 1); + string rx_string = floating_humanizer(gpu.pcie_rx, 0, 1, 0, 1); + out += Mv::to(b_y + height - 3, b_x+2) + Theme::c("div_line") + + Symbols::title_left_down + Theme::c("title") + Fx::b + "TX:" + Fx::ub + Theme::c("div_line") + Symbols::title_right_down + Symbols::h_line*(b_width/2-9-tx_string.size()) + + Symbols::title_left_down + Theme::c("title") + Fx::b + tx_string + Fx::ub + Theme::c("div_line") + Symbols::title_right_down + (gpu.supported_functions.mem_total and gpu.supported_functions.mem_used ? Symbols::div_down : Symbols::h_line) + + Symbols::title_left_down + Theme::c("title") + Fx::b + "RX:" + Fx::ub + Theme::c("div_line") + Symbols::title_right_down + Symbols::h_line*(b_width/2+b_width%2-9-rx_string.size()) + + Symbols::title_left_down + Theme::c("title") + Fx::b + rx_string + Fx::ub + Theme::c("div_line") + Symbols::title_right_down + Symbols::round_right_down; + } + + redraw[index] = false; + return out + Fx::reset; + } + +} +#endif + +namespace Mem { + int width_p = 45, height_p = 40; + int min_width = 36, min_height = 10; + int x = 1, y, width = 20, height; + int mem_width, disks_width, divider, item_height, mem_size, mem_meter, graph_height, disk_meter; + int disks_io_h = 0; + int disks_io_half = 0; + bool shown = true, redraw = true; + string box; + std::unordered_map mem_meters; + std::unordered_map mem_graphs; + std::unordered_map disk_meters_used; + std::unordered_map disk_meters_free; + std::unordered_map io_graphs; + + string draw(const mem_info& mem, bool force_redraw, bool data_same) { + if (Runner::stopping) return ""; + if (force_redraw) redraw = true; + auto show_swap = Config::getB("show_swap"); + auto swap_disk = Config::getB("swap_disk"); + auto show_disks = Config::getB("show_disks"); + auto show_io_stat = Config::getB("show_io_stat"); + auto io_mode = Config::getB("io_mode"); + auto io_graph_combined = Config::getB("io_graph_combined"); + auto use_graphs = Config::getB("mem_graphs"); + auto tty_mode = Config::getB("tty_mode"); + auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_mem")); + auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6); + auto totalMem = Mem::get_totalMem(); + string out; + out.reserve(height * width); + + //* Redraw elements not needed to be updated every cycle + if (redraw) { + out += box; + mem_meters.clear(); + mem_graphs.clear(); + disk_meters_free.clear(); + disk_meters_used.clear(); + io_graphs.clear(); + + //? Mem graphs and meters + for (const auto& name : mem_names) { + + if (use_graphs) + mem_graphs[name] = Draw::Graph{mem_meter, graph_height, name, safeVal(mem.percent, name), graph_symbol}; + else + mem_meters[name] = Draw::Meter{mem_meter, name}; + } + if (show_swap and has_swap) { + for (const auto& name : swap_names) { + if (use_graphs) + mem_graphs[name] = Draw::Graph{mem_meter, graph_height, name.substr(5), safeVal(mem.percent, name), graph_symbol}; + else + mem_meters[name] = Draw::Meter{mem_meter, name.substr(5)}; + } + } + + //? Disk meters and io graphs + if (show_disks) { + if (show_io_stat or io_mode) { + std::unordered_map custom_speeds; + int half_height = 0; + if (io_mode) { + disks_io_h = max((int)floor((double)(height - 2 - (disk_ios * 2)) / max(1, disk_ios)), (io_graph_combined ? 1 : 2)); + half_height = ceil((double)disks_io_h / 2); + + if (not Config::getS("io_graph_speeds").empty()) { + auto split = ssplit(Config::getS("io_graph_speeds")); + for (const auto& entry : split) { + auto vals = ssplit(entry, ':'); + if (vals.size() == 2 and mem.disks.contains(vals.at(0)) and isint(vals.at(1))) + try { + custom_speeds[vals.at(0)] = std::stoi(vals.at(1)); + } + catch (const std::out_of_range&) { continue; } + } + } + } + + for (const auto& [name, disk] : mem.disks) { + if (disk.io_read.empty()) continue; + + io_graphs[name + "_activity"] = Draw::Graph{disks_width - 6, 1, "available", disk.io_activity, graph_symbol}; + + if (io_mode) { + //? Create one combined graph for IO read/write if enabled + long long speed = static_cast(custom_speeds.contains(name) ? custom_speeds.at(name) : 100) << 20; + if (io_graph_combined) { + deque combined(disk.io_read.size(), 0); + rng::transform(disk.io_read, disk.io_write, combined.begin(), std::plus()); + io_graphs[name] = Draw::Graph{ + disks_width, disks_io_h, "available", combined, + graph_symbol, false, true, speed}; + } + else { + io_graphs[name + "_read"] = Draw::Graph{ + disks_width, half_height, "free", + disk.io_read, graph_symbol, false, + true, speed}; + io_graphs[name + "_write"] = Draw::Graph{ + disks_width, disks_io_h - half_height, + "used", disk.io_write, graph_symbol, + true, true, speed}; + } + } + } + } + + for (int i = 0; const auto& [name, ignored] : mem.disks) { + if (i * 2 > height - 2) break; + disk_meters_used[name] = Draw::Meter{disk_meter, "used"}; + if (cmp_less_equal(mem.disks.size() * 3, height - 1)) + disk_meters_free[name] = Draw::Meter{disk_meter, "free"}; + } + + out += Mv::to(y, x + width - 6) + Fx::ub + Theme::c("mem_box") + Symbols::title_left + (io_mode ? Fx::b : "") + Theme::c("hi_fg") + + 'i' + Theme::c("title") + 'o' + Fx::ub + Theme::c("mem_box") + Symbols::title_right; + Input::mouse_mappings["i"] = {y, x + width - 5, 1, 2}; + } + + } + + //? Mem and swap + int cx = 1, cy = 1; + string divider = (graph_height > 0 ? Mv::l(2) + Theme::c("mem_box") + Symbols::div_left + Theme::c("div_line") + Symbols::h_line * (mem_width - 1) + + (show_disks ? "" : Theme::c("mem_box")) + Symbols::div_right + Mv::l(mem_width - 1) + Theme::c("main_fg") : ""); + string up = (graph_height >= 2 ? Mv::l(mem_width - 2) + Mv::u(graph_height - 1) : ""); + bool big_mem = mem_width > 21; + + out += Mv::to(y + 1, x + 2) + Theme::c("title") + Fx::b + "Total:" + rjust(floating_humanizer(totalMem), mem_width - 9) + Fx::ub + Theme::c("main_fg"); + vector comb_names (mem_names.begin(), mem_names.end()); + if (show_swap and has_swap and not swap_disk) comb_names.insert(comb_names.end(), swap_names.begin(), swap_names.end()); + for (const auto& name : comb_names) { + if (cy > height - 4) break; + string title; + if (name == "swap_used") { + if (cy > height - 5) break; + if (height - cy > 6) { + if (graph_height > 0) out += Mv::to(y+1+cy, x+1+cx) + divider; + cy += 1; + } + out += Mv::to(y+1+cy, x+1+cx) + Theme::c("title") + Fx::b + "Swap:" + rjust(floating_humanizer(safeVal(mem.stats, "swap_total"s)), mem_width - 8) + + Theme::c("main_fg") + Fx::ub; + cy += 1; + title = "Used"; + } + else if (name == "swap_free") + title = "Free"; + + if (title.empty()) title = capitalize(name); + const string humanized = floating_humanizer(safeVal(mem.stats, name)); + const int offset = max(0, divider.empty() ? 9 - (int)humanized.size() : 0); + const string graphics = ( + use_graphs and mem_graphs.contains(name) ? mem_graphs.at(name)(safeVal(mem.percent, name), redraw or data_same) + : mem_meters.contains(name) ? mem_meters.at(name)(safeVal(mem.percent, name).back()) + : ""); + if (mem_size > 2) { + out += Mv::to(y+1+cy, x+1+cx) + divider + title.substr(0, big_mem ? 10 : 5) + ":" + + Mv::to(y+1+cy, x+cx + mem_width - 2 - humanized.size()) + (divider.empty() ? Mv::l(offset) + string(" ") * offset + humanized : trans(humanized)) + + Mv::to(y+2+cy, x+cx + (graph_height >= 2 ? 0 : 1)) + graphics + up + rjust(to_string(safeVal(mem.percent, name).back()) + "%", 4); + cy += (graph_height == 0 ? 2 : graph_height + 1); + } + else { + out += Mv::to(y+1+cy, x+1+cx) + ljust(title, (mem_size > 1 ? 5 : 1)) + (graph_height >= 2 ? "" : " ") + + graphics + Theme::c("title") + rjust(humanized, (mem_size > 1 ? 9 : 7)); + cy += (graph_height == 0 ? 1 : graph_height); + } + } + if (graph_height > 0 and cy < height - 2) + out += Mv::to(y+1+cy, x+1+cx) + divider; + + //? Disks + if (show_disks) { + const auto& disks = mem.disks; + cx = mem_width; cy = 0; + bool big_disk = disks_width >= 25; + divider = Mv::l(1) + Theme::c("div_line") + Symbols::div_left + Symbols::h_line * disks_width + Theme::c("mem_box") + Fx::ub + Symbols::div_right + Mv::l(disks_width); + const string hu_div = Theme::c("div_line") + Symbols::h_line + Theme::c("main_fg"); + if (io_mode) { + for (const auto& mount : mem.disks_order) { + if (not disks.contains(mount)) continue; + if (cy > height - 3) break; + const auto disk = safeVal(disks, mount); + if (disk.io_read.empty()) continue; + const string total = floating_humanizer(disk.total, not big_disk); + out += Mv::to(y+1+cy, x+1+cx) + divider + Theme::c("title") + Fx::b + uresize(disk.name, disks_width - 8) + Mv::to(y+1+cy, x+cx + disks_width - total.size()) + + trans(total) + Fx::ub; + if (big_disk) { + const string used_percent = to_string(disk.used_percent); + out += Mv::to(y+1+cy, x+1+cx + round((double)disks_width / 2) - round((double)used_percent.size() / 2) - 1) + hu_div + used_percent + '%' + hu_div; + } + if (io_graphs.contains(mount + "_activity")) { + out += Mv::to(y+2+cy++, x+1+cx) + (big_disk ? " IO% " : " IO " + Mv::l(2)) + Theme::c("inactive_fg") + graph_bg * (disks_width - 6) + + Mv::l(disks_width - 6) + io_graphs.at(mount + "_activity")(disk.io_activity, redraw or data_same) + Theme::c("main_fg"); + } + if (++cy > height - 3) break; + if (io_graph_combined) { + if (not io_graphs.contains(mount)) continue; + auto comb_val = disk.io_read.back() + disk.io_write.back(); + const string humanized = (disk.io_write.back() > 0 ? "▼"s : ""s) + (disk.io_read.back() > 0 ? "▲"s : ""s) + + (comb_val > 0 ? Mv::r(1) + floating_humanizer(comb_val, true) : "RW"); + if (disks_io_h == 1) out += Mv::to(y+1+cy, x+1+cx) + string(5, ' '); + out += Mv::to(y+1+cy, x+1+cx) + io_graphs.at(mount)({comb_val}, redraw or data_same) + + Mv::to(y+1+cy, x+1+cx) + Theme::c("main_fg") + humanized; + cy += disks_io_h; + } + else { + if (not io_graphs.contains(mount + "_read") or not io_graphs.contains(mount + "_write")) continue; + const string human_read = (disk.io_read.back() > 0 ? "▲" + floating_humanizer(disk.io_read.back(), true) : "R"); + const string human_write = (disk.io_write.back() > 0 ? "▼" + floating_humanizer(disk.io_write.back(), true) : "W"); + if (disks_io_h <= 3) out += Mv::to(y+1+cy, x+1+cx) + string(5, ' ') + Mv::to(y+cy + disks_io_h, x+1+cx) + string(5, ' '); + out += Mv::to(y+1+cy, x+1+cx) + io_graphs.at(mount + "_read")(disk.io_read, redraw or data_same) + Mv::l(disks_width) + + Mv::d(1) + io_graphs.at(mount + "_write")(disk.io_write, redraw or data_same) + + Mv::to(y+1+cy, x+1+cx) + human_read + Mv::to(y+cy + disks_io_h, x+1+cx) + human_write; + cy += disks_io_h; + } + } + } + else { + for (const auto& mount : mem.disks_order) { + if (not disks.contains(mount)) continue; + if (cy > height - 3) break; + const auto disk = safeVal(disks, mount); + if (disk.name.empty() or not disk_meters_used.contains(mount)) continue; + auto comb_val = (not disk.io_read.empty() ? disk.io_read.back() + disk.io_write.back() : 0ll); + const string human_io = (comb_val > 0 ? (disk.io_write.back() > 0 and big_disk ? "▼"s : ""s) + (disk.io_read.back() > 0 and big_disk ? "▲"s : ""s) + + floating_humanizer(comb_val, true) : ""); + const string human_total = floating_humanizer(disk.total, not big_disk); + const string human_used = floating_humanizer(disk.used, not big_disk); + const string human_free = floating_humanizer(disk.free, not big_disk); + + out += Mv::to(y+1+cy, x+1+cx) + divider + Theme::c("title") + Fx::b + uresize(disk.name, disks_width - 8) + Mv::to(y+1+cy, x+cx + disks_width - human_total.size()) + + trans(human_total) + Fx::ub + Theme::c("main_fg"); + if (big_disk and not human_io.empty()) + out += Mv::to(y+1+cy, x+1+cx + round((double)disks_width / 2) - round((double)human_io.size() / 2) - 1) + hu_div + human_io + hu_div; + if (++cy > height - 3) break; + if (show_io_stat and io_graphs.contains(mount + "_activity")) { + out += Mv::to(y+1+cy, x+1+cx) + (big_disk ? " IO% " : " IO " + Mv::l(2)) + Theme::c("inactive_fg") + graph_bg * (disks_width - 6) + Theme::g("available").at(clamp(disk.io_activity.back(), 50ll, 100ll)) + + Mv::l(disks_width - 6) + io_graphs.at(mount + "_activity")(disk.io_activity, redraw or data_same) + Theme::c("main_fg"); + if (not big_disk) out += Mv::to(y+1+cy, x+cx+1) + Theme::c("main_fg") + human_io; + if (++cy > height - 3) break; + } + + out += Mv::to(y+1+cy, x+1+cx) + (big_disk ? " Used:" + rjust(to_string(disk.used_percent) + '%', 4) : "U") + ' ' + + disk_meters_used.at(mount)(disk.used_percent) + rjust(human_used, (big_disk ? 9 : 5)); + if (++cy > height - 3) break; + + if (disk_meters_free.contains(mount) and cmp_less_equal(disks.size() * 3 + (show_io_stat ? disk_ios : 0), height - 1)) { + out += Mv::to(y+1+cy, x+1+cx) + (big_disk ? " Free:" + rjust(to_string(disk.free_percent) + '%', 4) : "F") + ' ' + + disk_meters_free.at(mount)(disk.free_percent) + rjust(human_free, (big_disk ? 9 : 5)); + cy++; + if (cmp_less_equal(disks.size() * 4 + (show_io_stat ? disk_ios : 0), height - 1)) cy++; + } + + } + } + if (cy < height - 2) out += Mv::to(y+1+cy, x+1+cx) + divider; + } + + redraw = false; + return out + Fx::reset; + } + +} + +namespace Net { + int width_p = 45, height_p = 28; + int min_width = 36, min_height = 6; + int x = 1, y, width = 20, height; + int b_x, b_y, b_width, b_height, d_graph_height, u_graph_height; + bool shown = true, redraw = true; + const int MAX_IFNAMSIZ = 15; + string old_ip; + std::unordered_map graphs; + string box; + + string draw(const net_info& net, bool force_redraw, bool data_same) { + if (Runner::stopping) return ""; + if (force_redraw) redraw = true; + auto net_sync = Config::getB("net_sync"); + auto net_auto = Config::getB("net_auto"); + auto tty_mode = Config::getB("tty_mode"); + auto swap_upload_download = Config::getB("swap_upload_download"); + auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_net")); + string ip_addr = (net.ipv4.empty() ? net.ipv6 : net.ipv4); + if (old_ip != ip_addr) { + old_ip = ip_addr; + redraw = true; + } + string out; + out.reserve(width * height); + const string title_left = Theme::c("net_box") + Fx::ub + Symbols::title_left; + const string title_right = Theme::c("net_box") + Fx::ub + Symbols::title_right; + const int i_size = min((int)selected_iface.size(), MAX_IFNAMSIZ); + const long long down_max = (net_auto ? safeVal(graph_max, "download"s) : ((long long)(Config::getI("net_download")) << 20) / 8); + const long long up_max = (net_auto ? safeVal(graph_max, "upload"s) : ((long long)(Config::getI("net_upload")) << 20) / 8); + + //* Redraw elements not needed to be updated every cycle + if (redraw) { + out = box; + //? Graphs + graphs.clear(); + if (safeVal(net.bandwidth, "download"s).empty() or safeVal(net.bandwidth, "upload"s).empty()) + return out + Fx::reset; + + graphs["download"] = Draw::Graph{ + width - b_width - 2, u_graph_height, "download", + net.bandwidth.at("download"), graph_symbol, + swap_upload_download, true, down_max}; + graphs["upload"] = Draw::Graph{ + width - b_width - 2, d_graph_height, "upload", + net.bandwidth.at("upload"), graph_symbol, !swap_upload_download, true, up_max}; + + //? Interface selector and buttons + + out += Mv::to(y, x+width - i_size - 9) + title_left + Fx::b + Theme::c("hi_fg") + Symbols::left + "b " + Theme::c("title") + + uresize(selected_iface, MAX_IFNAMSIZ) + Theme::c("hi_fg") + " n" + Symbols::right + title_right + + Mv::to(y, x+width - i_size - 15) + title_left + Theme::c("hi_fg") + (safeVal(net.stat, "download"s).offset + safeVal(net.stat, "upload"s).offset > 0 ? Fx::b : "") + 'z' + + Theme::c("title") + "ero" + title_right; + Input::mouse_mappings["b"] = {y, x+width - i_size - 8, 1, 3}; + Input::mouse_mappings["n"] = {y, x+width - 6, 1, 3}; + Input::mouse_mappings["z"] = {y, x+width - i_size - 14, 1, 4}; + if (width - i_size - 20 > 6) { + out += Mv::to(y, x+width - i_size - 21) + title_left + Theme::c("hi_fg") + (net_auto ? Fx::b : "") + 'a' + Theme::c("title") + "uto" + title_right; + Input::mouse_mappings["a"] = {y, x+width - i_size - 20, 1, 4}; + } + if (width - i_size - 20 > 13) { + out += Mv::to(y, x+width - i_size - 27) + title_left + Theme::c("title") + (net_sync ? Fx::b : "") + 's' + Theme::c("hi_fg") + + 'y' + Theme::c("title") + "nc" + title_right; + Input::mouse_mappings["y"] = {y, x+width - i_size - 26, 1, 4}; + } + } + + //? IP or device address + if (not ip_addr.empty() and cmp_greater(width - i_size - 36, ip_addr.size())) { + out += Mv::to(y, x + 8) + title_left + Theme::c("title") + Fx::b + ip_addr + title_right; + } + + //? Graphs and stats + for (const string dir : {"download", "upload"}) { + // | upload | download | + // no swap | bottom | top | + // swap | top | bottom | + // XNOR operation (==) + if ((not swap_upload_download and dir == "download") or (swap_upload_download and dir == "upload")) { + out += Mv::to(y+1, x + 1); + } else { + out += Mv::to(y + u_graph_height + 1 + ((height * swap_upload_download) % 2), x + 1); + } + out += graphs.at(dir)(safeVal(net.bandwidth, dir), redraw or data_same or not net.connected) + + Mv::to(y+1 + (((dir == "upload") == (!swap_upload_download)) * (height - 3)), x + 1) + Fx::ub + Theme::c("graph_text") + + floating_humanizer((dir == "upload" ? up_max : down_max), true); + const string speed = floating_humanizer(safeVal(net.stat, dir).speed, false, 0, false, true); + const string speed_bits = (b_width >= 20 ? floating_humanizer(safeVal(net.stat, dir).speed, false, 0, true, true) : ""); + const string top = floating_humanizer(safeVal(net.stat, dir).top, false, 0, true, true); + const string total = floating_humanizer(safeVal(net.stat, dir).total); + const string symbol = (dir == "upload" ? "▲" : "▼"); + if ((swap_upload_download and dir == "upload") or (not swap_upload_download and dir == "download")) { + // Top graph + out += Mv::to(b_y+1, b_x+1) + Fx::ub + Theme::c("main_fg") + symbol + ' ' + ljust(speed, 10) + (b_width >= 20 ? rjust('(' + speed_bits + ')', 13) : ""); + if (b_height >= 8) + out += Mv::to(b_y+2, b_x+1) + symbol + ' ' + "Top: " + rjust('(' + top, (b_width >= 20 ? 17 : 9)) + ')'; + if (b_height >= 6) + out += Mv::to(b_y+2 + (b_height >= 8), b_x+1) + symbol + ' ' + "Total: " + rjust(total, (b_width >= 20 ? 16 : 8)); + } else { + // Bottom graph + out += Mv::to(b_y + b_height - (b_height / 2), b_x + 1) + Fx::ub + Theme::c("main_fg") + symbol + ' ' + ljust(speed, 10) + (b_width >= 20 ? rjust('(' + speed_bits + ')', 13) : ""); + if (b_height >= 8) + out += Mv::to(b_y + b_height - (b_height / 2) + 1, b_x + 1) + symbol + ' ' + "Top: " + rjust('(' + top, (b_width >= 20 ? 17 : 9)) + ')'; + if (b_height >= 6) + out += Mv::to(b_y + b_height - (b_height / 2) + 1 + (b_height >= 8), b_x + 1) + symbol + ' ' + "Total: " + rjust(total, (b_width >= 20 ? 16 : 8)); + } + } + + redraw = false; + return out + Fx::reset; + } + +} + +namespace Proc { + int width_p = 55, height_p = 68; + int min_width = 44, min_height = 16; + int x, y, width = 20, height; + int start, selected, select_max; + bool shown = true, redraw = true; + bool is_last_process_in_list = false; + int selected_pid = 0, selected_depth = 0; + int scroll_pos; + string selected_name; + std::unordered_map p_graphs; + std::unordered_map p_wide_cmd; + std::unordered_map p_counters; + int counter = 0; + Draw::TextEdit filter; + Draw::Graph detailed_cpu_graph; + Draw::Graph detailed_mem_graph; + int user_size, thread_size, prog_size, cmd_size, tree_size; + int dgraph_x, dgraph_width, d_width, d_x, d_y; + bool previous_proc_banner_state = false; + atomic resized (false); + + string box; + + int selection(const std::string_view cmd_key) { + auto start = Config::getI("proc_start"); + auto selected = Config::getI("proc_selected"); + auto last_selected = Config::getI("proc_last_selected"); + bool changed = false; + int select_max = (Config::getB("show_detailed") ? (Config::getB("proc_banner_shown") ? Proc::select_max - 9 : Proc::select_max - 8) : + (Config::getB("proc_banner_shown") ? Proc::select_max - 1 : Proc::select_max)); + + // Return the selection from the detailed view to the followed process before moving the selection + // Disengage following mode when moving the selection unless paused + if (Config::getB("follow_process")) { + if (Config::getB("show_detailed") and selected == 0 and Config::getB("should_selection_return_to_followed") + and Config::getI("detailed_pid") == Config::getI("followed_pid")) { + selected = Config::getI("proc_followed"); + Config::set("should_selection_return_to_followed", false); + changed = true; + } + if (not Config::getB("pause_proc_list")) { + Config::flip("follow_process"); + Config::set("followed_pid", 0); + Config::set("proc_followed", 0); + select_max++; + } + redraw = true; + } + + auto vim_keys = Config::getB("vim_keys"); + + int numpids = Proc::numpids; + if ((cmd_key == "up" or (vim_keys and cmd_key == "k")) and selected > 0) { + if (start > 0 and selected == 1) start--; + else selected--; + if (Config::getI("proc_last_selected") > 0) Config::set("proc_last_selected", 0); + } + else if (cmd_key == "mouse_scroll_up" and start > 0) { + start = max(0, start - 3); + } + else if (cmd_key == "mouse_scroll_down" and start < numpids - select_max) { + start = min(numpids - select_max, start + 3); + } + else if (cmd_key == "down" or (vim_keys and cmd_key == "j")) { + if (start < numpids - select_max and selected == select_max) start++; + else if (selected == 0 and last_selected > 0) { + selected = last_selected; + Config::set("proc_last_selected", 0); + } + else selected++; + } + else if (cmd_key == "page_up") { + if (selected > 0 and start == 0) selected = 0; + else start = max(0, start - select_max); + } + else if (cmd_key == "page_down") { + if (selected > 0 and start >= numpids - select_max) selected = select_max; + else start = clamp(start + select_max, 0, max(0, numpids - select_max)); + } + else if (cmd_key == "home" or (vim_keys and cmd_key == "g")) { + start = 0; + if (selected > 0) selected = 1; + } + else if (cmd_key == "end" or (vim_keys and cmd_key == "G")) { + start = max(0, numpids - select_max); + if (selected > 0) selected = select_max; + } + else if (cmd_key.starts_with("mousey")) { + int mouse_y = std::atoi(cmd_key.substr(6).data()); + start = clamp((int)round((double)mouse_y * (numpids - select_max - 2) / (select_max - 2)), 0, max(0, numpids - select_max)); + } + + if (start != Config::getI("proc_start")) { + Config::set("proc_start", start); + changed = true; + } + if (selected != Config::getI("proc_selected")) { + Config::set("proc_selected", selected); + changed = true; + } + return (not changed ? -1 : selected); + } + + string draw(const vector& plist, bool force_redraw, bool data_same) { + if (Runner::stopping) return ""; + auto proc_tree = Config::getB("proc_tree"); + bool show_detailed = (Config::getB("show_detailed") and cmp_equal(Proc::detailed.last_pid, Config::getI("detailed_pid"))); + bool proc_gradient = (Config::getB("proc_gradient") and not Config::getB("lowcolor") and Theme::gradients.contains("proc")); + auto proc_colors = Config::getB("proc_colors"); + auto tty_mode = Config::getB("tty_mode"); + auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_proc")); + auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6); + auto mem_bytes = Config::getB("proc_mem_bytes"); + auto vim_keys = Config::getB("vim_keys"); + auto show_graphs = Config::getB("proc_cpu_graphs"); + const auto pause_proc_list = Config::getB("pause_proc_list"); + auto follow_process = Config::getB("follow_process"); + int followed_pid = Config::getI("followed_pid"); + int followed = Config::getI("proc_followed"); + bool should_selection_return_to_followed = Config::getB("should_selection_return_to_followed"); + auto proc_banner_shown = pause_proc_list or follow_process; + Config::set("proc_banner_shown", proc_banner_shown); + start = Config::getI("proc_start"); + selected = Config::getI("proc_selected"); + const int y = show_detailed ? Proc::y + 8 : Proc::y; + const int height = show_detailed ? Proc::height - 8 : Proc::height; + int select_max = show_detailed ? (proc_banner_shown ? Proc::select_max - 9 : Proc::select_max - 8) : + (proc_banner_shown ? Proc::select_max - 1 : Proc::select_max); + auto totalMem = Mem::get_totalMem(); + int numpids = Proc::numpids; + if (force_redraw) redraw = true; + string out; + out.reserve(width * height); + + //? Move current selection/view to the selected process when a process should be followed + //? Restore view and selection to the detailed view process when detailed view is closed + const int restore_detailed_pid = Config::getI("restore_detailed_pid"); + if ((follow_process and (not pause_proc_list or Config::getB("update_following"))) or restore_detailed_pid > 0) { + Config::set("update_following", false); + int loc = 1; + bool can_follow = false; + for (auto& p : plist) { + if (p.filtered or (proc_tree and p.tree_index == plist.size())) continue; + if (p.pid == (size_t)(restore_detailed_pid > 0 ? restore_detailed_pid : followed_pid)) { + can_follow = true; + break; + } + loc++; + } + + if (can_follow) { + const int list_middle = select_max % 2 == 0 ? select_max / 2 : select_max / 2 + 1; + start = max(0, loc - list_middle); + followed = loc < list_middle ? loc : start > numpids - select_max ? select_max - numpids + loc : list_middle; + if (restore_detailed_pid == 0) { + Config::set("proc_followed", followed); + Config::set("should_selection_return_to_followed", should_selection_return_to_followed = true); + } + selected = (followed_pid != Config::getI("detailed_pid") or restore_detailed_pid > 0) ? followed : 0; + } + else if (restore_detailed_pid == 0) { + Config::set("followed_pid", followed_pid = 0); + Config::set("follow_process", follow_process = false); + Config::set("proc_banner_shown", proc_banner_shown = pause_proc_list); + Config::set("proc_followed", 0); + if (not proc_banner_shown) select_max++; + } + if (restore_detailed_pid > 0) Config::set("restore_detailed_pid", 0); + } + + //? Handle selection edge cases when list view is showing bottom of list + //? for Pause and Following modes + const bool proc_banner_changed = proc_banner_shown != previous_proc_banner_state; + previous_proc_banner_state = proc_banner_shown; + if (proc_banner_changed and not proc_banner_shown + and start + select_max - 1 == numpids) + selected++; + else if (pause_proc_list and selected > select_max) + start++; + + //? redraw if selection reaches or leaves the end of the list + if (selected != Config::getI("proc_last_selected")) { + if (selected >= select_max and start >= numpids - select_max) { + redraw = true; + is_last_process_in_list = true; + } + else if (is_last_process_in_list) { + redraw = true; + is_last_process_in_list = false; + } + } + + //* Redraw elements not needed to be updated every cycle + if (redraw) { + out = box; + const string title_left = Theme::c("proc_box") + Symbols::title_left; + const string title_right = Theme::c("proc_box") + Symbols::title_right; + const string title_left_down = Theme::c("proc_box") + Symbols::title_left_down; + const string title_right_down = Theme::c("proc_box") + Symbols::title_right_down; + for (const auto& key : {"t", "K", "k", "s", "N", "F", "enter", "info_enter"}) + if (Input::mouse_mappings.contains(key)) Input::mouse_mappings.erase(key); + + //? Adapt sizes of text fields + user_size = (width < 75 ? 5 : 10); + thread_size = (width < 75 ? - 1 : 4); + prog_size = (width > 70 ? 16 : ( width > 55 ? 8 : width - user_size - thread_size - 33)); + cmd_size = (width > 55 ? width - prog_size - user_size - thread_size - 33 : -1); + tree_size = width - user_size - thread_size - 23; + if (not show_graphs) { + cmd_size += 5; + tree_size += 5; + } + + //? Detailed box + if (show_detailed) { + bool alive = detailed.status != "Dead"; + dgraph_x = x; + dgraph_width = max(width / 3, width - 121); + d_width = width - dgraph_width - 1; + d_x = x + dgraph_width + 1; + d_y = Proc::y; + + //? Create cpu and mem graphs if process is alive + if (alive or pause_proc_list) { + detailed_cpu_graph = Draw::Graph{dgraph_width - 1, 7, "cpu", detailed.cpu_percent, graph_symbol, false, true}; + detailed_mem_graph = Draw::Graph{d_width / 3, 1, "", detailed.mem_bytes, graph_symbol, false, false, detailed.first_mem}; + } + + //? Draw structure of details box + const string pid_str = to_string(detailed.entry.pid); + out += Mv::to(y, x) + Theme::c("proc_box") + Symbols::div_left + Symbols::h_line + title_left + Theme::c("hi_fg") + Fx::b + + (tty_mode ? "4" : Symbols::superscript.at(4)) + Theme::c("title") + "proc" + + Fx::ub + title_right + Symbols::h_line * (width - 10) + Symbols::div_right + + Mv::to(d_y, dgraph_x + 2) + title_left + Fx::b + Theme::c("title") + pid_str + Fx::ub + title_right + + title_left + Fx::b + Theme::c("title") + uresize(detailed.entry.name, dgraph_width - pid_str.size() - 7, true) + Fx::ub + title_right; + + out += Mv::to(d_y, d_x - 1) + Theme::c("proc_box") + Symbols::div_up + Mv::to(y, d_x - 1) + Symbols::div_down + Theme::c("div_line"); + for (const int& i : iota(1, 8)) out += Mv::to(d_y + i, d_x - 1) + Symbols::v_line; + + const string t_color = (not alive or selected > 0 ? Theme::c("inactive_fg") : Theme::c("title")); + const string hi_color = (not alive or selected > 0 ? t_color : Theme::c("hi_fg")); + int mouse_x = d_x + 2; + out += Mv::to(d_y, d_x + 1); + if (width > 55) { + out += Fx::ub + title_left + hi_color + Fx::b + 't' + t_color + "erminate" + Fx::ub + title_right; + if (alive and selected == 0) Input::mouse_mappings["t"] = {d_y, mouse_x, 1, 9}; + mouse_x += 11; + } + out += title_left + hi_color + Fx::b + (vim_keys ? 'K' : 'k') + t_color + "ill" + Fx::ub + title_right + + title_left + hi_color + Fx::b + 's' + t_color + "ignals" + Fx::ub + title_right + + title_left + hi_color + Fx::b + 'N' + t_color + "ice" + Fx::ub + title_right; + if (alive and selected == 0) { + Input::mouse_mappings[vim_keys ? "K" : "k"] = {d_y, mouse_x, 1, 4}; + mouse_x += 6; + Input::mouse_mappings["s"] = {d_y, mouse_x, 1, 7}; + mouse_x += 9; + Input::mouse_mappings["N"] = {d_y, mouse_x, 1, 5}; + mouse_x += 7; + } + if (width > 77) { + fmt::format_to(std::back_inserter(out), "{}{}{}{}{}{}{}{}", + title_left, follow_process ? Fx::b : "", + hi_color, 'F', t_color, "ollow", + Fx::ub, title_right); + if (selected == 0) Input::mouse_mappings["F"] = {d_y, mouse_x, 1, 6}; + } + + //? Labels + const int item_fit = floor((double)(d_width - 2) / 10); + const int item_width = floor((double)(d_width - 2) / min(item_fit, 8)); + out += Mv::to(d_y + 1, d_x + 1) + Fx::b + Theme::c("title") + + cjust("Status:", item_width) + + cjust("Elapsed:", item_width); + if (item_fit >= 3) out += cjust("IO/R:", item_width); + if (item_fit >= 4) out += cjust("IO/W:", item_width); + if (item_fit >= 5) out += cjust("Parent:", item_width); + if (item_fit >= 6) out += cjust("User:", item_width); + if (item_fit >= 7) out += cjust("Threads:", item_width); + if (item_fit >= 8) out += cjust("Nice:", item_width); + + + //? Command line + for (int i = 0; const auto& l : {'C', 'M', 'D'}) + out += Mv::to(d_y + 5 + i++, d_x + 1) + l; + + out += Theme::c("main_fg") + Fx::ub; + const auto san_cmd = replace_ascii_control(detailed.entry.cmd); + const int cmd_size = ulen(san_cmd, true); + for (int num_lines = min(3, (int)ceil((double)cmd_size / (d_width - 5))), i = 0; i < num_lines; i++) { + out += Mv::to(d_y + 5 + (num_lines == 1 ? 1 : i), d_x + 3) + + cjust(luresize(san_cmd, cmd_size - (d_width - 5) * i, true), d_width - 5, true, true); + } + + } + + //? Filter + auto filtering = Config::getB("proc_filtering"); // ? filter(20) : Config::getS("proc_filter")) + const auto filter_text = (filtering) ? filter(max(6, width - 66)) : uresize(Config::getS("proc_filter"), max(6, width - 66)); + out += Mv::to(y, x+9) + title_left + (not filter_text.empty() ? Fx::b : "") + Theme::c("hi_fg") + 'f' + + Theme::c("title") + (not filter_text.empty() ? ' ' + filter_text : "ilter") + + (not filtering and not filter_text.empty() ? Theme::c("hi_fg") + " del" : "") + + (filtering ? Theme::c("hi_fg") + ' ' + Symbols::enter : "") + Fx::ub + title_right; + if (not filtering) { + int f_len = (filter_text.empty() ? 6 : ulen(filter_text) + 2); + Input::mouse_mappings["f"] = {y, x + 10, 1, f_len}; + if (filter_text.empty() and Input::mouse_mappings.contains("delete")) + Input::mouse_mappings.erase("delete"); + else if (not filter_text.empty()) + Input::mouse_mappings["delete"] = {y, x + 11 + f_len, 1, 3}; + } + + //? pause, per-core, reverse, tree and sorting + const auto& sorting = Config::getS("proc_sorting"); + const int sort_len = sorting.size(); + const int sort_pos = x + width - sort_len - 8; + + if (width > 60 + sort_len) { + fmt::format_to(std::back_inserter(out), "{}{}{}{}{}{}{}{}{}{}{}", + Mv::to(y, sort_pos - 32), title_left, pause_proc_list ? Fx::b : "", + Theme::c("title"), "pa", Theme::c("hi_fg"), 'u', Theme::c("title"), "se", + Fx::ub, title_right); + Input::mouse_mappings["u"] = {y, sort_pos - 31, 1, 5}; + } + if (width > 55 + sort_len) { + out += Mv::to(y, sort_pos - 25) + title_left + (Config::getB("proc_per_core") ? Fx::b : "") + Theme::c("title") + + "per-" + Theme::c("hi_fg") + 'c' + Theme::c("title") + "ore" + Fx::ub + title_right; + Input::mouse_mappings["c"] = {y, sort_pos - 24, 1, 8}; + } + if (width > 45 + sort_len) { + out += Mv::to(y, sort_pos - 15) + title_left + (Config::getB("proc_reversed") ? Fx::b : "") + Theme::c("hi_fg") + + 'r' + Theme::c("title") + "everse" + Fx::ub + title_right; + Input::mouse_mappings["r"] = {y, sort_pos - 14, 1, 7}; + } + if (width > 35 + sort_len) { + out += Mv::to(y, sort_pos - 6) + title_left + (Config::getB("proc_tree") ? Fx::b : "") + Theme::c("title") + "tre" + + Theme::c("hi_fg") + 'e' + Fx::ub + title_right; + Input::mouse_mappings["e"] = {y, sort_pos - 5, 1, 4}; + } + out += Mv::to(y, sort_pos) + title_left + Fx::b + Theme::c("hi_fg") + Symbols::left + " " + Theme::c("title") + sorting + " " + Theme::c("hi_fg") + + Symbols::right + Fx::ub + title_right; + Input::mouse_mappings["left"] = {y, sort_pos + 1, 1, 2}; + Input::mouse_mappings["right"] = {y, sort_pos + sort_len + 3, 1, 2}; + + //? select, info, signal, and follow buttons + const string down_button = (is_last_process_in_list ? Theme::c("inactive_fg") : Theme::c("hi_fg")) + Symbols::down; + const bool is_up_button_highlighted = selected != 0 or (follow_process and followed_pid == Config::getI("detailed_pid") and should_selection_return_to_followed); + const string up_button = (is_up_button_highlighted ? Theme::c("hi_fg") : Theme::c("inactive_fg")) + Symbols::up; + const string t_color = (selected == 0 ? Theme::c("inactive_fg") : Theme::c("title")); + const string hi_color = (selected == 0 ? Theme::c("inactive_fg") : Theme::c("hi_fg")); + int mouse_x = x + 14; + out += Mv::to(y + height - 1, x + 1) + title_left_down + Fx::b + hi_color + up_button + Theme::c("title") + " select " + down_button + Fx::ub + title_right_down + + title_left_down + Fx::b + t_color + "info " + hi_color + Symbols::enter + Fx::ub + title_right_down; + if (selected > 0) Input::mouse_mappings["info_enter"] = {y + height - 1, mouse_x, 1, 6}; + mouse_x += 8; + if (width > 60) { + out += title_left_down + Fx::b + hi_color + 't' + t_color + "erminate" + Fx::ub + title_right_down; + if (selected > 0) Input::mouse_mappings["t"] = {y + height - 1, mouse_x, 1, 9}; + mouse_x += 11; + } + if (width > 55) { + out += title_left_down + Fx::b + hi_color + (vim_keys ? 'K' : 'k') + t_color + "ill" + Fx::ub + title_right_down; + if (selected > 0) Input::mouse_mappings[vim_keys ? "K" : "k"] = {y + height - 1, mouse_x, 1, 4}; + mouse_x += 6; + } + out += title_left_down + Fx::b + hi_color + 's' + t_color + "ignals" + Fx::ub + title_right_down; + if (selected > 0) Input::mouse_mappings["s"] = {y + height - 1, mouse_x, 1, 7}; + mouse_x += 9; + out += title_left_down + Fx::b + hi_color + 'N' + t_color + "ice" + Fx::ub + title_right_down; + if (selected > 0) Input::mouse_mappings["N"] = {y + height -1, mouse_x, 1, 5}; + mouse_x += 6; + if (width > 72) { + fmt::format_to(std::back_inserter(out), "{}{}{}{}{}{}{}{}", + title_left_down, follow_process ? Fx::b : "", + hi_color, 'F', t_color, "ollow", + Fx::ub, title_right_down); + if (selected > 0) Input::mouse_mappings["F"] = {y + height - 1, mouse_x, 1, 6}; + } + + //? Labels for fields in list + if (not proc_tree) + out += Mv::to(y+1, x+1) + Theme::c("title") + Fx::b + + rjust("Pid:", 8) + ' ' + + ljust("Program:", prog_size) + ' ' + + (cmd_size > 0 ? ljust("Command:", cmd_size) : "") + ' '; + else + out += Mv::to(y+1, x+1) + Theme::c("title") + Fx::b + + ljust("Tree:", tree_size) + ' '; + + out += (thread_size > 0 ? Mv::l(4) + "Threads: " : "") + + ljust("User:", user_size) + ' ' + + rjust((mem_bytes ? "MemB" : "Mem%"), 5) + ' ' + + rjust("Cpu%", (show_graphs ? 10 : 5)) + Fx::ub; + } + //* End of redraw block + + //? Draw details box if shown + if (show_detailed) { + bool alive = detailed.status != "Dead"; + const int item_fit = floor((double)(d_width - 2) / 10); + const int item_width = floor((double)(d_width - 2) / min(item_fit, 8)); + + //? Graph part of box + fmt::format_to(std::back_inserter(out), "{move}{unbold}{graph}{move}{fg_color}{bold}{cpu_str}%", + "move"_a = Mv::to(d_y + 1, dgraph_x + 1), "bold"_a = Fx::b, "unbold"_a = Fx::ub, "fg_color"_a = Theme::c("title"), + "graph"_a = detailed_cpu_graph(detailed.cpu_percent, (redraw or data_same or not alive)), + "cpu_str"_a = (alive or pause_proc_list) ? fmt::format("{:>4.{}f}", detailed.entry.cpu_p, detailed.entry.cpu_p < 9.995f ? 2 : detailed.entry.cpu_p < 99.95f ? 1 : 0) : ""); + for (int i = 0; const auto& l : {'C', 'P', 'U'}) + fmt::format_to(std::back_inserter(out), "{}{}", Mv::to(d_y + 3 + i++, dgraph_x + 1), l); + + //? Info part of box + const string stat_color = (not alive ? Theme::c("inactive_fg") : (detailed.status == "Running" ? Theme::c("proc_misc") : Theme::c("main_fg"))); + out += Mv::to(d_y + 2, d_x + 1) + stat_color + Fx::ub + + cjust(detailed.status, item_width) + Theme::c("main_fg") + + cjust(detailed.elapsed, item_width); + if (item_fit >= 3) out += cjust(detailed.io_read, item_width); + if (item_fit >= 4) out += cjust(detailed.io_write, item_width); + if (item_fit >= 5) out += cjust(detailed.parent, item_width, true); + if (item_fit >= 6) out += cjust(detailed.entry.user, item_width, true); + if (item_fit >= 7) out += cjust(to_string(detailed.entry.threads), item_width); + if (item_fit >= 8) out += cjust(to_string(detailed.entry.p_nice), item_width); + + + const double mem_p = detailed.mem_bytes.back() * 100.0 / totalMem; + string mem_str = fmt::format("{:.2f}", mem_p); + mem_str.resize(4); + if (mem_str.ends_with('.')) mem_str.pop_back(); + out += Mv::to(d_y + 4, d_x + 1) + Theme::c("title") + Fx::b + rjust((item_fit > 4 ? "Memory: " : "M:") + rjust(mem_str, 4) + "% ", (d_width / 3) - 2) + + Theme::c("inactive_fg") + Fx::ub + graph_bg * (d_width / 3) + Mv::l(d_width / 3) + + Theme::c("proc_misc") + detailed_mem_graph(detailed.mem_bytes, (redraw or data_same or not alive)) + ' ' + + Theme::c("title") + Fx::b + detailed.memory; + } + + //? Check bounds of current selection and view + if (start > 0 and numpids <= select_max) + start = 0; + if (start > numpids - select_max) + start = max(0, numpids - select_max); + if (selected > select_max) + selected = select_max; + if (selected > numpids) + selected = numpids; + + //* Iteration over processes + int lc = 0; + for (int n=0; auto& p : plist) { + if (p.filtered or (proc_tree and p.tree_index == plist.size()) or n++ < start) continue; + bool is_selected = (lc + 1 == selected); + bool is_followed = followed_pid == (int)p.pid; + if (is_selected) { + selected_pid = (int)p.pid; + selected_name = p.name; + selected_depth = p.depth; + } + + //? Update graphs for processes with above 0.0% cpu usage, delete if below 0.1% 10x times + bool has_graph = show_graphs ? p_counters.contains(p.pid) : false; + if (show_graphs and ((p.cpu_p > 0 and not has_graph) or (not data_same and has_graph))) { + if (not has_graph) { + p_graphs[p.pid] = Draw::Graph{5, 1, "", {}, graph_symbol}; + p_counters[p.pid] = 0; + } + else if (p.cpu_p < 0.1 and ++p_counters[p.pid] >= 10) { + if (p_graphs.contains(p.pid)) p_graphs.erase(p.pid); + p_counters.erase(p.pid); + } + else + p_counters[p.pid] = 0; + } + + out += Fx::reset; + + //? Set correct gradient colors if enabled + string c_color, m_color, t_color, g_color, end; + if (is_selected or is_followed) { + c_color = m_color = t_color = g_color = Fx::b; + end = Fx::ub; + const string highlight = is_followed ? Theme::c("followed_bg") + Theme::c("followed_fg") : Theme::c("selected_bg") + Theme::c("selected_fg"); + fmt::format_to(std::back_inserter(out), "{}{}", highlight, Fx::b); + } + else { + int calc = (selected > lc) ? selected - lc : lc - selected; + if (proc_colors) { + end = Theme::c("main_fg") + Fx::ub; + array colors; + for (int i = 0; int v : {(int)round(p.cpu_p), (int)round(p.mem * 100 / totalMem), (int)p.threads / 3}) { + if (proc_gradient) { + int val = (min(v, 100) + 100) - calc * 100 / select_max; + if (val < 100) colors[i++] = Theme::g("proc_color").at(max(0, val)); + else colors[i++] = Theme::g("process").at(clamp(val - 100, 0, 100)); + } + else + colors[i++] = Theme::g("process").at(clamp(v, 0, 100)); + } + c_color = colors.at(0); m_color = colors.at(1); t_color = colors.at(2); + } + else { + c_color = m_color = t_color = Fx::b; + end = Fx::ub; + } + if (proc_gradient) { + g_color = Theme::g("proc").at(clamp(calc * 100 / select_max, 0, 100)); + } + } + + const auto san_cmd = replace_ascii_control(p.cmd); + + if (not p_wide_cmd.contains(p.pid)) p_wide_cmd[p.pid] = ulen(san_cmd) != ulen(san_cmd, true); + + //? Normal view line + if (not proc_tree) { + out += Mv::to(y+2+lc, x+1) + + g_color + rjust(to_string(p.pid), 8) + ' ' + + c_color + ljust(p.name, prog_size, true) + ' ' + end + + (cmd_size > 0 ? g_color + ljust(san_cmd, cmd_size, true, p_wide_cmd[p.pid]) + Mv::to(y+2+lc, x+11+prog_size+cmd_size) + ' ' : ""); + } + //? Tree view line + else { + const string prefix_pid = p.prefix + to_string(p.pid); + int width_left = tree_size; + out += Mv::to(y+2+lc, x+1) + g_color + uresize(prefix_pid, width_left) + ' '; + width_left -= ulen(prefix_pid); + if (width_left > 0) { + out += c_color + uresize(p.name, width_left - 1) + end + ' '; + width_left -= (ulen(p.name) + 1); + } + if (width_left > 7) { + const string_view cmd = width_left > 40 ? rtrim(san_cmd) : p.short_cmd; + if (not cmd.empty() and cmd != p.name) { + out += g_color + '(' + uresize(string{cmd}, width_left - 3, p_wide_cmd[p.pid]) + ") "; + width_left -= (ulen(string{cmd}, true) + 3); + } + } + out += string(max(0, width_left), ' ') + Mv::to(y+2+lc, x+2+tree_size); + } + //? Common end of line + string cpu_str = fmt::format("{:.2f}", p.cpu_p); + if (p.cpu_p < 10 or (p.cpu_p >= 100 and p.cpu_p < 1000)) cpu_str.resize(3); + else if (p.cpu_p >= 10'000) { + cpu_str = fmt::format("{:.2f}", p.cpu_p / 1000); + cpu_str.resize(3); + if (cpu_str.ends_with('.')) cpu_str.pop_back(); + cpu_str += "k"; + } + string mem_str = (mem_bytes ? floating_humanizer(p.mem, true) : ""); + if (not mem_bytes) { + double mem_p = clamp((double)p.mem * 100 / totalMem, 0.0, 100.0); + mem_str = mem_p < 0.01 ? "0" : fmt::format("{:.1f}", mem_p); + if (mem_str.size() > 3) mem_str.resize(3); + if (mem_str.ends_with('.')) mem_str.pop_back(); + mem_str += '%'; + } + + // Shorten process thread representation when larger than 5 digits: 10000 -> 10K ... + const std::string proc_threads_string = [&] { + if (p.threads > 9999) { + return std::to_string(p.threads / 1000) + 'K'; + } else { + return std::to_string(p.threads); + } + }(); + + out += (thread_size > 0 ? t_color + rjust(proc_threads_string, thread_size) + ' ' + end : "" ) + + g_color + ljust((cmp_greater(p.user.size(), user_size) ? p.user.substr(0, user_size - 1) + '+' : p.user), user_size) + ' ' + + m_color + rjust(mem_str, 5) + end + ' ' + + (is_selected or is_followed ? "" : Theme::c("inactive_fg")) + (show_graphs ? graph_bg * 5: "") + + (p_graphs.contains(p.pid) ? Mv::l(5) + c_color + p_graphs.at(p.pid)({(p.cpu_p >= 0.1 and p.cpu_p < 5 ? 5ll : (long long)round(p.cpu_p))}, data_same) : "") + end + ' ' + + c_color + rjust(cpu_str, 4) + " " + end; + if (lc++ > height - 5) break; + else if (lc > height - 5 and proc_banner_shown) break; + } + + out += Fx::reset; + while (lc++ < height - 3) out += Mv::to(y+lc+1, x+1) + string(width - 2, ' '); + if (proc_banner_shown) { + fmt::format_to(std::back_inserter(out), "{}{}{}{}{:^{}}{}", + Mv::to(y + height - 2, x + 1), + (pause_proc_list and follow_process) ? Theme::c("proc_banner_bg") + : pause_proc_list ? Theme::c("proc_pause_bg") + : Theme::c("proc_follow_bg"), + Theme::c("proc_banner_fg"), Fx::b, + (pause_proc_list and follow_process) ? "Paused list and Following process" + : pause_proc_list ? "Process list paused" + : "Following process", width - 2, + Fx::reset); + } + + //? Draw scrollbar if needed + if (numpids > select_max) { + scroll_pos = clamp((int)round((double)start * select_max / (numpids - select_max)), 0, height - 5); + out += Mv::to(y + 1, x + width - 2) + Fx::b + Theme::c("main_fg") + Symbols::up + + Mv::to(y + height - 2, x + width - 2) + Symbols::down; + + for (int i = y + 2; i < y + height - 2; i++) { + out += Mv::to(i, x + width - 2) + ((i == y + 2 + scroll_pos) ? "█" : " "); + } + } + + //? Current selection and number of processes + string location = to_string(start + (follow_process ? followed : selected)) + '/' + to_string(numpids); + string loc_clear = Symbols::h_line * max((size_t)0, 9 - location.size()); + out += Mv::to(y + height - 1, x+width - 3 - max(9, (int)location.size())) + Fx::ub + Theme::c("proc_box") + loc_clear + + Symbols::title_left_down + Theme::c("title") + Fx::b + location + Fx::ub + Theme::c("proc_box") + Symbols::title_right_down; + + //? Clear out left over graphs from dead processes at a regular interval + if (not data_same and ++counter >= 100) { + counter = 0; + + std::erase_if(p_graphs, [&](const auto& pair) { + return rng::find(plist, pair.first, &proc_info::pid) == plist.end(); + }); + + std::erase_if(p_counters, [&](const auto& pair) { + return rng::find(plist, pair.first, &proc_info::pid) == plist.end(); + }); + + std::erase_if(p_wide_cmd, [&](const auto& pair) { + return rng::find(plist, pair.first, &proc_info::pid) == plist.end(); + }); + } + + //? Draw hide button if detailed view is shown + if (show_detailed) { + const bool greyed_out = selected_pid != Config::getI("detailed_pid") && selected > 0; + fmt::format_to(std::back_inserter(out), "{}{}{}{}{}{}{}{}{}{}{}", + Mv::to(d_y, d_x + d_width - 10), + Theme::c("proc_box"), Symbols::title_left, Fx::b, + greyed_out ? Theme::c("inactive_fg") : Theme::c("title"), "hide ", + greyed_out ? "" : Theme::c("hi_fg"), Symbols::enter, + Fx::ub, Theme::c("proc_box"), Symbols::title_right); + if (not greyed_out) Input::mouse_mappings["enter"] = {d_y, d_x + d_width - 9, 1, 6}; + else Input::mouse_mappings.erase("enter"); + } + + if (selected == 0 and selected_pid != 0) { + selected_pid = 0; + selected_name.clear(); + } + redraw = false; + return out + Fx::reset; + } + +} + +namespace Draw { + void calcSizes() { + atomic_wait(Runner::active); + Config::unlock(); + auto boxes = Config::getS("shown_boxes"); + auto cpu_bottom = Config::getB("cpu_bottom"); + auto mem_below_net = Config::getB("mem_below_net"); + auto proc_left = Config::getB("proc_left"); + + Cpu::box.clear(); + + Mem::box.clear(); + Net::box.clear(); + Proc::box.clear(); + Global::clock.clear(); + Global::overlay.clear(); + Runner::pause_output = false; + Runner::redraw = true; + if (not (Proc::resized or Global::resized)) { + Proc::p_counters.clear(); + Proc::p_graphs.clear(); + } + if (Menu::active) Menu::redraw = true; + + Input::mouse_mappings.clear(); + + Cpu::x = Mem::x = Net::x = Proc::x = 1; + Cpu::y = Mem::y = Net::y = Proc::y = 1; + Cpu::width = Mem::width = Net::width = Proc::width = 0; + Cpu::height = Mem::height = Net::height = Proc::height = 0; + Cpu::redraw = Mem::redraw = Net::redraw = Proc::redraw = true; + + Cpu::shown = boxes.contains("cpu"); + #ifdef GPU_SUPPORT + Gpu::box.clear(); + Gpu::width = 0; + Gpu::shown_panels.clear(); + if (Gpu::count > 0) { + std::istringstream iss(boxes, std::istringstream::in); + string current; + while (iss >> current) { + if (current.starts_with("gpu")) + Gpu::shown_panels.push_back(current.back()-'0'); + } + } + Gpu::shown = Gpu::shown_panels.size(); + + // Calculate the minimum possible GPU height, store in total_height + // The actual total_height value will of course be overwritten later + Gpu::total_height = 0; + for (int i = 0; i < Gpu::shown; i++) { + using namespace Gpu; + total_height += 4 + gpu_b_height_offsets[shown_panels[i]]; + } + #endif + Mem::shown = boxes.contains("mem"); + Net::shown = boxes.contains("net"); + Proc::shown = boxes.contains("proc"); + + //* Calculate and draw cpu box outlines + if (Cpu::shown) { + using namespace Cpu; + #ifdef GPU_SUPPORT + // inline GPU information + int gpus_extra_height = + Config::getS("show_gpu_info") == "On" ? Gpu::count + : Config::getS("show_gpu_info") == "Auto" ? Gpu::count - Gpu::shown + : 0; + #endif + const bool show_temp = (Config::getB("check_temp") and got_sensors); + width = round((double)Term::width * width_p / 100); + #ifdef GPU_SUPPORT + if (Gpu::shown != 0 and not (Mem::shown or Net::shown or Proc::shown)) { + height = Term::height - Gpu::total_height - gpus_extra_height; + } else { + height = max(8, (int)ceil((double)Term::height * (trim(boxes) == "cpu" ? 100 : height_p/(Gpu::shown+1) + (Gpu::shown != 0)*5) / 100)); + } + if (height <= Term::height-gpus_extra_height) height += gpus_extra_height; + #else + height = max(8, (int)ceil((double)Term::height * (trim(boxes) == "cpu" ? 100 : height_p) / 100)); + #endif + x = 1; + y = cpu_bottom ? Term::height - height + 1 : 1; + + #ifdef GPU_SUPPORT + b_columns = max(2, (int)ceil((double)(Shared::coreCount + 1) / (height - gpus_extra_height - 5))); + #else + b_columns = max(1, (int)ceil((double)(Shared::coreCount + 1) / (height - 5))); + #endif + if (b_columns * (21 + 12 * show_temp) < width - (width / 3)) { + b_column_size = 2; + b_width = max(29, (21 + 12 * show_temp) * b_columns - (b_columns - 1)); + } + else if (b_columns * (15 + 6 * show_temp) < width - (width / 3)) { + b_column_size = 1; + b_width = (15 + 6 * show_temp) * b_columns - (b_columns - 1); + } + else if (b_columns * (8 + 6 * show_temp) < width - (width / 3)) { + b_column_size = 0; + } + else { + b_columns = (width - width / 3) / (8 + 6 * show_temp); + b_column_size = 0; + } + + if (b_column_size == 0) b_width = (8 + 6 * show_temp) * b_columns + 1; + #ifdef GPU_SUPPORT + //gpus_extra_height = max(0, gpus_extra_height - 1); + b_height = min(height - 2, (int)ceil((double)Shared::coreCount / b_columns) + 4 + gpus_extra_height); + #else + b_height = min(height - 2, (int)ceil((double)Shared::coreCount / b_columns) + 4); + #endif + + b_x = x + width - b_width - 1; + b_y = y + ceil((double)(height - 2) / 2) - ceil((double)b_height / 2) + 1; + + box = createBox(x, y, width, height, Theme::c("cpu_box"), true, (cpu_bottom ? "" : "cpu"), (cpu_bottom ? "cpu" : ""), 1); + + auto& custom = Config::getS("custom_cpu_name"); + static const bool hasCpuHz = not Cpu::get_cpuHz().empty(); + #ifdef __linux__ + static const bool freq_range = Config::getS("freq_mode") == "range"; + #else + static const bool freq_range = false; + #endif + const string cpu_title = uresize( + (custom.empty() ? Cpu::cpuName : custom), + b_width - (Config::getB("show_cpu_freq") and hasCpuHz ? (freq_range ? 24 : 14) : 5) + ); + box += createBox(b_x, b_y, b_width, b_height, "", false, cpu_title); + } + + #ifdef GPU_SUPPORT + //* Calculate and draw gpu box outlines + if (Gpu::shown != 0) { + using namespace Gpu; + x_vec.resize(shown); y_vec.resize(shown); + b_x_vec.resize(shown); b_y_vec.resize(shown); + b_height_vec.resize(shown); + box.resize(shown); + graph_upper_vec.resize(shown); graph_lower_vec.resize(shown); + temp_graph_vec.resize(shown); + mem_used_graph_vec.resize(shown); mem_util_graph_vec.resize(shown); + gpu_meter_vec.resize(shown); + pwr_meter_vec.resize(shown); + enc_meter_vec.resize(shown); + redraw.resize(shown); + total_height = 0; + for (auto i = 0; i < shown; ++i) { + redraw[i] = true; + int height = 0; + width = Term::width; + if (Cpu::shown) + if (not (Mem::shown or Net::shown or Proc::shown)) + height = min_height; + else height = Cpu::height; + else + if (not (Mem::shown or Net::shown or Proc::shown)) + height = (Term::height - total_height) / (Gpu::shown - i) + (i == 0) * ((Term::height - total_height) % (Gpu::shown - i)); + else + height = max(min_height, (int)ceil((double)Term::height * height_p/Gpu::shown / 100)); + + b_height_vec[i] = gpu_b_height_offsets[shown_panels[i]] + 2; + height += (height+Cpu::height == Term::height-1); + height = max(height, b_height_vec[i] + 2); + x_vec[i] = 1; y_vec[i] = 1 + total_height + (not Config::getB("cpu_bottom"))*Cpu::shown*Cpu::height; + box[i] = createBox(x_vec[i], y_vec[i], width, height, Theme::c("cpu_box"), true, std::string("gpu") + (char)(shown_panels[i]+'0'), "", (shown_panels[i]+5)%10); // TODO gpu_box + b_width = clamp(width/2, min_width, 65); + total_height += height; + + //? Main statistics box + b_x_vec[i] = x_vec[i] + width - b_width - 1; + b_y_vec[i] = y_vec[i] + ceil((double)(height - 2 - b_height_vec[i]) / 2) + 1; + + string name = Config::getS(std::string("custom_gpu_name") + (char)(shown_panels[i]+'0')); + if (name.empty()) name = gpu_names[shown_panels[i]]; + + box[i] += createBox(b_x_vec[i], b_y_vec[i], b_width, b_height_vec[i], "", false, name.substr(0, b_width-5)); + b_height_vec[i] = height - 2; + } + } + #endif + + //* Calculate and draw mem box outlines + if (Mem::shown) { + using namespace Mem; + auto show_disks = Config::getB("show_disks"); + auto swap_disk = Config::getB("swap_disk"); + auto mem_graphs = Config::getB("mem_graphs"); + + width = round((double)Term::width * (Proc::shown ? width_p : 100) / 100); + #ifdef GPU_SUPPORT + height = floor(static_cast(Term::height) * (100 - Net::height_p * Net::shown*4 / ((Gpu::shown != 0 and Cpu::shown) + 4)) / 100) - Cpu::height - Gpu::total_height; + #else + height = floor(static_cast(Term::height) * (100 - Cpu::height_p * Cpu::shown - Net::height_p * Net::shown) / 100); + #endif + x = (proc_left and Proc::shown) ? Term::width - width + 1: 1; + if (mem_below_net and Net::shown) + #ifdef GPU_SUPPORT + y = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0); + else + y = (cpu_bottom ? 1 : Cpu::height + 1) + Gpu::total_height; + #else + y = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0); + else + y = cpu_bottom ? 1 : Cpu::height + 1; + #endif + + if (show_disks) { + mem_width = ceil((double)(width - 3) / 2); + mem_width += mem_width % 2; + disks_width = width - mem_width - 2; + divider = x + mem_width; + } + else + mem_width = width - 1; + + item_height = has_swap and not swap_disk ? 6 : 4; + if (height - (has_swap and not swap_disk ? 3 : 2) > 2 * item_height) + mem_size = 3; + else if (mem_width > 25) + mem_size = 2; + else + mem_size = 1; + + mem_meter = max(0, mem_width - (mem_size > 2 ? 7 : 17)); + if (mem_size == 1) mem_meter += 6; + + if (mem_graphs) { + graph_height = max(1, (int)round((double)((height - (has_swap and not swap_disk ? 2 : 1)) - (mem_size == 3 ? 2 : 1) * item_height) / item_height)); + if (graph_height > 1) mem_meter += 6; + } + else + graph_height = 0; + + if (show_disks) { + disk_meter = max(-14, width - mem_width - 23); + if (disks_width < 25) disk_meter += 14; + } + + box = createBox(x, y, width, height, Theme::c("mem_box"), true, "mem", "", 2); + box += Mv::to(y, (show_disks ? divider + 2 : x + width - 9)) + Theme::c("mem_box") + Symbols::title_left + (show_disks ? Fx::b : "") + + Theme::c("hi_fg") + 'd' + Theme::c("title") + "isks" + Fx::ub + Theme::c("mem_box") + Symbols::title_right; + Input::mouse_mappings["d"] = {y, (show_disks ? divider + 3 : x + width - 8), 1, 5}; + if (show_disks) { + box += Mv::to(y, divider) + Symbols::div_up + Mv::to(y + height - 1, divider) + Symbols::div_down + Theme::c("div_line"); + for (auto i : iota(1, height - 1)) + box += Mv::to(y + i, divider) + Symbols::v_line; + } + } + + //* Calculate and draw net box outlines + if (Net::shown) { + using namespace Net; + width = round((double)Term::width * (Proc::shown ? width_p : 100) / 100); + #ifdef GPU_SUPPORT + height = Term::height - Cpu::height - Gpu::total_height - Mem::height; + #else + height = Term::height - Cpu::height - Mem::height; + #endif + x = (proc_left and Proc::shown) ? Term::width - width + 1 : 1; + if (mem_below_net and Mem::shown) + #ifdef GPU_SUPPORT + y = (cpu_bottom ? 1 : Cpu::height + 1) + Gpu::total_height; + #else + y = cpu_bottom ? 1 : Cpu::height + 1; + #endif + else + y = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0); + + b_width = (width > 45) ? 27 : 19; + b_height = (height > 10) ? 9 : height - 2; + b_x = x + width - b_width - 1; + b_y = y + ((height - 2) / 2) - b_height / 2 + 1; + d_graph_height = round((double)(height - 2) / 2); + u_graph_height = height - 2 - d_graph_height; + + box = createBox(x, y, width, height, Theme::c("net_box"), true, "net", "", 3); + auto swap_up_down = Config::getB("swap_upload_download"); + if (swap_up_down) + box += createBox(b_x, b_y, b_width, b_height, "", false, "upload", "download"); + else + box += createBox(b_x, b_y, b_width, b_height, "", false, "download", "upload"); + } + + //* Calculate and draw proc box outlines + if (Proc::shown) { + using namespace Proc; + width = Term::width - (Mem::shown ? Mem::width : (Net::shown ? Net::width : 0)); + #ifdef GPU_SUPPORT + height = Term::height - Cpu::height - Gpu::total_height; + #else + height = Term::height - Cpu::height; + #endif + x = proc_left ? 1 : Term::width - width + 1; + #ifdef GPU_SUPPORT + y = ((cpu_bottom and Cpu::shown) ? 1 : Cpu::height + 1) + Gpu::total_height; + #else + y = (cpu_bottom and Cpu::shown) ? 1 : Cpu::height + 1; + #endif + select_max = height - 3; + box = createBox(x, y, width, height, Theme::c("proc_box"), true, "proc", "", 4); + } + } +} diff --git a/vendor/btop/src/btop_draw.hpp b/vendor/btop/src/btop_draw.hpp new file mode 100644 index 000000000..c0468c79d --- /dev/null +++ b/vendor/btop/src/btop_draw.hpp @@ -0,0 +1,141 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + +using std::array; +using std::deque; +using std::string; +using std::vector; + +namespace Symbols { + extern const string h_line; + extern const string v_line; + extern const string dotted_v_line; + extern const string left_up; + extern const string right_up; + extern const string left_down; + extern const string right_down; + extern const string round_left_up; + extern const string round_right_up; + extern const string round_left_down; + extern const string round_right_down; + extern const string title_left_down; + extern const string title_right_down; + extern const string title_left; + extern const string title_right; + extern const string div_right; + extern const string div_left; + extern const string div_up; + extern const string div_down; + + + extern const string up; + extern const string down; + extern const string left; + extern const string right; + extern const string enter; +} + +namespace Draw { + + //* Generate if needed and return the btop++ banner + string banner_gen(int y=0, int x=0, bool centered=false, bool redraw=false); + + //* An editable text field + class TextEdit { + size_t pos{}; + size_t upos{}; + bool numeric = false; + public: + string text; + TextEdit(); + explicit TextEdit(string text, bool numeric=false); + bool command(const std::string_view key); + string operator()(const size_t limit=0); + void clear(); + }; + + //* Create a box and return as a string + string createBox( + const int x, const int y, const int width, const int height, string line_color = "", bool fill = false, + const std::string_view title = "", const std::string_view title2 = "", const int num = 0 + ); + + bool update_clock(bool force = false); + + //* Class holding a percentage meter + class Meter { + int width; + string color_gradient; + bool invert; + array cache; + public: + Meter(); + Meter(const int width, string color_gradient, bool invert = false); + + //* Return a string representation of the meter with given value + string operator()(int value); + }; + + //* Class holding a percentage graph + class Graph { + int width, height; + string color_gradient; + string out, symbol = "default"; + bool invert, no_zero; + long long offset; + long long last = 0, max_value = 0; + bool current = true, tty_mode = false; + std::unordered_map> graphs = { {true, {}}, {false, {}}}; + + //* Create two representations of the graph to switch between to represent two values for each braille character + void _create(const deque& data, int data_offset); + + public: + Graph(); + Graph(int width, int height, + const string& color_gradient, + const deque& data, + const string& symbol="default", + bool invert=false, bool no_zero=false, + long long max_value=0, long long offset=0); + + //* Add last value from back of and return string representation of graph + string& operator()(const deque& data, bool data_same=false); + + //* Return string representation of graph + string& operator()(); + }; + + //* Calculate sizes of boxes, draw outlines and save to enabled boxes namespaces + void calcSizes(); +} + +namespace Proc { + extern Draw::TextEdit filter; + extern std::unordered_map p_graphs; + extern std::unordered_map p_counters; +} diff --git a/vendor/btop/src/btop_input.cpp b/vendor/btop/src/btop_input.cpp new file mode 100644 index 000000000..4c77b718a --- /dev/null +++ b/vendor/btop/src/btop_input.cpp @@ -0,0 +1,648 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "btop_input.hpp" +#include "btop_tools.hpp" +#include "btop_config.hpp" +#include "btop_shared.hpp" +#include "btop_menu.hpp" +#include "btop_draw.hpp" + +using namespace Tools; +using namespace std::literals; // for operator""s +namespace rng = std::ranges; + +namespace Input { + + //* Map for translating key codes to readable values + const std::unordered_map Key_escapes = { + {"\033", "escape"}, + {"\x12", "ctrl_r"}, + {"\n", "enter"}, + {" ", "space"}, + {"\x7f", "backspace"}, + {"\x08", "backspace"}, + {"[A", "up"}, + {"OA", "up"}, + {"[B", "down"}, + {"OB", "down"}, + {"[D", "left"}, + {"OD", "left"}, + {"[C", "right"}, + {"OC", "right"}, + {"[2~", "insert"}, + {"[4h", "insert"}, + {"[3~", "delete"}, + {"[P", "delete"}, + {"[H", "home"}, + {"[1~", "home"}, + {"[F", "end"}, + {"[4~", "end"}, + {"[5~", "page_up"}, + {"[6~", "page_down"}, + {"\t", "tab"}, + {"[Z", "shift_tab"}, + {"OP", "f1"}, + {"OQ", "f2"}, + {"OR", "f3"}, + {"OS", "f4"}, + {"[15~", "f5"}, + {"[17~", "f6"}, + {"[18~", "f7"}, + {"[19~", "f8"}, + {"[20~", "f9"}, + {"[21~", "f10"}, + {"[23~", "f11"}, + {"[24~", "f12"} + }; + + sigset_t signal_mask; + std::atomic polling (false); + array mouse_pos; + std::unordered_map mouse_mappings; + bool dragging_scroll; + + deque history(50, ""); + string old_filter; + string input; + + bool poll(const uint64_t timeout) { + atomic_lock lck(polling); + fd_set fds; + FD_ZERO(&fds); + FD_SET(STDIN_FILENO, &fds); + struct timespec wait; + struct timespec *waitptr = nullptr; + + if(timeout != std::numeric_limits::max()) { + wait.tv_sec = timeout / 1000; + wait.tv_nsec = (timeout % 1000) * 1000000; + waitptr = &wait; + } + + if(pselect(STDIN_FILENO + 1, &fds, nullptr, nullptr, waitptr, &signal_mask) > 0) { + input.clear(); + char buf[1024]; + ssize_t count = 0; + while((count = read(STDIN_FILENO, buf, sizeof(buf))) > 0) { + input.append(std::string_view(buf, count)); + } + + return true; + } + + return false; + } + + string get() { + string key = input; + if (not key.empty()) { + //? Remove escape code prefix if present + if (key.length() > 1 and key.at(0) == Fx::e.at(0)) { + key.erase(0, 1); + } + + //? Detect if input is a mouse event. + if (key.starts_with("[<")) { + std::string_view key_view = key; + string mouse_event; + if (key_view.starts_with("[<0;") and key_view.find('M') != std::string_view::npos) { + mouse_event = "mouse_click"; + key_view.remove_prefix(4); + } + else if (key_view.starts_with("[<32;")) { + mouse_event = "mouse_drag"; + key_view.remove_prefix(5); + } + else if (key_view.starts_with("[<0;") and key_view.ends_with('m')) { + mouse_event = "mouse_release"; + key_view.remove_prefix(4); + } + else if (key_view.starts_with("[<64;")) { + mouse_event = "mouse_scroll_up"; + key_view.remove_prefix(5); + } + else if (key_view.starts_with("[<65;")) { + mouse_event = "mouse_scroll_down"; + key_view.remove_prefix(5); + } + else + key.clear(); + + if (Config::getB("proc_filtering")) { + if (mouse_event == "mouse_click") return mouse_event; + else return ""; + } + + //? Get column and line position of mouse and check for any actions mapped to current position + if (not key.empty()) { + try { + const auto delim = key_view.find(';'); + mouse_pos[0] = stoi((string)key_view.substr(0, delim)); + mouse_pos[1] = stoi((string)key_view.substr(delim + 1, key_view.find('M', delim))); + } + catch (const std::invalid_argument&) { mouse_event.clear(); } + catch (const std::out_of_range&) { mouse_event.clear(); } + + key = mouse_event; + + if (key == "mouse_click" or key == "mouse_drag") { + const auto& [col, line] = mouse_pos; + + for (const auto& [mapped_key, pos] : (Menu::active ? Menu::mouse_mappings : mouse_mappings)) { + if (col >= pos.col and col < pos.col + pos.width and line >= pos.line and line < pos.line + pos.height) { + key = mapped_key; + break; + } + } + } + } + + } + else if (auto it = Key_escapes.find(key); it != Key_escapes.end()) + key = it->second; + else if (ulen(key) > 1) + key.clear(); + + if (not key.empty()) { + history.push_back(key); + history.pop_front(); + } + } + return key; + } + + string wait() { + while(not poll(std::numeric_limits::max())) {} + return get(); + } + + void interrupt() { + kill(getpid(), SIGUSR1); + } + + void clear() { + // do not need it, actually + } + + void process(const std::string_view key) { + if (key.empty()) return; + try { + auto filtering = Config::getB("proc_filtering"); + auto vim_keys = Config::getB("vim_keys"); + auto help_key = (vim_keys ? "H" : "h"); + auto kill_key = (vim_keys ? "K" : "k"); + //? Global input actions + if (not filtering) { + bool keep_going = false; + if (key == "q") { + clean_quit(0); + } + else if (is_in(key, "escape", "m")) { + Menu::show(Menu::Menus::Main); + return; + } + else if (is_in(key, "f1", "?", help_key)) { + Menu::show(Menu::Menus::Help); + return; + } + else if (is_in(key, "f2", "o")) { + Menu::show(Menu::Menus::Options); + return; + } + else if (key.size() == 1 and isint(key)) { + auto intKey = std::atoi(key.data()); + #ifdef GPU_SUPPORT + static const array boxes = {"gpu5", "cpu", "mem", "net", "proc", "gpu0", "gpu1", "gpu2", "gpu3", "gpu4"}; + if ((intKey == 0 and Gpu::count < 5) or (intKey >= 5 and intKey - 4 > Gpu::count)) + return; + #else + static const array boxes = {"", "cpu", "mem", "net", "proc"}; + if (intKey == 0 or intKey > 4) + return; + #endif + atomic_wait(Runner::active); + + if (not Config::toggle_box(boxes.at(intKey))) { + Menu::show(Menu::Menus::SizeError); + return; + } + Config::current_preset.reset(); + Draw::calcSizes(); + Draw::update_clock(true); + Runner::run("all", false, true); + return; + } + else if (is_in(key, "p", "P") and Config::getS("disable_presets") != "All") { + if (Config::getS("disable_presets") == "Default" and Config::preset_list.size() <= 1) return; + atomic_wait(Runner::active); + const auto old_preset = Config::current_preset; + const int first_preset = (Config::getS("disable_presets") == "Default") ? 1 : 0; + if (Config::getS("disable_presets") == "Custom") Config::current_preset = 0; + else if (Config::current_preset.has_value()) { + if (key == "p") { + if(++(*Config::current_preset) >= static_cast(Config::preset_list.size())) Config::current_preset = first_preset; + } + else if (--(*Config::current_preset) < first_preset) Config::current_preset = Config::preset_list.size() - 1; + } + else Config::current_preset = (key == "p") ? first_preset : Config::preset_list.size() - 1; + if (Config::current_preset == old_preset) return; + if (not Config::apply_preset(Config::preset_list.at(Config::current_preset.value()))) { + Menu::show(Menu::Menus::SizeError); + Config::current_preset = old_preset; + return; + } + Draw::calcSizes(); + Draw::update_clock(true); + Runner::run("all", false, true); + return; + } else if (is_in(key, "ctrl_r")) { + kill(getpid(), SIGUSR2); + return; + } else if (key == "mouse_release") { + dragging_scroll = false; + } else + keep_going = true; + + if (not keep_going) return; + } + + //? Input actions for proc box + if (Proc::shown) { + bool keep_going = false; + bool no_update = true; + bool redraw = true; + if (filtering) { + if (key == "enter" or key == "down") { + Config::set("proc_filter", Proc::filter.text); + Config::set("proc_filtering", false); + old_filter.clear(); + if(key == "down"){ + Config::unlock(); + Config::lock(); + process("down"); + return; + } + } + else if (key == "escape" or key == "mouse_click") { + Config::set("proc_filter", old_filter); + Config::set("proc_filtering", false); + old_filter.clear(); + } + else if (Proc::filter.command(key)) { + if (Config::getS("proc_filter") != Proc::filter.text) + Config::set("proc_filter", Proc::filter.text); + } + else + return; + } + else if (key == "left" or (vim_keys and key == "h")) { + int cur_i = v_index(Proc::sort_vector, Config::getS("proc_sorting")); + if (--cur_i < 0) + cur_i = Proc::sort_vector.size() - 1; + Config::set("proc_sorting", Proc::sort_vector.at(cur_i)); + Config::set("update_following", true); + if (Config::getB("proc_tree")) no_update = false; + } + else if (key == "right" or (vim_keys and key == "l")) { + int cur_i = v_index(Proc::sort_vector, Config::getS("proc_sorting")); + if (std::cmp_greater(++cur_i, Proc::sort_vector.size() - 1)) + cur_i = 0; + Config::set("proc_sorting", Proc::sort_vector.at(cur_i)); + Config::set("update_following", true); + if (Config::getB("proc_tree")) no_update = false; + } + else if (is_in(key, "f", "/")) { + Config::flip("proc_filtering"); + Proc::filter = Draw::TextEdit{Config::getS("proc_filter")}; + old_filter = Proc::filter.text; + } + else if (key == "e") { + Config::flip("proc_tree"); + no_update = false; + Config::set("update_following", true); + } + else if (key == "E" and Config::getB("proc_tree")) { + atomic_wait(Runner::active); + Proc::collapse_all = 1; + no_update = false; + } + else if (is_in(key, "u")) { + Config::flip("pause_proc_list"); + } + else if (is_in(key, "F")) { + if (Config::getI("proc_selected") != 0 and Config::getI("followed_pid") != Config::getI("selected_pid")) { + Config::set("follow_process", true); + Config::set("followed_pid", Config::getI("selected_pid")); + Config::set("update_following", true); + } + else if (Config::getB("show_detailed") and Config::getI("proc_selected") == 0 and Config::getI("followed_pid") != Config::getI("detailed_pid")) { + Config::set("follow_process", true); + Config::set("followed_pid", Config::getI("detailed_pid")); + Config::set("update_following", true); + } + else if (Config::getB("follow_process")) { + Config::flip("follow_process"); + if (Config::getB("should_selection_return_to_followed")) + Config::set("proc_selected", Config::getI("proc_followed")); + else if (Config::getB("show_detailed") and Config::getI("followed_pid") == Config::getI("detailed_pid")) + Config::set("restore_detailed_pid", Config::getI("detailed_pid")); + Config::set("followed_pid", 0); + Config::set("proc_followed", 0); + } + } + else if (key == "r") { + Config::flip("proc_reversed"); + Config::set("update_following", true); + } + else if (key == "c") + Config::flip("proc_per_core"); + + else if (key == "%") + Config::flip("proc_mem_bytes"); + + else if (key == "delete" and not Config::getS("proc_filter").empty()) + Config::set("proc_filter", ""s); + + else if (key.starts_with("mouse_")) { + redraw = false; + const auto& [col, line] = mouse_pos; + const int y = (Config::getB("show_detailed") ? Proc::y + 8 : Proc::y); + const int height = (Config::getB("show_detailed") ? Proc::height - 8 : Proc::height); + const auto in_proc_box = col >= Proc::x + 1 and col < Proc::x + Proc::width and line >= y + 1 and line < y + height - 1; + if (key == "mouse_click") { + if (in_proc_box) { + if (col < Proc::x + Proc::width - 2) { + const auto& current_selection = Config::getI("proc_selected"); + if (current_selection == line - y - 1) { + redraw = true; + if (Config::getB("proc_tree")) { + const int x_pos = col - Proc::x; + const int offset = Config::getI("selected_depth") * 3; + if (x_pos > offset and x_pos < 4 + offset) { + process("space"); + return; + } + } + process("enter"); + return; + } + else if (Config::getB("proc_banner_shown") and line == y + height - 2) + return; + else if (current_selection == 0 or line - y - 1 == 0) + redraw = true; + + if (Config::getB("follow_process") and not Config::getB("pause_proc_list")) { + Config::flip("follow_process"); + Config::set("followed_pid", 0); + Config::set("proc_followed", 0); + redraw = true; + } + + Config::set("proc_selected", line - y - 1); + } + else if (line == y + 1) { + if (Proc::selection("page_up") == -1) return; + } + else if (line == y + height - 2) { + if (Proc::selection("page_down") == -1) return; + } + else if (line == y + 2 + Proc::scroll_pos) { + dragging_scroll = true; + } + else if (Proc::selection("mousey" + to_string(line - y - 2)) == -1) + return; + } + else if (Config::getI("proc_selected") > 0){ + Config::set("proc_selected", 0); + if (Config::getB("follow_process") and not Config::getB("pause_proc_list")) { + Config::flip("follow_process"); + Config::set("followed_pid", 0); + Config::set("proc_followed", 0); + } + redraw = true; + } + } + else if (key.starts_with("mouse_scroll_") and in_proc_box) { + goto proc_mouse_scroll; + } + else if (key == "mouse_drag" and dragging_scroll) { + Proc::selection("mousey" + to_string(line - y - 2)); + } + else + keep_going = true; + } + else if (is_in(key, "enter", "info_enter")) { + if (Config::getI("proc_selected") == 0 and not Config::getB("show_detailed")) { + return; + } + else if (Config::getI("proc_selected") > 0 and Config::getI("detailed_pid") != Config::getI("selected_pid")) { + Config::set("detailed_pid", Config::getI("selected_pid")); + Config::set("proc_last_selected", Config::getI("proc_selected")); + Config::set("proc_selected", 0); + if (Config::getB("proc_follow_detailed")) { + Config::set("follow_process", true); + Config::set("followed_pid", Config::getI("selected_pid")); + } + Config::set("show_detailed", true); + } + else if (Config::getB("show_detailed")) { + if (Config::getB("proc_follow_detailed")) { + Config::set("restore_detailed_pid", Config::getI("detailed_pid")); + if (Config::getB("follow_process") and Config::getI("followed_pid") == Config::getI("detailed_pid")) { + Config::flip("follow_process"); + Config::set("followed_pid", 0); + Config::set("proc_followed", 0); + } + } + else if (Config::getI("proc_last_selected") > 0) Config::set("proc_selected", Config::getI("proc_last_selected")); + Config::set("proc_last_selected", 0); + Config::set("detailed_pid", 0); + Config::set("show_detailed", false); + } + Config::set("update_following", true); + } + else if (is_in(key, "+", "-", "space", "C", "=") and Config::getB("proc_tree")) { + const bool is_following_detailed = Config::getB("follow_process") and Config::getI("followed_pid") == Config::getI("detailed_pid"); + if (Config::getI("proc_selected") > 0 or is_following_detailed) { + atomic_wait(Runner::active); + auto& pid = is_following_detailed and Config::getI("proc_selected") == 0 ? Config::getI("followed_pid") : Config::getI("selected_pid"); + if (key == "+" or key == "space" or key == "=") Proc::expand = pid; + if (key == "-" or key == "space") Proc::collapse = pid; + if (key == "C") Proc::toggle_children = pid; + no_update = false; + } + else + keep_going = true; + } + else if (is_in(key, "t", kill_key) and (Config::getB("show_detailed") or Config::getI("selected_pid") > 0)) { + atomic_wait(Runner::active); + if (Config::getB("show_detailed") and Config::getI("proc_selected") == 0 and Proc::detailed.status == "Dead") return; + Menu::show(Menu::Menus::SignalSend, (key == "t" ? SIGTERM : SIGKILL)); + return; + } + else if (key == "s" and (Config::getB("show_detailed") or Config::getI("selected_pid") > 0)) { + atomic_wait(Runner::active); + if (Config::getB("show_detailed") and Config::getI("proc_selected") == 0 and Proc::detailed.status == "Dead") return; + Menu::show(Menu::Menus::SignalChoose); + return; + } + else if (key == "N" and (Config::getB("show_detailed") or Config::getI("selected_pid") > 0)) { + atomic_wait(Runner::active); + if (Config::getB("show_detailed") and Config::getI("proc_selected") == 0 and Proc::detailed.status == "Dead") return; + Menu::show(Menu::Menus::Renice); + return; + } + else if (is_in(key, "up", "down", "page_up", "page_down", "home", "end") or (vim_keys and is_in(key, "j", "k", "g", "G"))) { + proc_mouse_scroll: + redraw = false; + auto old_selected = Config::getI("proc_selected"); + auto new_selected = Proc::selection(key); + if (new_selected == -1) + return; + else if (old_selected != new_selected and (old_selected == 0 or new_selected == 0)) + redraw = true; + } + else keep_going = true; + + if (not keep_going) { + Runner::run("proc", no_update, redraw); + Runner::run("cpu", no_update, redraw); + return; + } + } + + //? Input actions for cpu box + if (Cpu::shown) { + bool keep_going = false; + bool no_update = true; + bool redraw = true; + static uint64_t last_press = 0; + + if ((key == "+" or key == "=") and Config::getI("update_ms") <= 86399900) { + int add = (Config::getI("update_ms") <= 86399000 and last_press >= time_ms() - 200 + and rng::all_of(Input::history, [](const auto& str){ return str == "+"; }) + ? 1000 : 100); + Config::set("update_ms", Config::getI("update_ms") + add); + last_press = time_ms(); + redraw = true; + } + else if (key == "-" and Config::getI("update_ms") >= 200) { + int sub = (Config::getI("update_ms") >= 2000 and last_press >= time_ms() - 200 + and rng::all_of(Input::history, [](const auto& str){ return str == "-"; }) + ? 1000 : 100); + Config::set("update_ms", Config::getI("update_ms") - sub); + last_press = time_ms(); + redraw = true; + } + else keep_going = true; + + if (not keep_going) { + Runner::run("cpu", no_update, redraw); + return; + } + } + + //? Input actions for mem box + if (Mem::shown) { + bool keep_going = false; + bool no_update = true; + bool redraw = true; + + if (key == "i") { + Config::flip("io_mode"); + } + else if (key == "d") { + Config::flip("show_disks"); + no_update = false; + Draw::calcSizes(); + } + else keep_going = true; + + if (not keep_going) { + Runner::run("mem", no_update, redraw); + return; + } + } + + //? Input actions for net box + if (Net::shown) { + bool keep_going = false; + bool no_update = true; + bool redraw = true; + + if (is_in(key, "b", "n")) { + atomic_wait(Runner::active); + int c_index = v_index(Net::interfaces, Net::selected_iface); + if (c_index != (int)Net::interfaces.size()) { + if (key == "b") { + if (--c_index < 0) c_index = Net::interfaces.size() - 1; + } + else if (key == "n") { + if (++c_index == (int)Net::interfaces.size()) c_index = 0; + } + Net::selected_iface = Net::interfaces.at(c_index); + Net::rescale = true; + } + } + else if (key == "y") { + Config::flip("net_sync"); + Net::rescale = true; + } + else if (key == "a") { + Config::flip("net_auto"); + Net::rescale = true; + } + else if (key == "z") { + atomic_wait(Runner::active); + auto& ndev = Net::current_net.at(Net::selected_iface); + if (ndev.stat.at("download").offset + ndev.stat.at("upload").offset > 0) { + ndev.stat.at("download").offset = 0; + ndev.stat.at("upload").offset = 0; + } + else { + ndev.stat.at("download").offset = ndev.stat.at("download").last + ndev.stat.at("download").rollover; + ndev.stat.at("upload").offset = ndev.stat.at("upload").last + ndev.stat.at("upload").rollover; + } + no_update = false; + } + else keep_going = true; + + if (not keep_going) { + Runner::run("net", no_update, redraw); + return; + } + } + } + + catch (const std::exception& e) { + throw std::runtime_error { fmt::format(R"(Input::process("{}"))", e.what()) }; + } + } +} diff --git a/vendor/btop/src/btop_input.hpp b/vendor/btop/src/btop_input.hpp new file mode 100644 index 000000000..b64662897 --- /dev/null +++ b/vendor/btop/src/btop_input.hpp @@ -0,0 +1,78 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include + +using std::array; +using std::atomic; +using std::deque; +using std::string; + +/* The input functions rely on the following termios parameters being set: + Non-canonical mode (c_lflags & ~(ICANON)) + VMIN and VTIME (c_cc) set to 0 + These will automatically be set when running Term::init() from btop_tools.cpp +*/ + +//* Functions and variables for handling keyboard and mouse input +namespace Input { + + struct Mouse_loc { + int line, col, height, width; + }; + + //? line, col, height, width + extern std::unordered_map mouse_mappings; + + //* Signal mask used during polling read + extern sigset_t signal_mask; + + extern atomic polling; + + //* Mouse column and line position + extern array mouse_pos; + + //* Last entered key + extern deque history; + + //* Poll keyboard & mouse input for ms and return input availability as a bool + bool poll(const uint64_t timeout=0); + + //* Get a key or mouse action from input + string get(); + + //* Wait until input is available and return key + string wait(); + + //* Interrupt poll/wait + void interrupt(); + + //* Clears last entered key + void clear(); + + //* Process actions for input + void process(const std::string_view key); + +} diff --git a/vendor/btop/src/btop_log.cpp b/vendor/btop/src/btop_log.cpp new file mode 100644 index 000000000..db70c4a29 --- /dev/null +++ b/vendor/btop/src/btop_log.cpp @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: Apache-2.0 + +#include "btop_log.hpp" + +#include "btop_shared.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace Logger { + namespace { + constexpr auto ONE_MEGABYTE = 1024 << 10; + + struct State { + std::mutex lock {}; + std::once_flag print_header; + Level level = Level::ERROR; + std::optional path {}; + }; + + [[nodiscard]] auto get_state() -> State& { + static State state; + return state; + } + + auto rotate_log_file(fs::path& path) { + std::error_code errc {}; + if (fs::exists(path, errc) && !errc && fs::file_size(path, errc) > ONE_MEGABYTE && !errc) { + auto old_path = path; + old_path += ".1"; + if (fs::exists(old_path, errc) && !errc) { + fs::remove(old_path, errc); + } + if (!errc) { + fs::rename(path, old_path, errc); + } + } + return !errc; + } + + class DropPrivilegeGuard { + private: + uid_t saved_euid {}; + + public: + DropPrivilegeGuard() { + saved_euid = geteuid(); + auto real_uid = getuid(); + if (saved_euid != real_uid && seteuid(real_uid) != 0) { + throw std::runtime_error( + fmt::format("Failed to drop privileges to write log file: {}", strerror(errno)) + ); + } + } + + ~DropPrivilegeGuard() noexcept { + if (saved_euid != geteuid()) { + // Silently drop error status. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wunused-result" + seteuid(saved_euid); + #pragma GCC diagnostic pop + } + } + + DropPrivilegeGuard(const DropPrivilegeGuard&) = delete; + DropPrivilegeGuard& operator=(const DropPrivilegeGuard&) = delete; + }; + } // namespace + + void init(const fs::path& path) { + auto& state = get_state(); + std::lock_guard guard { state.lock }; + state.path = std::make_optional(path); + } + + void set_log_level(Level level) { + auto& state = get_state(); + std::lock_guard guard { state.lock }; + state.level = level; + } + + void set_log_level(const std::string_view level) { + auto& state = get_state(); + auto it = std::ranges::find(log_levels, level); + if (it != log_levels.end()) { + std::lock_guard guard { state.lock }; + state.level = static_cast(std::distance(log_levels.begin(), it)); + } + } + + namespace detail { + [[nodiscard]] auto is_enabled(Level level) -> bool { + auto& state = get_state(); + return state.level >= level && state.path.has_value(); + } + + void log_write(Level level, const std::string_view msg) { + auto& state = get_state(); + + auto guard = std::lock_guard { state.lock }; + + if (!is_enabled(level) || !state.path.has_value()) { + return; + } + + std::string buffer {}; + std::call_once(state.print_header, [&buffer]() { + fmt::format_to(std::back_inserter(buffer), "\n===> btop++ v{}\n", Global::Version); + }); + auto now = std::chrono::system_clock::now(); + auto seconds = std::chrono::time_point_cast(now); + fmt::format_to( + std::back_inserter(buffer), + "{:%FT%T}Z | {}: {}\n", + seconds, + log_levels.at(std::to_underlying(level)), + msg + ); + + DropPrivilegeGuard privilege_guard {}; + + auto& path = state.path.value(); + if (!rotate_log_file(path)) { + return; + } + + auto file = std::ofstream { path, std::ios::app }; + if (!file.is_open()) { + return; + } + file << buffer; + } + } // namespace detail + +} // namespace Logger + +const std::vector Logger::log_levels = { "DISABLED", "ERROR", "WARNING", "INFO", "DEBUG" }; diff --git a/vendor/btop/src/btop_log.hpp b/vendor/btop/src/btop_log.hpp new file mode 100644 index 000000000..1c8e4aba0 --- /dev/null +++ b/vendor/btop/src/btop_log.hpp @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace Logger { + enum class Level : std::uint8_t { + DISABLED = 0, + ERROR = 1, + WARNING = 2, + INFO = 3, + DEBUG = 4, + }; + + extern const std::vector log_levels; + + namespace detail { + auto is_enabled(Level level) -> bool; + + void log_write(Level level, const std::string_view msg); + } // namespace detail + + void init(const std::filesystem::path& path); + + void set_log_level(Level level); + + void set_log_level(const std::string_view level); + + template + inline void error(fmt::format_string fmt, T&&... args) { + // Check if log level is enabled before allocating string. + if (detail::is_enabled(Level::ERROR)) { + detail::log_write(Level::ERROR, fmt::format(fmt, std::forward(args)...)); + } + } + + template + inline void warning(fmt::format_string fmt, T&&... args) { + // Check if log level is enabled before allocating string. + if (detail::is_enabled(Level::WARNING)) { + detail::log_write(Level::WARNING, fmt::format(fmt, std::forward(args)...)); + } + } + + template + inline void info(fmt::format_string fmt, T&&... args) { + // Check if log level is enabled before allocating string. + if (detail::is_enabled(Level::INFO)) { + detail::log_write(Level::INFO, fmt::format(fmt, std::forward(args)...)); + } + } + + template + inline void debug(fmt::format_string fmt, T&&... args) { + // Check if log level is enabled before allocating string. + if (detail::is_enabled(Level::DEBUG)) { + detail::log_write(Level::DEBUG, fmt::format(fmt, std::forward(args)...)); + } + } +} // namespace Logger diff --git a/vendor/btop/src/btop_menu.cpp b/vendor/btop/src/btop_menu.cpp new file mode 100644 index 000000000..bcb64bf7b --- /dev/null +++ b/vendor/btop/src/btop_menu.cpp @@ -0,0 +1,1963 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include "btop_menu.hpp" + +#include "btop_config.hpp" +#include "btop_draw.hpp" +#include "btop_log.hpp" +#include "btop_shared.hpp" +#include "btop_theme.hpp" +#include "btop_tools.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +using std::array; +using std::ceil; +using std::max; +using std::min; +using std::ref; +using std::views::iota; + +using namespace Tools; + +namespace fs = std::filesystem; + +namespace Menu { + + atomic active (false); + string bg; + bool redraw{true}; + int currentMenu = -1; + msgBox messageBox; + int signalToSend{}; + int signalKillRet{}; + + const array P_Signals = { + "0", +#ifdef __linux__ +#if defined(__hppa__) + "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", + "SIGTRAP", "SIGABRT", "SIGSTKFLT", "SIGFPE", + "SIGKILL", "SIGBUS", "SIGSEGV", "SIGXCPU", + "SIGPIPE", "SIGALRM", "SIGTERM", "SIGUSR1", + "SIGUSR2", "SIGCHLD", "SIGPWR", "SIGVTALRM", + "SIGPROF", "SIGIO", "SIGWINCH", "SIGSTOP", + "SIGTSTP", "SIGCONT", "SIGTTIN", "SIGTTOU", + "SIGURG", "SIGXFSZ", "SIGSYS" +#elif defined(__mips__) + "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", + "SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE", + "SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS", + "SIGPIPE", "SIGALRM", "SIGTERM", "SIGUSR1", + "SIGUSR2", "SIGCHLD", "SIGPWR", "SIGWINCH", + "SIGURG", "SIGIO", "SIGSTOP", "SIGTSTP", + "SIGCONT", "SIGTTIN", "SIGTTOU", "SIGVTALRM", + "SIGPROF", "SIGXCPU", "SIGXFSZ" +#elif defined(__alpha__) + "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", + "SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE", + "SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS", + "SIGPIPE", "SIGALRM", "SIGTERM", "SIGURG", + "SIGSTOP", "SIGTSTP", "SIGCONT", "SIGCHLD", + "SIGTTIN", "SIGTTOU", "SIGIO", "SIGXCPU", + "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", + "SIGPWR", "SIGUSR1", "SIGUSR2" +#elif defined (__sparc__) + "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", + "SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE", + "SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS", + "SIGPIPE", "SIGALRM", "SIGTERM", "SIGURG", + "SIGSTOP", "SIGTSTP", "SIGCONT", "SIGCHLD", + "SIGTTIN", "SIGTTOU", "SIGIO", "SIGXCPU", + "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", + "SIGLOST", "SIGUSR1", "SIGUSR2" +#else + "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", + "SIGTRAP", "SIGABRT", "SIGBUS", "SIGFPE", + "SIGKILL", "SIGUSR1", "SIGSEGV", "SIGUSR2", + "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", + "SIGCHLD", "SIGCONT", "SIGSTOP", "SIGTSTP", + "SIGTTIN", "SIGTTOU", "SIGURG", "SIGXCPU", + "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", + "SIGIO", "SIGPWR", "SIGSYS" +#endif +#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__APPLE__) + "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", + "SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE", + "SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS", + "SIGPIPE", "SIGALRM", "SIGTERM", "SIGURG", + "SIGSTOP", "SIGTSTP", "SIGCONT", "SIGCHLD", + "SIGTTIN", "SIGTTOU", "SIGIO", "SIGXCPU", + "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", + "SIGINFO", "SIGUSR1", "SIGUSR2" +#else + "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", + "SIGTRAP", "SIGABRT", "7", "SIGFPE", + "SIGKILL", "10", "SIGSEGV", "12", + "SIGPIPE", "SIGALRM", "SIGTERM", "16", + "17", "18", "19", "20", + "21", "22", "23", "24", + "25", "26", "27", "28", + "29", "30", "31" +#endif + }; + + std::unordered_map mouse_mappings; + + const array, 3> menu_normal = { + array{ + "┌─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐", + "│ │├─┘ │ ││ ││││└─┐", + "└─┘┴ ┴ ┴└─┘┘└┘└─┘" + }, + { + "┬ ┬┌─┐┬ ┌─┐", + "├─┤├┤ │ ├─┘", + "┴ ┴└─┘┴─┘┴ " + }, + { + "┌─┐ ┬ ┬ ┬┌┬┐", + "│─┼┐│ │ │ │ ", + "└─┘└└─┘ ┴ ┴ " + } + }; + + const array, 3> menu_selected = { + array{ + "╔═╗╔═╗╔╦╗╦╔═╗╔╗╔╔═╗", + "║ ║╠═╝ ║ ║║ ║║║║╚═╗", + "╚═╝╩ ╩ ╩╚═╝╝╚╝╚═╝" + }, + { + "╦ ╦╔═╗╦ ╔═╗", + "╠═╣╠╣ ║ ╠═╝", + "╩ ╩╚═╝╩═╝╩ " + }, + { + "╔═╗ ╦ ╦ ╦╔╦╗ ", + "║═╬╗║ ║ ║ ║ ", + "╚═╝╚╚═╝ ╩ ╩ " + } + }; + + const array menu_width = {19, 12, 12}; + + const vector> help_text = { + {"Mouse 1", "Clicks buttons and selects in process list."}, + {"Mouse scroll", "Scrolls any scrollable list/text under cursor."}, + {"Esc, m", "Toggles main menu."}, + {"p", "Cycle view presets forwards."}, + {"shift + p", "Cycle view presets backwards."}, + {"1", "Toggle CPU box."}, + {"2", "Toggle MEM box."}, + {"3", "Toggle NET box."}, + {"4", "Toggle PROC box."}, + {"5", "Toggle GPU box."}, + {"d", "Toggle disks view in MEM box."}, + {"F2, o", "Shows options."}, + {"F1, ?, h", "Shows this window."}, + {"ctrl + z", "Sleep program and put in background."}, + {"ctrl + r", "Reloads config file from disk."}, + {"q, ctrl + c", "Quits program."}, + {"+, -", "Add/Subtract 100ms to/from update timer."}, + {"Up, Down", "Select in process list."}, + {"Enter", "Show detailed information for selected process."}, + {"Spacebar", "Expand/collapse the selected process in tree view."}, + {"C", "Expand/collapse the selected process' children."}, + {"Pg Up, Pg Down", "Jump 1 page in process list."}, + {"Home, End", "Jump to first or last page in process list."}, + {"Left, Right", "Select previous/next sorting column."}, + {"b, n", "Select previous/next network device."}, + {"i", "Toggle disks io mode with big graphs."}, + {"z", "Toggle totals reset for current network device"}, + {"a", "Toggle auto scaling for the network graphs."}, + {"y", "Toggle synced scaling mode for network graphs."}, + {"f, /", "To enter a process filter. Start with ! for regex."}, + {"F", "Follow selected process."}, + {"u", "Pause process list."}, + {"delete", "Clear any entered filter."}, + {"c", "Toggle per-core cpu usage of processes."}, + {"r", "Reverse sorting order in processes box."}, + {"e", "Toggle processes tree view."}, + {"E", "Collapse/expand all processes in tree view."}, + {"%", "Toggles memory display mode in processes box."}, + {"Selected +, -", "Expand/collapse the selected process in tree view."}, + {"Selected t", "Terminate selected process with SIGTERM - 15."}, + {"Selected k", "Kill selected process with SIGKILL - 9."}, + {"Selected s", "Select or enter signal to send to process."}, + {"Selected N", "Select new nice value for selected process."}, + {"", " "}, + {"", "For bug reporting and project updates, visit:"}, + {"", "https://github.com/aristocratos/btop"}, + }; + + const vector>> categories = { + { + {"color_theme", + "Set color theme.", + "", + "Choose from all theme files in (usually)", + "\"/usr/[local/]share/btop/themes\" and", + "\"~/.config/btop/themes\".", + "", + "\"Default\" for builtin default theme.", + "\"TTY\" for builtin 16-color theme.", + "", + "For theme updates see:", + "https://github.com/aristocratos/btop"}, + {"theme_background", + "If the theme set background should be shown.", + "", + "Set to False if you want terminal background", + "transparency."}, + {"truecolor", + "Sets if 24-bit truecolor should be used.", + "", + "Will convert 24-bit colors to 256 color", + "(6x6x6 color cube) if False.", + "", + "Set to False if your terminal doesn't have", + "truecolor support and can't convert to", + "256-color."}, + {"force_tty", + "TTY mode.", + "", + "Set to true to force tty mode regardless", + "if a real tty has been detected or not.", + "", + "Will force 16-color mode and TTY theme,", + "set all graph symbols to \"tty\" and swap", + "out other non tty friendly symbols."}, + {"vim_keys", + "Enable vim keys.", + "Set to True to enable \"h,j,k,l\" keys for", + "directional control in lists.", + "", + "Conflicting keys for", + "h (help) and k (kill)", + "is accessible while holding shift."}, + {"disable_mouse", + "Disable all mouse events."}, + {"disable_presets", + "Disable the presets.", + "", + "\"Off\" All presets are enabled.", + "", + "\"Default\" preset is disabled.", + "", + "\"Custom\" presets are disabled.", + "", + "\"All\" presets are disabled."}, + {"presets", + "Define presets for the layout of the boxes.", + "", + "Preset 0 is always all boxes shown with", + "default settings.", + "Max 9 presets.", + "", + "Format: \"box_name:P:G,box_name:P:G\"", + "P=(0 or 1) for alternate positions.", + "G=graph symbol to use for box.", + "", + "Use whitespace \" \" as separator between", + "different presets.", + "", + "Example:", + "\"mem:0:tty,proc:1:default cpu:0:braille\""}, + {"shown_boxes", + "Manually set which boxes to show.", + "", + "Available values are \"cpu mem net proc\".", + #ifdef GPU_SUPPORT + "Or \"gpu0\" through \"gpu5\" for GPU boxes.", + #endif + "Separate values with whitespace.", + "", + "Toggle between presets with key \"p\"."}, + {"update_ms", + "Update time in milliseconds.", + "", + "Recommended 2000 ms or above for better", + "sample times for graphs.", + "", + "Min value: 100 ms", + "Max value: 86400000 ms = 24 hours."}, + {"rounded_corners", + "Rounded corners on boxes.", + "", + "True or False", + "", + "Is always False if TTY mode is ON."}, + {"terminal_sync", + "Output synchronization.", + "", + "Use terminal synchronized output sequences", + "to reduce flickering on supported terminals.", + "", + "True or False."}, + {"graph_symbol", + "Default symbols to use for graph creation.", + "", + "\"braille\", \"block\" or \"tty\".", + "", + "\"braille\" offers the highest resolution but", + "might not be included in all fonts.", + "", + "\"block\" has half the resolution of braille", + "but uses more common characters.", + "", + "\"tty\" uses only 3 different symbols but will", + "work with most fonts.", + "", + "Note that \"tty\" only has half the horizontal", + "resolution of the other two,", + "so will show a shorter historical view."}, + {"clock_format", + "Draw a clock at top of screen.", + "(Only visible if cpu box is enabled!)", + "", + "Formatting according to strftime, empty", + "string to disable.", + "", + "Custom formatting options:", + "\"/host\" = hostname", + "\"/user\" = username", + "\"/uptime\" = system uptime", + "", + "Examples of strftime formats:", + "\"%X\" = locale HH:MM:SS", + "\"%H\" = 24h hour, \"%I\" = 12h hour", + "\"%M\" = minute, \"%S\" = second", + "\"%d\" = day, \"%m\" = month, \"%y\" = year"}, + {"base_10_sizes", + "Use base 10 for bits and bytes sizes.", + "", + "Uses KB = 1000 instead of KiB = 1024,", + "MB = 1000KB instead of MiB = 1024KiB,", + "and so on.", + "", + "True or False."}, + {"background_update", + "Update main ui when menus are showing.", + "", + "True or False.", + "", + "Set this to false if the menus is flickering", + "too much for a comfortable experience."}, + {"show_battery", + "Show battery stats.", + "(Only visible if cpu box is enabled!)", + "", + "Show battery stats in the top right corner", + "if a battery is present."}, + {"selected_battery", + "Select battery.", + "", + "Which battery to use if multiple are present.", + "Can be both batteries and UPS.", + "", + "\"Auto\" for auto detection."}, + {"show_battery_watts", + "Show battery power.", + "", + "Show discharge power when discharging.", + "Show charging power when charging."}, + {"log_level", + "Set loglevel for error.log", + "", + "\"ERROR\", \"WARNING\", \"INFO\" and \"DEBUG\".", + "", + "The level set includes all lower levels,", + "i.e. \"DEBUG\" will show all logging info."}, + {"save_config_on_exit", + "Save config on exit.", + "", + "Automatically save current settings to", + "config file on exit.", + "", + "When this is toggled from True to False", + "a save is immediately triggered.", + "This way a manual save can be done by", + "toggling this setting on and off again."} + }, + { + {"cpu_bottom", + "Cpu box location.", + "", + "Show cpu box at bottom of screen instead", + "of top."}, + {"graph_symbol_cpu", + "Graph symbol to use for graphs in cpu box.", + "", + "\"default\", \"braille\", \"block\" or \"tty\".", + "", + "\"default\" for the general default symbol.",}, + {"cpu_graph_upper", + "Cpu upper graph.", + "", + "Sets the CPU/GPU stat shown in upper half of", + "the CPU graph.", + "", + "CPU:", + "\"total\" = Total cpu usage. (Auto)", + "\"user\" = User mode cpu usage.", + "\"system\" = Kernel mode cpu usage.", + "+ more depending on kernel.", + #ifdef GPU_SUPPORT + "", + "GPU:", + "\"gpu-totals\" = GPU usage split by device.", + "\"gpu-vram-totals\" = VRAM usage split by GPU.", + "\"gpu-pwr-totals\" = Power usage split by GPU.", + "\"gpu-average\" = Avg usage of all GPUs.", + "\"gpu-vram-total\" = VRAM usage of all GPUs.", + "\"gpu-pwr-total\" = Power usage of all GPUs.", + "Not all stats are supported on all devices." + #endif + }, + {"cpu_graph_lower", + "Cpu lower graph.", + "", + "Sets the CPU/GPU stat shown in lower half of", + "the CPU graph.", + "", + "CPU:", + "\"total\" = Total cpu usage.", + "\"user\" = User mode cpu usage.", + "\"system\" = Kernel mode cpu usage.", + "+ more depending on kernel.", + #ifdef GPU_SUPPORT + "", + "GPU:", + "\"gpu-totals\" = GPU usage split/device. (Auto)", + "\"gpu-vram-totals\" = VRAM usage split by GPU.", + "\"gpu-pwr-totals\" = Power usage split by GPU.", + "\"gpu-average\" = Avg usage of all GPUs.", + "\"gpu-vram-total\" = VRAM usage of all GPUs.", + "\"gpu-pwr-total\" = Power usage of all GPUs.", + "Not all stats are supported on all devices." + #endif + }, + {"cpu_invert_lower", + "Toggles orientation of the lower CPU graph.", + "", + "True or False."}, + {"cpu_single_graph", + "Completely disable the lower CPU graph.", + "", + "Shows only upper CPU graph and resizes it", + "to fit to box height.", + "", + "True or False."}, + #ifdef GPU_SUPPORT + {"show_gpu_info", + "Show gpu info in cpu box.", + "", + "Toggles gpu stats in cpu box and the", + "gpu graph (if \"cpu_graph_lower\" is set to", + "\"Auto\").", + "", + "\"Auto\" to show when no gpu box is shown.", + "\"On\" to always show.", + "\"Off\" to never show."}, + #endif + {"check_temp", + "Enable cpu temperature reporting.", + "", + "True or False."}, + {"cpu_sensor", + "Cpu temperature sensor.", + "", + "Select the sensor that corresponds to", + "your cpu temperature.", + "", + "Set to \"Auto\" for auto detection."}, + {"show_coretemp", + "Show temperatures for cpu cores.", + "", + "Only works if check_temp is True and", + "the system is reporting core temps."}, + {"cpu_core_map", + "Custom mapping between core and coretemp.", + "", + "Can be needed on certain cpus to get correct", + "temperature for correct core.", + "", + "Use lm-sensors or similar to see which cores", + "are reporting temperatures on your machine.", + "", + "Format: \"X:Y\"", + "X=core with wrong temp.", + "Y=core with correct temp.", + "Use space as separator between multiple", + "entries.", + "", + "Example: \"4:0 5:1 6:3\""}, + {"temp_scale", + "Which temperature scale to use.", + "", + "Celsius, default scale.", + "", + "Fahrenheit, the american one.", + "", + "Kelvin, 0 = absolute zero, 1 degree change", + "equals 1 degree change in Celsius.", + "", + "Rankine, 0 = absolute zero, 1 degree change", + "equals 1 degree change in Fahrenheit."}, + {"show_cpu_freq", + "Show CPU frequency.", + "", + "Can cause slowdowns on systems with many", + "cores and certain kernel versions."}, + #ifdef __linux__ + {"freq_mode", + "How the CPU frequency will be displayed.", + "", + "First, get the frequency from the first", + "core.", + "", + "Range, show the lowest and the highest", + "frequency.", + "", + "Lowest, the lowest frequency.", + "", + "Highest, the highest frequency.", + "", + "Average, sum and divide."}, + #endif + {"custom_cpu_name", + "Custom cpu model name in cpu percentage box.", + "", + "Empty string to disable."}, + {"show_uptime", + "Shows the system uptime in the CPU box.", + "", + "Can also be shown in the clock by using", + "\"/uptime\" in the formatting.", + "", + "True or False."}, + {"show_cpu_watts", + "Shows the CPU power consumption in watts.", + "", + "Requires running `make setcap` or", + "`make setuid` or running with sudo.", + "", + "True or False."}, + }, + #ifdef GPU_SUPPORT + { + {"nvml_measure_pcie_speeds", + "Measure PCIe throughput on NVIDIA cards.", + "", + "May impact performance on certain cards.", + "", + "True or False."}, + {"rsmi_measure_pcie_speeds", + "Measure PCIe throughput on AMD cards.", + "", + "May impact performance on certain cards.", + "", + "True or False."}, + {"graph_symbol_gpu", + "Graph symbol to use for graphs in gpu box.", + "", + "\"default\", \"braille\", \"block\" or \"tty\".", + "", + "\"default\" for the general default symbol.",}, + {"gpu_mirror_graph", + "Horizontally mirror the GPU graph.", + "", + "True or False."}, + {"shown_gpus", + "Manually set which gpu vendors to show.", + "", + "Available values are", + "\"nvidia\", \"amd\", \"intel\",", + "and \"apple\".", + "Separate values with whitespace.", + "", + "A restart is required to apply changes."}, + {"custom_gpu_name0", + "Custom gpu0 model name in gpu stats box.", + "", + "Empty string to disable."}, + {"custom_gpu_name1", + "Custom gpu1 model name in gpu stats box.", + "", + "Empty string to disable."}, + {"custom_gpu_name2", + "Custom gpu2 model name in gpu stats box.", + "", + "Empty string to disable."}, + {"custom_gpu_name3", + "Custom gpu3 model name in gpu stats box.", + "", + "Empty string to disable."}, + {"custom_gpu_name4", + "Custom gpu4 model name in gpu stats box.", + "", + "Empty string to disable."}, + {"custom_gpu_name5", + "Custom gpu5 model name in gpu stats box.", + "", + "Empty string to disable."}, + }, + #endif + { + {"mem_below_net", + "Mem box location.", + "", + "Show mem box below net box instead of above."}, + {"graph_symbol_mem", + "Graph symbol to use for graphs in mem box.", + "", + "\"default\", \"braille\", \"block\" or \"tty\".", + "", + "\"default\" for the general default symbol.",}, + {"mem_graphs", + "Show graphs for memory values.", + "", + "True or False."}, + {"show_disks", + "Split memory box to also show disks.", + "", + "True or False."}, + {"show_io_stat", + "Toggle IO activity graphs.", + "", + "Show small IO graphs that for disk activity", + "(disk busy time) when not in IO mode.", + "", + "True or False."}, + {"io_mode", + "Toggles io mode for disks.", + "", + "Shows big graphs for disk read/write speeds", + "instead of used/free percentage meters.", + "", + "True or False."}, + {"io_graph_combined", + "Toggle combined read and write graphs.", + "", + "Only has effect if \"io mode\" is True.", + "", + "True or False."}, + {"io_graph_speeds", + "Set top speeds for the io graphs.", + "", + "Manually set which speed in MiB/s that", + "equals 100 percent in the io graphs.", + "(100 MiB/s by default).", + "", + "Format: \"device:speed\" separate disks with", + "whitespace \" \".", + "", + "Example: \"/dev/sda:100, /dev/sdb:20\"."}, + {"show_swap", + "If swap memory should be shown in memory box.", + "", + "True or False."}, + {"swap_disk", + "Show swap as a disk.", + "", + "Ignores show_swap value above.", + "Inserts itself after first disk."}, + {"only_physical", + "Filter out non physical disks.", + "", + "Set this to False to include network disks,", + "RAM disks and similar.", + "", + "True or False."}, + {"use_fstab", + "(Linux) Read disks list from /etc/fstab.", + "", + "This also disables only_physical.", + "", + "True or False."}, + {"zfs_hide_datasets", + "(Linux) Hide ZFS datasets in disks list.", + "", + "Setting this to True will hide all datasets,", + "and only show ZFS pools.", + "", + "(IO stats will be calculated per-pool)", + "", + "True or False."}, + {"disk_free_priv", + "(Linux) Type of available disk space.", + "", + "Set to true to show how much disk space is", + "available for privileged users.", + "", + "Set to false to show available for normal", + "users."}, + {"disks_filter", + "Optional filter for shown disks.", + "", + "Should be full path of a mountpoint.", + "Separate multiple values with", + "whitespace \" \".", + "", + "Only disks matching the filter will be shown.", + "Prepend \033[3mexclude=\033[23m to only show disks ", + "not matching the filter.", + "", + "Examples:", + "/boot /home/user", + "exclude=/boot /home/user"}, + {"zfs_arc_cached", + "(Linux) Count ZFS ARC as cached memory.", + "", + "Add ZFS ARC used to cached memory and", + "ZFS ARC available to available memory.", + "These are otherwise reported by the Linux", + "kernel as used memory.", + "", + "True or False."}, + }, + { + {"graph_symbol_net", + "Graph symbol to use for graphs in net box.", + "", + "\"default\", \"braille\", \"block\" or \"tty\".", + "", + "\"default\" for the general default symbol.",}, + {"swap_upload_download", + "Swap the positions of the upload and download", + "graphs.", + "", + "This allows for a more \"intuitive\" view", + "with download being down, on the bottom."}, + {"net_download", + "Fixed network graph download value.", + "", + "Value in Mebibits, default \"100\".", + "", + "Can be toggled with auto button."}, + {"net_upload", + "Fixed network graph upload value.", + "", + "Value in Mebibits, default \"100\".", + "", + "Can be toggled with auto button."}, + {"net_auto", + "Start in network graphs auto rescaling mode.", + "", + "Ignores any values set above at start and", + "rescales down to 10Kibibytes at the lowest.", + "", + "True or False."}, + {"net_sync", + "Network scale sync.", + "", + "Syncs the scaling for download and upload to", + "whichever currently has the highest scale.", + "", + "True or False."}, + {"net_iface", + "Network Interface.", + "", + "Manually set the starting Network Interface.", + "", + "Will otherwise automatically choose the NIC", + "with the highest total download since boot."}, + {"base_10_bitrate", + "Base 10 bitrate", + "", + "True: Use SI prefixes for bitrates", + " (1000Kbps = 1Mbps)", + "False: Use binary prefixes for bitrates", + " (1024Kibps = 1Mibps)", + "Auto: Use the General -> Base 10 Sizes", + " setting for bitrates", + "", + "True, False, or Auto",}, + }, + { + {"proc_left", + "Proc box location.", + "", + "Show proc box on left side of screen", + "instead of right."}, + {"graph_symbol_proc", + "Graph symbol to use for graphs in proc box.", + "", + "\"default\", \"braille\", \"block\" or \"tty\".", + "", + "\"default\" for the general default symbol.",}, + {"proc_sorting", + "Processes sorting option.", + "", + "Possible values:", + "\"pid\", \"program\", \"arguments\", \"threads\",", + "\"user\", \"memory\", \"cpu lazy\" and", + "\"cpu direct\".", + "", + "\"cpu lazy\" updates top process over time.", + "\"cpu direct\" updates top process", + "directly."}, + {"proc_reversed", + "Reverse processes sorting order.", + "", + "True or False."}, + {"proc_tree", + "Processes tree view.", + "", + "Set true to show processes grouped by", + "parents with lines drawn between parent", + "and child process."}, + {"proc_aggregate", + "Aggregate child's resources in parent.", + "", + "In tree-view, include all child resources", + "with the parent even while expanded."}, + {"proc_tree_auto_collapse", + "Auto-collapse busy parents in tree view.", + "", + "When entering tree mode, automatically", + "collapse any process that has this many", + "or more direct children.", + "", + "Useful for hiding noisy multi-process apps", + "like Chrome, Firefox or Electron.", + "", + "Set to 0 to disable.", + "", + "Min value: 0", + "Max value: 10000"}, + {"proc_colors", + "Enable colors in process view.", + "", + "True or False."}, + {"proc_gradient", + "Enable process view gradient fade.", + "", + "Fades from top or current selection.", + "Max fade value is equal to current themes", + "\"inactive_fg\" color value."}, + {"proc_per_core", + "Process usage per core.", + "", + "If process cpu usage should be of the core", + "it's running on or usage of the total", + "available cpu power.", + "", + "If true and process is multithreaded", + "cpu usage can reach over 100%."}, + {"proc_mem_bytes", + "Show memory as bytes in process list.", + " ", + "Will show percentage of total memory", + "if False."}, + {"keep_dead_proc_usage", + "Cpu and Mem usage for dead processes", + "", + "Set true if process should preserve the cpu", + "and memory usage of when it died while", + "paused."}, + {"proc_cpu_graphs", + "Show cpu graph for each process.", + "", + "True or False"}, + {"proc_filter_kernel", + "(Linux) Filter kernel processes from output.", + "", + "Set to 'True' to filter out internal", + "processes started by the Linux kernel."}, + {"proc_follow_detailed", + "Follow selected process with detailed view", + "", + "If set to 'True' then when opening the", + "detailed view, the process will be", + "followed in the list. Pressing enter", + "again will close the detailed view", + "and stop following the process."}, + } + }; + + msgBox::msgBox() {} + msgBox::msgBox(int width, int boxtype, const vector& content, const std::string_view title) + : width(width), boxtype(boxtype) { + auto tty_mode = Config::getB("tty_mode"); + auto rounded = Config::getB("rounded_corners"); + const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up); + const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up); + const auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down); + const auto& left_down = (tty_mode or not rounded ? Symbols::left_down : Symbols::round_left_down); + height = content.size() + 7; + x = Term::width / 2 - width / 2; + y = Term::height/2 - height/2; + if (boxtype == 2) selected = 1; + + + button_left = left_up + Symbols::h_line * 6 + Mv::l(7) + Mv::d(2) + left_down + Symbols::h_line * 6 + Mv::l(7) + Mv::u(1) + Symbols::v_line; + button_right = Symbols::v_line + Mv::l(7) + Mv::u(1) + Symbols::h_line * 6 + right_up + Mv::l(7) + Mv::d(2) + Symbols::h_line * 6 + right_down + Mv::u(2); + + box_contents = Draw::createBox(x, y, width, height, Theme::c("hi_fg"), true, title) + Mv::d(1); + for (const auto& line : content) { + box_contents += Mv::save + Mv::r(max((size_t)0, (width / 2) - (Fx::uncolor(line).size() / 2) - 1)) + line + Mv::restore + Mv::d(1); + } + } + + string msgBox::operator()() { + string out; + int pos = width / 2 - (boxtype == 0 ? 6 : 14); + const auto first_color = (selected == 0 ? Theme::c("hi_fg") : Theme::c("div_line")); + out = Mv::d(1) + Mv::r(pos) + Fx::b + first_color + button_left + (selected == 0 ? Theme::c("title") : Theme::c("main_fg") + Fx::ub) + + (boxtype == 0 ? " Ok " : " Yes ") + first_color + button_right; + mouse_mappings["button1"] = Input::Mouse_loc{y + height - 4, x + pos + 1, 3, 12 + (boxtype > 0 ? 1 : 0)}; + if (boxtype > 0) { + const auto second_color = (selected == 1 ? Theme::c("hi_fg") : Theme::c("div_line")); + out += Mv::r(2) + second_color + button_left + (selected == 1 ? Theme::c("title") : Theme::c("main_fg") + Fx::ub) + + " No " + second_color + button_right; + mouse_mappings["button2"] = Input::Mouse_loc{y + height - 4, x + pos + 15 + (boxtype > 0 ? 1 : 0), 3, 12}; + } + return box_contents + out + Fx::reset; + } + + //? Process input + int msgBox::input(const string& key) { + if (key.empty()) return Invalid; + + if (is_in(key, "escape", "backspace", "q") or key == "button2") { + return No_Esc; + } + else if (key == "button1" or (boxtype == 0 and str_to_upper(key) == "O")) { + return Ok_Yes; + } + else if (is_in(key, "enter", "space")) { + return selected + 1; + } + else if (boxtype == 0) { + return Invalid; + } + else if (str_to_upper(key) == "Y") { + return Ok_Yes; + } + else if (str_to_upper(key) == "N") { + return No_Esc; + } + else if (is_in(key, "right", "tab")) { + if (++selected > 1) selected = 0; + return Select; + } + else if (is_in(key, "left", "shift_tab")) { + if (--selected < 0) selected = 1; + return Select; + } + + return Invalid; + } + + void msgBox::clear() { + box_contents.clear(); + box_contents.shrink_to_fit(); + button_left.clear(); + button_left.shrink_to_fit(); + button_right.clear(); + button_right.shrink_to_fit(); + mouse_mappings.erase("button1"); + mouse_mappings.erase("button2"); + } + + enum menuReturnCodes { + NoChange, + Changed, + Closed, + Switch + }; + + static int signalChoose(const string& key) { + static std::optional s_pid; + static int x{}; + static int y{}; + static int selected_signal = -1; + + if (!s_pid) { + s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid")); + } + + if (bg.empty()) selected_signal = -1; + auto& out = Global::overlay; + int retval = Changed; + + if (redraw) { + x = Term::width/2 - 40; + y = Term::height/2 - 9; + bg = Draw::createBox(x + 2, y, 78, 19, Theme::c("hi_fg"), true, "signals"); + bg += Mv::to(y+2, x+3) + Theme::c("title") + Fx::b + cjust("Send signal to PID " + to_string(s_pid.value()) + " (" + + uresize((s_pid == Config::getI("detailed_pid") ? Proc::detailed.entry.name : Config::getS("selected_name")), 30) + ")", 76); + } + else if (is_in(key, "escape", "q")) { + goto MenuClosing; + } + else if (key.starts_with("button_")) { + if (int new_select = stoi(key.substr(7)); new_select == selected_signal) + goto ChooseEntering; + else + selected_signal = new_select; + } + else if (is_in(key, "enter", "space") and selected_signal >= 0) { + ChooseEntering: + signalKillRet = 0; + if (s_pid < 1) { + signalKillRet = ESRCH; + menuMask.set(SignalReturn); + } + else if (kill(s_pid.value(), selected_signal) != 0) { + signalKillRet = errno; + menuMask.set(SignalReturn); + } + goto MenuClosing; + } + else if (key.size() == 1 and isdigit(key.at(0)) and selected_signal < 10) { + selected_signal = std::min(std::stoi((selected_signal < 1 ? key : to_string(selected_signal) + key)), 64); + } + else if (key == "backspace" and selected_signal != -1) { + selected_signal = (selected_signal < 10 ? -1 : selected_signal / 10); + } + else if (is_in(key, "up", "k") and selected_signal != 16) { + if (selected_signal == 1) selected_signal = 31; + else if (selected_signal < 6) selected_signal += 25; + else { + bool offset = (selected_signal > 16); + selected_signal -= 5; + if (selected_signal <= 16 and offset) selected_signal--; + } + } + else if (is_in(key, "down", "j")) { + if (selected_signal == 31) selected_signal = 1; + else if (selected_signal < 1 or selected_signal == 16) selected_signal = 1; + else if (selected_signal > 26) selected_signal -= 25; + else { + bool offset = (selected_signal < 16); + selected_signal += 5; + if (selected_signal >= 16 and offset) selected_signal++; + if (selected_signal > 31) selected_signal = 31; + } + } + else if (is_in(key, "left", "h") and selected_signal > 0 and selected_signal != 16) { + if (--selected_signal < 1) selected_signal = 31; + else if (selected_signal == 16) selected_signal--; + } + else if (is_in(key, "right", "l") and selected_signal <= 31 and selected_signal != 16) { + if (++selected_signal > 31) selected_signal = 1; + else if (selected_signal == 16) selected_signal++; + } + else { + retval = NoChange; + } + + if (retval == Changed) { + int cy = y+4, cx = x+4; + out = bg + Mv::to(cy++, x+3) + Theme::c("main_fg") + Fx::ub + + rjust("Enter signal number: ", 48) + Theme::c("hi_fg") + (selected_signal >= 0 ? to_string(selected_signal) : "") + Theme::c("main_fg") + Fx::bl + "█" + Fx::ubl; + + auto sig_str = to_string(selected_signal); + for (int count = 0, i = 0; const auto& sig : P_Signals) { + if (count == 0 or count == 16) { count++; continue; } + if (i++ % 5 == 0) { ++cy; cx = x+4; } + out += Mv::to(cy, cx); + if (count == selected_signal) out += Theme::c("selected_bg") + Theme::c("selected_fg") + Fx::b + ljust(to_string(count), 3) + ljust('(' + sig + ')', 12) + Fx::reset; + else out += Theme::c("hi_fg") + ljust(to_string(count), 3) + Theme::c("main_fg") + ljust('(' + sig + ')', 12); + if (redraw) mouse_mappings["button_" + to_string(count)] = {cy, cx, 1, 15}; + count++; + cx += 15; + } + + cy++; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust( "↑ ↓ ← →", 33, true) + Theme::c("main_fg") + Fx::ub + " | To choose signal."; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("0-9", 33) + Theme::c("main_fg") + Fx::ub + " | Enter manually."; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ENTER", 33) + Theme::c("main_fg") + Fx::ub + " | To send signal."; + mouse_mappings["enter"] = {cy, x, 1, 73}; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ESC or \"q\"", 33) + Theme::c("main_fg") + Fx::ub + " | To abort."; + mouse_mappings["escape"] = {cy, x, 1, 73}; + + out += Fx::reset; + } + + return (redraw ? Changed : retval); + + MenuClosing: + s_pid.reset(); + return Closed; + } + + static int sizeError(const string& key) { + if (redraw) { + vector cont_vec { + Fx::b + Theme::g("used")[100] + "Error:" + Theme::c("main_fg") + Fx::ub, + "Terminal size too small to" + Fx::reset, + "display menu or box!" + Fx::reset }; + + messageBox = Menu::msgBox{45, 0, cont_vec, "error"}; + Global::overlay = messageBox(); + } + + auto ret = messageBox.input(key); + if (ret == msgBox::Ok_Yes or ret == msgBox::No_Esc) { + messageBox.clear(); + return Closed; + } + else if (redraw) { + return Changed; + } + return NoChange; + } + + static int signalSend(const string& key) { + static std::optional s_pid; + + if (!s_pid) { + s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid")); + } + + if (redraw) { + atomic_wait(Runner::active); + auto& p_name = (s_pid == Config::getI("detailed_pid") ? Proc::detailed.entry.name : Config::getS("selected_name")); + vector cont_vec = { + Fx::b + Theme::c("main_fg") + "Send signal: " + Fx::ub + Theme::c("hi_fg") + to_string(signalToSend) + + (signalToSend > 0 and signalToSend <= 32 ? Theme::c("main_fg") + " (" + P_Signals.at(signalToSend) + ')' : ""), + + Fx::b + Theme::c("main_fg") + "To PID: " + Fx::ub + Theme::c("hi_fg") + to_string(s_pid.value()) + Theme::c("main_fg") + " (" + + uresize(p_name, 16) + ')' + Fx::reset, + }; + messageBox = Menu::msgBox{50, 1, cont_vec, (signalToSend > 1 and signalToSend <= 32 and signalToSend != 17 ? P_Signals.at(signalToSend) : "signal")}; + Global::overlay = messageBox(); + } + auto ret = messageBox.input(key); + if (ret == msgBox::Ok_Yes) { + signalKillRet = 0; + if (kill(s_pid.value(), signalToSend) != 0) { + signalKillRet = errno; + menuMask.set(SignalReturn); + } + messageBox.clear(); + goto MenuClosing; + } + else if (ret == msgBox::No_Esc) { + messageBox.clear(); + goto MenuClosing; + } + else if (ret == msgBox::Select) { + Global::overlay = messageBox(); + return Changed; + } + else if (redraw) { + return Changed; + } + return NoChange; + + MenuClosing: + s_pid.reset(); + return Closed; + } + + static int signalReturn(const string& key) { + if (redraw) { + vector cont_vec; + cont_vec.push_back(Fx::b + Theme::g("used")[100] + "Failure:" + Theme::c("main_fg") + Fx::ub); + if (signalKillRet == EINVAL) { + cont_vec.push_back("Unsupported signal!" + Fx::reset); + } + else if (signalKillRet == EPERM) { + cont_vec.push_back("Insufficient permissions to send signal!" + Fx::reset); + } + else if (signalKillRet == ESRCH) { + cont_vec.push_back("Process not found!" + Fx::reset); + } + else { + cont_vec.push_back("Unknown error! (errno: " + to_string(signalKillRet) + ')' + Fx::reset); + } + + messageBox = Menu::msgBox{50, 0, cont_vec, "error"}; + Global::overlay = messageBox(); + } + + auto ret = messageBox.input(key); + if (ret == msgBox::Ok_Yes or ret == msgBox::No_Esc) { + messageBox.clear(); + return Closed; + } + else if (redraw) { + return Changed; + } + return NoChange; + } + + static int mainMenu(const string& key) { + enum MenuItems { Options, Help, Quit }; + static int y{}; + static int selected{}; + static vector colors_selected; + static vector colors_normal; + auto tty_mode = Config::getB("tty_mode"); + if (bg.empty()) selected = 0; + int retval = Changed; + + if (redraw) { + y = Term::height/2 - 10; + bg = Draw::banner_gen(y, 0, true); + if (not tty_mode) { + colors_selected = { + Theme::hex_to_color(Global::Banner_src.at(0).at(0)), + Theme::hex_to_color(Global::Banner_src.at(2).at(0)), + Theme::hex_to_color(Global::Banner_src.at(4).at(0)) + }; + colors_normal = { + Theme::hex_to_color("#CC"), + Theme::hex_to_color("#AA"), + Theme::hex_to_color("#80") + }; + } + } + else if (is_in(key, "escape", "q", "m", "mouse_click")) { + return Closed; + } + else if (key.starts_with("button_")) { + if (int new_select = key.back() - '0'; new_select == selected) + goto MainEntering; + else + selected = new_select; + } + else if (is_in(key, "enter", "space")) { + MainEntering: + switch (selected) { + case Options: + menuMask.set(Menus::Options); + currentMenu = Menus::Options; + return Switch; + case Help: + menuMask.set(Menus::Help); + currentMenu = Menus::Help; + return Switch; + case Quit: + clean_quit(0); + } + } + else if (is_in(key, "down", "tab", "mouse_scroll_down", "j")) { + if (++selected > 2) selected = 0; + } + else if (is_in(key, "up", "shift_tab", "mouse_scroll_up", "k")) { + if (--selected < 0) selected = 2; + } + else { + retval = NoChange; + } + + if (retval == Changed) { + auto& out = Global::overlay; + out = bg + Fx::reset + Fx::b; + auto cy = y + 7; + for (const auto& i : iota(0, 3)) { + if (tty_mode) out += (i == selected ? Theme::c("hi_fg") : Theme::c("main_fg")); + const auto& menu = (not tty_mode and i == selected ? menu_selected[i] : menu_normal[i]); + const auto& colors = (i == selected ? colors_selected : colors_normal); + if (redraw) mouse_mappings["button_" + to_string(i)] = {cy, Term::width/2 - menu_width[i]/2, 3, menu_width[i]}; + for (int ic = 0; const auto& line : menu) { + out += Mv::to(cy++, Term::width/2 - menu_width[i]/2) + (tty_mode ? "" : colors[ic++]) + line; + } + } + out += Fx::reset; + } + + return (redraw ? Changed : retval); + } + +static int optionsMenu(const string& key) { + enum Predispositions { isBool, isInt, isString, is2D, isBrowsable, isEditable}; + static int y{}; + static int x{}; + static int height{}; + static int page{}; + static int pages{}; + static int selected{}; + static int select_max{}; + static int item_height{}; + static int selected_cat{}; + static int max_items{}; + static int last_sel{}; + static bool editing{}; + static Draw::TextEdit editor; + static string warnings; + static bitset<8> selPred; + static const std::unordered_map>> optionsList = { + {"color_theme", std::cref(Theme::themes)}, + {"log_level", std::cref(Logger::log_levels)}, + {"temp_scale", std::cref(Config::temp_scales)}, + #ifdef __linux__ + {"freq_mode", std::cref(Config::freq_modes)}, + #endif + {"proc_sorting", std::cref(Proc::sort_vector)}, + {"graph_symbol", std::cref(Config::valid_graph_symbols)}, + {"graph_symbol_cpu", std::cref(Config::valid_graph_symbols_def)}, + {"graph_symbol_mem", std::cref(Config::valid_graph_symbols_def)}, + {"graph_symbol_net", std::cref(Config::valid_graph_symbols_def)}, + {"graph_symbol_proc", std::cref(Config::valid_graph_symbols_def)}, + {"cpu_graph_upper", std::cref(Cpu::available_fields)}, + {"cpu_graph_lower", std::cref(Cpu::available_fields)}, + {"cpu_sensor", std::cref(Cpu::available_sensors)}, + {"selected_battery", std::cref(Config::available_batteries)}, + {"base_10_bitrate", std::cref(Config::base_10_bitrate_values)}, + {"disable_presets", std::cref(Config::disable_preset_options)}, + #ifdef GPU_SUPPORT + {"show_gpu_info", std::cref(Config::show_gpu_values)}, + {"graph_symbol_gpu", std::cref(Config::valid_graph_symbols_def)}, + #endif + }; + auto tty_mode = Config::getB("tty_mode"); + auto vim_keys = Config::getB("vim_keys"); + if (max_items == 0) { + for (const auto& cat : categories) { + if ((int)cat.size() > max_items) max_items = cat.size(); + } + } + if (bg.empty()) { + page = selected = selected_cat = last_sel = 0; + redraw = true; + Theme::updateThemes(); + } + int retval = Changed; + bool recollect{}; + bool screen_redraw{}; + bool theme_refresh{}; + + //? Draw background if needed else process input + if (redraw) { + mouse_mappings.clear(); + selPred.reset(); + y = max(1, Term::height/2 - 3 - max_items); + x = Term::width/2 - 39; + height = min(Term::height - 7, max_items * 2 + 4); + if (height % 2 != 0) height--; + bg = Draw::banner_gen(y, 0, true) + + Draw::createBox(x, y + 6, 78, height, Theme::c("hi_fg"), true, fmt::format("{}tab{}", Theme::c("hi_fg"), Theme::c("main_fg")) + Symbols::right) + + Mv::to(y+8, x) + Theme::c("hi_fg") + Symbols::div_left + Theme::c("div_line") + Symbols::h_line * 29 + + Symbols::div_up + Symbols::h_line * (78 - 32) + Theme::c("hi_fg") + Symbols::div_right + + Mv::to(y+6+height - 1, x+30) + Symbols::div_down + Theme::c("div_line"); + for (const auto& i : iota(0, height - 4)) { + bg += Mv::to(y+9 + i, x + 30) + Symbols::v_line; + } + } + else if (not warnings.empty() and not key.empty()) { + auto ret = messageBox.input(key); + if (ret == msgBox::msgReturn::Ok_Yes or ret == msgBox::msgReturn::No_Esc) { + warnings.clear(); + messageBox.clear(); + } + } + else if (editing and not key.empty()) { + if (is_in(key, "escape", "mouse_click")) { + editor.clear(); + editing = false; + } + else if (key == "enter") { + const auto& option = categories[selected_cat][item_height * page + selected][0]; + if (selPred.test(isString) and Config::stringValid(option, editor.text)) { + Config::set(option, editor.text); + if (option == "custom_cpu_name" or option.starts_with("custom_gpu_name")) + screen_redraw = true; + else if (is_in(option, "shown_boxes", "presets")) { + screen_redraw = true; + atomic_wait(Runner::active); + Config::current_preset.reset(); + } + else if (option == "clock_format") { + Draw::update_clock(true); + screen_redraw = true; + } + else if (option == "cpu_core_map") { + atomic_wait(Runner::active); + Cpu::core_mapping = Cpu::get_core_mapping(); + } + } + else if (selPred.test(isInt) and Config::intValid(option, editor.text)) { + Config::set(option, stoi(editor.text)); + } + else + warnings = Config::validError; + + editor.clear(); + editing = false; + } + else if (not editor.command(key)) + retval = NoChange; + } + else if (key == "mouse_click") { + const auto [mouse_x, mouse_y] = Input::mouse_pos; + if (mouse_x < x or mouse_x > x + 80 or mouse_y < y + 6 or mouse_y > y + 6 + height) { + return Closed; + } + else if (mouse_x < x + 30 and mouse_y > y + 8) { + auto m_select = ceil((double)(mouse_y - y - 8) / 2) - 1; + if (selected != m_select) + selected = m_select; + else if (selPred.test(isEditable)) + goto mouseEnter; + else retval = NoChange; + } + } + else if (is_in(key, "enter", "e", "E") and selPred.test(isEditable)) { + mouseEnter: + const auto& option = categories[selected_cat][item_height * page + selected][0]; + editor = Draw::TextEdit{Config::getAsString(option), selPred.test(isInt)}; + editing = true; + mouse_mappings.clear(); + } + else if (is_in(key, "escape", "q", "o", "backspace")) { + return Closed; + } + else if (is_in(key, "down", "mouse_scroll_down") or (vim_keys and key == "j")) { + if (++selected > select_max or selected >= item_height) { + if (page < pages - 1) page++; + else if (pages > 1) page = 0; + selected = 0; + } + } + else if (is_in(key, "up", "mouse_scroll_up") or (vim_keys and key == "k")) { + if (--selected < 0) { + if (page > 0) page--; + else if (pages > 1) page = pages - 1; + + selected = item_height - 1; + } + } + else if (pages > 1 and key == "page_down") { + if (++page >= pages) page = 0; + selected = 0; + last_sel = -1; + } + else if (pages > 1 and key == "page_up") { + if (--page < 0) page = pages - 1; + selected = 0; + last_sel = -1; + } + else if (key == "tab") { + if (++selected_cat >= (int)categories.size()) selected_cat = 0; + page = selected = 0; + } + else if (key == "shift_tab") { + if (--selected_cat < 0) selected_cat = (int)categories.size() - 1; + page = selected = 0; + } +#ifdef GPU_SUPPORT + else if (is_in(key, "1", "2", "3", "4", "5", "6") or key.starts_with("select_cat_")) { +#else + else if (is_in(key, "1", "2", "3", "4", "5") or key.starts_with("select_cat_")) { +#endif + selected_cat = key.back() - '0' - 1; + page = selected = 0; + } + else if (is_in(key, "left", "right") or (vim_keys and is_in(key, "h", "l"))) { + const auto& option = categories[selected_cat][item_height * page + selected][0]; + if (selPred.test(isInt)) { + const int mod = (option == "update_ms" ? 100 : 1); + long value = Config::getI(option); + if (key == "right" or (vim_keys and key == "l")) value += mod; + else value -= mod; + + if (Config::intValid(option, to_string(value))) + Config::set(option, static_cast(value)); + else { + warnings = Config::validError; + } + } + else if (selPred.test(isBool)) { + Config::flip(option); + screen_redraw = true; + + // Special handling for options that need additional action. + if (option == "truecolor") { + theme_refresh = true; + Config::flip("lowcolor"); + } + #if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__NetBSD__) + else if (option == "force_tty" and not Term::current_tty.starts_with("/dev/tty")) { + #else + else if (option == "force_tty") { + #endif + theme_refresh = true; + Config::set("tty_mode", Config::getB("force_tty")); + } + else if (is_in(option, "rounded_corners", "theme_background")) + theme_refresh = true; + else if (option == "background_update") { + Runner::pause_output = false; + } + else if (option == "base_10_sizes") { + recollect = true; + } + else if (option == "save_config_on_exit" and not Config::getB("save_config_on_exit")) { + const bool old_write_new = Config::write_new; + Config::write_new = true; + Config::write(); + Config::write_new = old_write_new; + } + else if (option == "disable_mouse") { + const auto is_mouse_enabled = !Config::getB("disable_mouse"); + std::cout << (is_mouse_enabled ? Term::mouse_on : Term::mouse_off) << std::flush; + } + } + else if (selPred.test(isBrowsable)) { + auto& optList = optionsList.at(option).get(); + int i = -1; + if (option == "color_theme") { + const auto current_theme = Config::getS(option); + const auto it = std::ranges::find_if(optList, [&](const auto& p) { + return (p == current_theme or fs::path(p).filename().string() == current_theme); + }); + if (it != optList.end()) i = std::distance(optList.begin(), it); + else i = optList.size(); + } + else { + i = v_index(optList, Config::getS(option)); + } + + if ((key == "right" or (vim_keys and key == "l")) and ++i >= (int)optList.size()) i = 0; + else if ((key == "left" or (vim_keys and key == "h")) and --i < 0) i = optList.size() - 1; + + if (option == "color_theme") { + const auto theme_path = fs::path(optList.at(i)); + const auto theme_filename = theme_path.filename().string(); + + //? Check if the selected theme is the first one that matches this filename (handling shadowing) + const auto first_match = std::ranges::find_if(optList, [&](const string& p) { + return fs::path(p).filename().string() == theme_filename; + }); + + if (first_match != optList.end() and *first_match == optList.at(i)) + Config::set(option, theme_filename); + else + Config::set(option, theme_path.string()); + + theme_refresh = true; + } + else { + Config::set(option, optList.at(i)); + + if (option == "log_level") { + Logger::set_log_level(optList.at(i)); + Logger::info("Logger set to {}", optList.at(i)); + } + else if (option == "base_10_bitrate") { + recollect = true; + } + else if (is_in(option, "proc_sorting", "cpu_sensor", "show_gpu_info") or option.starts_with("graph_symbol") or option.starts_with("cpu_graph_")) + screen_redraw = true; + else if (option == "disable_presets" and optList.at(i) != "Off") { + atomic_wait(Runner::active); + Config::current_preset.reset(); + } + } + } + else + retval = NoChange; + } + else { + retval = NoChange; + } + + //? Draw the menu + if (retval == Changed) { + Config::unlock(); + auto& out = Global::overlay; + out = bg; + item_height = min((int)categories[selected_cat].size(), (int)floor((double)(height - 4) / 2)); + pages = ceil((double)categories[selected_cat].size() / item_height); + if (page > pages - 1) page = pages - 1; + select_max = min(item_height - 1, (int)categories[selected_cat].size() - 1 - item_height * page); + if (selected > select_max) { + selected = select_max; + } + + //? Get variable properties for currently selected option + selPred.reset(); + last_sel = (selected_cat << 8) + selected; + const auto& selOption = categories[selected_cat][item_height * page + selected][0]; + if (Config::ints.contains(selOption)) + selPred.set(isInt); + else if (Config::bools.contains(selOption)) + selPred.set(isBool); + else + selPred.set(isString); + + if (not selPred.test(isString)) + selPred.set(is2D); + else if (optionsList.contains(selOption)) { + selPred.set(isBrowsable); + } + if (not selPred.test(isBrowsable) and (selPred.test(isString) or selPred.test(isInt))) + selPred.set(isEditable); + + //? Category buttons + out += Mv::to(y+7, x+4); + #ifdef GPU_SUPPORT + for (int i = 0; const auto& m : {"general", "cpu", "gpu", "mem", "net", "proc"}) { + #else + for (int i = 0; const auto& m : {"general", "cpu", "mem", "net", "proc"}) { + #endif + out += Fx::b + (i == selected_cat + ? Theme::c("hi_fg") + '[' + Theme::c("title") + m + Theme::c("hi_fg") + ']' + : Theme::c("hi_fg") + to_string(i + 1) + Theme::c("title") + m + ' ') + #ifdef GPU_SUPPORT + + Mv::r(7); + #else + + Mv::r(10); + #endif + +#if !defined(GPU_SUPPORT) + constexpr static auto option_menu_tab_width = 15; +#else + constexpr static auto option_menu_tab_width = 12; +#endif + if (const auto button_name = fmt::format("select_cat_{}", i + 1); not editing and not mouse_mappings.contains(button_name)) { + mouse_mappings[button_name] = { + .line = y + 6, + .col = x + 2 + (option_menu_tab_width * i), + .height = 3, + .width = option_menu_tab_width, + }; + } + i++; + } + if (pages > 1) { + out += Mv::to(y+6 + height - 1, x+2) + Theme::c("hi_fg") + Symbols::title_left_down + Fx::b + Symbols::up + Theme::c("title") + " page " + + to_string(page+1) + '/' + to_string(pages) + ' ' + Theme::c("hi_fg") + Symbols::down + Fx::ub + Symbols::title_right_down; + } + //? Option name and value + auto cy = y+9; + for (int c = 0, i = max(0, item_height * page); c++ < item_height and i < (int)categories[selected_cat].size(); i++) { + const auto& option = categories[selected_cat][i][0]; + const auto& value = (option == "color_theme" ? fs::path(Config::getS("color_theme")).stem().string() : Config::getAsString(option)); + + string idx_str; + if (c-1 == selected and selPred.test(isBrowsable)) { + const auto& optList = optionsList.at(option).get(); + int idx = 0; + if (option == "color_theme") { + const auto current_theme = Config::getS(option); + const auto current_theme_path = fs::path(current_theme); + const auto it = std::ranges::find_if(optList, [&](const string& p) { + const auto p_path = fs::path(p); + //? Match against full path, filename, stem or legacy absolute path + return p == current_theme + or p_path.filename() == current_theme + or p_path.stem() == current_theme + or (current_theme_path.is_absolute() and current_theme_path.filename() == p_path.filename()); + }); + if (it != optList.end()) idx = std::distance(optList.begin(), it); + else idx = optList.size(); + } else { + idx = v_index(optList, value); + } + idx_str = " " + to_string(idx + 1) + '/' + to_string(optList.size()); + } + + out += Mv::to(cy++, x + 1) + (c-1 == selected ? Theme::c("selected_bg") + Theme::c("selected_fg") : Theme::c("title")) + + Fx::b + cjust(capitalize(s_replace(option, "_", " ")) + idx_str, 29); + out += Mv::to(cy++, x + 1) + (c-1 == selected ? "" : Theme::c("main_fg")) + Fx::ub + " " + + (c-1 == selected and editing ? cjust(editor(24), 34, true) : cjust(value, 25, true)) + " "; + + if (c-1 == selected) { + if (not editing and (selPred.test(is2D) or selPred.test(isBrowsable))) { + out += Fx::b + Mv::to(cy-1, x+2) + Symbols::left + Mv::to(cy-1, x+28) + Symbols::right; + mouse_mappings["left"] = {cy-2, x, 2, 5}; + mouse_mappings["right"] = {cy-2, x+25, 2, 5}; + } + if (selPred.test(isEditable)) { + out += Fx::b + Mv::to(cy-1, x+28 - (not editing and selPred.test(isInt) ? 2 : 0)) + (tty_mode ? "E" : Symbols::enter); + } + //? Description of selected option + out += Fx::reset + Theme::c("title") + Fx::b; + for (int cyy = y+7; const auto& desc : categories[selected_cat][i]) { + if (cyy++ == y+7) continue; + else if (cyy == y+10) out += Theme::c("main_fg") + Fx::ub; + else if (cyy > y + height + 4) break; + out += Mv::to(cyy, x+32) + desc; + } + } + } + + if (not warnings.empty()) { + messageBox = msgBox{min(78, (int)ulen(warnings) + 10), msgBox::BoxTypes::OK, {uresize(warnings, 74)}, "warning"}; + out += messageBox(); + } + + out += Fx::reset; + } + + if (theme_refresh) { + Theme::setTheme(); + Draw::banner_gen(0, 0, false, true); + screen_redraw = true; + redraw = true; + optionsMenu(""); + } + if (screen_redraw) { + auto overlay_bkp = std::move(Global::overlay); + auto clock_bkp = std::move(Global::clock); + Draw::calcSizes(); + Global::overlay = std::move(overlay_bkp); + Global::clock = std::move(clock_bkp); + recollect = true; + } + if (recollect) { + Runner::run("all", false, true); + retval = NoChange; + } + + return (redraw ? Changed : retval); + } + + static int helpMenu(const string& key) { + static int y{}; + static int x{}; + static int height{}; + static int page{}; + static int pages{}; + + if (bg.empty()) page = 0; + int retval = Changed; + + if (redraw) { + y = max(1, Term::height/2 - 4 - (int)(help_text.size() / 2)); + x = Term::width/2 - 39; + height = min(Term::height - 6, (int)help_text.size() + 3); + pages = ceil((double)help_text.size() / (height - 3)); + page = 0; + bg = Draw::banner_gen(y, 0, true); + bg += Draw::createBox(x, y + 6, 78, height, Theme::c("hi_fg"), true, "help"); + } + else if (is_in(key, "escape", "q", "h", "backspace", "space", "enter", "mouse_click")) { + return Closed; + } + else if (pages > 1 and is_in(key, "down", "j", "page_down", "tab", "mouse_scroll_down")) { + if (++page >= pages) page = 0; + } + else if (pages > 1 and is_in(key, "up", "k", "page_up", "shift_tab", "mouse_scroll_up")) { + if (--page < 0) page = pages - 1; + } + else { + retval = NoChange; + } + + + if (retval == Changed) { + auto& out = Global::overlay; + out = bg; + if (pages > 1) { + out += Mv::to(y+height+6, x + 2) + Theme::c("hi_fg") + Symbols::title_left_down + Fx::b + Symbols::up + Theme::c("title") + " page " + + to_string(page+1) + '/' + to_string(pages) + ' ' + Theme::c("hi_fg") + Symbols::down + Fx::ub + Symbols::title_right_down; + } + auto cy = y+7; + out += Mv::to(cy++, x + 1) + Theme::c("title") + Fx::b + cjust("Key:", 20) + "Description:"; + for (int c = 0, i = max(0, (height - 3) * page); c++ < height - 3 and i < (int)help_text.size(); i++) { + out += Mv::to(cy++, x + 1) + Theme::c("hi_fg") + Fx::b + cjust(help_text[i][0], 20) + + Theme::c("main_fg") + Fx::ub + help_text[i][1]; + } + out += Fx::reset; + } + + + return (redraw ? Changed : retval); + } + + static int reniceMenu(const string& key) { + static std::optional s_pid; + static int x{}; + static int y{}; + static int selected_nice = 0; + static string nice_edit; + + if (!s_pid) { + s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid")); + } + + if (bg.empty()) { + selected_nice = 0; + nice_edit.clear(); + } + auto& out = Global::overlay; + int retval = Changed; + + if (redraw) { + x = Term::width/2 - 25; + y = Term::height/2 - 6; + bg = Draw::createBox(x + 2, y, 50, 13, Theme::c("hi_fg"), true, "renice"); + bg += Mv::to(y+2, x+3) + Theme::c("title") + Fx::b + cjust("Renice PID " + to_string(s_pid.value()) + " (" + + uresize((s_pid == Config::getI("detailed_pid") ? Proc::detailed.entry.name : Config::getS("selected_name")), 15) + ")", 48); + } + else if (is_in(key, "escape", "q")) { + goto MenuClosing; + } + else if (is_in(key, "enter", "space")) { + if (s_pid > 0) { + if (not nice_edit.empty()) { + try { + selected_nice = stoi(nice_edit); + } + catch (...) { selected_nice = 0; } + } + if (not Proc::set_priority(s_pid.value(), selected_nice)) { + // TODO: show error message + } + } + goto MenuClosing; + } + else if (key.size() == 1 and (isdigit(key.at(0)) or (key.at(0) == '-' and nice_edit.empty()))) { + nice_edit += key; + } + else if (key == "backspace" and not nice_edit.empty()) { + nice_edit.pop_back(); + } + else if (is_in(key, "up", "k")) { + if (++selected_nice > 19) selected_nice = -20; + nice_edit.clear(); + } + else if (is_in(key, "down", "j")) { + if (--selected_nice < -20) selected_nice = 19; + nice_edit.clear(); + } + else if (is_in(key, "left", "h")) { + if ((selected_nice -= 5) < -20) selected_nice += 40; + nice_edit.clear(); + } + else if (is_in(key, "right", "l")) { + if ((selected_nice += 5) > 19) selected_nice -= 40; + nice_edit.clear(); + } + else { + retval = NoChange; + } + + if (retval == Changed) { + int cy = y+4; + if (not nice_edit.empty()) { + try { + selected_nice = stoi(nice_edit); + } + catch (...) { selected_nice = 0; } + } + out = bg + Mv::to(cy++, x+3) + Theme::c("main_fg") + Fx::ub + + rjust("Enter nice value: ", 30) + Theme::c("hi_fg") + (nice_edit.empty() ? to_string(selected_nice) : nice_edit) + Theme::c("main_fg") + Fx::bl + "█" + Fx::ubl; + + cy++; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust( "↑ ↓", 20, true) + Theme::c("main_fg") + Fx::ub + " | To change value."; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust( "← →", 20, true) + Theme::c("main_fg") + Fx::ub + " | To change value by 5."; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("0-9", 20) + Theme::c("main_fg") + Fx::ub + " | Enter manually."; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ENTER", 20) + Theme::c("main_fg") + Fx::ub + " | To set nice value."; + out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ESC or 'q'", 20) + Theme::c("main_fg") + Fx::ub + " | To abort."; + + out += Fx::reset; + } + + return (redraw ? Changed : retval); + + MenuClosing: + s_pid.reset(); + return Closed; + } + + //* Add menus here and update enum Menus in header + const auto menuFunc = vector{ + ref(sizeError), + ref(signalChoose), + ref(signalSend), + ref(signalReturn), + ref(optionsMenu), + ref(helpMenu), + ref(reniceMenu), + ref(mainMenu), + }; + bitset<8> menuMask; + + void process(const std::string_view key) { + if (menuMask.none()) { + Menu::active = false; + Global::overlay.clear(); + Global::overlay.shrink_to_fit(); + Runner::pause_output = false; + bg.clear(); + bg.shrink_to_fit(); + currentMenu = -1; + Runner::run("all", true, true); + mouse_mappings.clear(); + return; + } + + if (currentMenu < 0 or not menuMask.test(currentMenu)) { + Menu::active = true; + redraw = true; + if (((menuMask.test(Main) or menuMask.test(Options) or menuMask.test(Help) or menuMask.test(SignalChoose)) + and (Term::width < 80 or Term::height < 24)) + or (Term::width < 50 or Term::height < 20)) { + menuMask.reset(); + menuMask.set(SizeError); + } + + for (const auto& i : iota(0, (int)menuMask.size())) { + if (menuMask.test(i)) currentMenu = i; + } + + } + + auto retCode = menuFunc.at(currentMenu)(key.data()); + if (retCode == Closed) { + menuMask.reset(currentMenu); + mouse_mappings.clear(); + bg.clear(); + Runner::pause_output = false; + process(); + } + else if (redraw) { + redraw = false; + Runner::run("all", true, true); + } + else if (retCode == Changed) + Runner::run("overlay"); + else if (retCode == Switch) { + Runner::pause_output = false; + bg.clear(); + redraw = true; + mouse_mappings.clear(); + process(); + } + } + + void show(int menu, int signal) { + menuMask.set(menu); + signalToSend = signal; + process(); + } +} diff --git a/vendor/btop/src/btop_menu.hpp b/vendor/btop/src/btop_menu.hpp new file mode 100644 index 000000000..09deabddc --- /dev/null +++ b/vendor/btop/src/btop_menu.hpp @@ -0,0 +1,99 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#include +#include +#include +#include +#include + +#include "btop_input.hpp" + +using std::atomic; +using std::bitset; +using std::string; +using std::vector; + +namespace Menu { + + extern atomic active; + extern string output; + extern int signalToSend; + extern bool redraw; + + //? line, col, height, width + extern std::unordered_map mouse_mappings; + + //* Creates a message box centered on screen + //? Height of box is determined by size of content vector + //? Boxtypes: 0 = OK button | 1 = YES and NO with YES selected | 2 = Same as 1 but with NO selected + //? Strings in content vector is not checked for box width overflow + class msgBox { + string box_contents, button_left, button_right; + int height{}; + int width{}; + int boxtype{}; + int selected{}; + int x{}; + int y{}; + public: + enum BoxTypes { OK, YES_NO, NO_YES }; + enum msgReturn { + Invalid, + Ok_Yes, + No_Esc, + Select + }; + msgBox(); + msgBox(int width, int boxtype, const vector& content, std::string_view title); + + //? Draw and return box as a string + string operator()(); + + //? Process input and returns value from enum Ret + int input(const string& key); + + //? Clears content vector and private strings + void clear(); + int getX() const { return x; } + int getY() const { return y; } + }; + + extern bitset<8> menuMask; + + //* Enum for functions in vector menuFuncs + enum Menus { + SizeError, + SignalChoose, + SignalSend, + SignalReturn, + Options, + Help, + Renice, + Main + }; + + //* Handles redirection of input for menu functions and handles return codes + void process(const std::string_view key = ""); + + //* Show a menu from enum Menu::Menus + void show(int menu, int signal=-1); + +} diff --git a/vendor/btop/src/btop_shared.cpp b/vendor/btop/src/btop_shared.cpp new file mode 100644 index 000000000..55490161e --- /dev/null +++ b/vendor/btop/src/btop_shared.cpp @@ -0,0 +1,360 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#include +#include +#include +#include +#include +#include + +#include "btop_config.hpp" +#include "btop_shared.hpp" +#include "btop_tools.hpp" + +namespace fs = std::filesystem; +namespace rng = std::ranges; +using namespace Tools; + +namespace Cpu { + std::optional container_engine; + + string trim_name(string name) { + auto name_vec = ssplit(name); + + if ((name.contains("Xeon") or v_contains(name_vec, "Duo"s)) and v_contains(name_vec, "CPU"s)) { + auto cpu_pos = v_index(name_vec, "CPU"s); + if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')')) + name = name_vec.at(cpu_pos + 1); + else + name.clear(); + } else if (v_contains(name_vec, "Ryzen"s)) { + auto ryz_pos = v_index(name_vec, "Ryzen"s); + name = "Ryzen"; + int tokens = 0; + for (auto i = ryz_pos + 1; i < name_vec.size() && tokens < 2; i++) { + const std::string& p = name_vec.at(i); + if (p != "AI" && p != "PRO" && p != "H" && p != "HX") + tokens++; + name += " " + p; + } + } else if (name.contains("Intel") and v_contains(name_vec, "CPU"s)) { + auto cpu_pos = v_index(name_vec, "CPU"s); + if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')') and name_vec.at(cpu_pos + 1) != "@") + name = name_vec.at(cpu_pos + 1); + else + name.clear(); + } else + name.clear(); + + if (name.empty() and not name_vec.empty()) { + for (const auto &n : name_vec) { + if (n == "@") break; + name += n + ' '; + } + name.pop_back(); + for (const auto& replace : {"Processor", "CPU", "(R)", "(TM)", "Intel", "AMD", "Apple", "Core"}) { + name = s_replace(name, replace, ""); + name = s_replace(name, " ", " "); + } + name = trim(name); + } + + return name; + } +} + +#ifdef GPU_SUPPORT +namespace Gpu { + vector gpu_names; + vector gpu_b_height_offsets; + std::unordered_map> shared_gpu_percent = { + {"gpu-average", {}}, + {"gpu-vram-total", {}}, + {"gpu-pwr-total", {}}, + }; + long long gpu_pwr_total_max = 0; +} +#endif + +namespace Proc { +bool set_priority(pid_t pid, int priority) { + if (setpriority(PRIO_PROCESS, pid, priority) == 0) { + return true; + } + return false; +} + + void proc_sorter(vector& proc_vec, const string& sorting, bool reverse, bool tree) { + if (reverse) { + switch (v_index(sort_vector, sorting)) { + case 0: rng::stable_sort(proc_vec, rng::less{}, &proc_info::pid); break; + case 1: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::name); break; + case 2: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cmd); break; + case 3: rng::stable_sort(proc_vec, rng::less{}, &proc_info::threads); break; + case 4: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::user); break; + case 5: rng::stable_sort(proc_vec, rng::less{}, &proc_info::mem); break; + case 6: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_p); break; + case 7: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_c); break; + } + } + else { + switch (v_index(sort_vector, sorting)) { + case 0: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::pid); break; + case 1: rng::stable_sort(proc_vec, rng::less{}, &proc_info::name); break; + case 2: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cmd); break; + case 3: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::threads); break; + case 4: rng::stable_sort(proc_vec, rng::less{}, &proc_info::user); break; + case 5: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::mem); break; + case 6: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_p); break; + case 7: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_c); break; + } + } + + //* When sorting with "cpu lazy" push processes over threshold cpu usage to the front regardless of cumulative usage + if (not tree and not reverse and sorting == "cpu lazy") { + double max = 10.0, target = 30.0; + for (size_t i = 0, x = 0, offset = 0; i < proc_vec.size(); i++) { + if (i <= 5 and proc_vec.at(i).cpu_p > max) + max = proc_vec.at(i).cpu_p; + else if (i == 6) + target = (max > 30.0) ? max : 10.0; + if (i == offset and proc_vec.at(i).cpu_p > 30.0) + offset++; + else if (proc_vec.at(i).cpu_p > target) { + rotate(proc_vec.begin() + offset, proc_vec.begin() + i, proc_vec.begin() + i + 1); + if (++x > 10) break; + } + } + } + } + + void tree_sort(vector& proc_vec, const string& sorting, bool reverse, bool paused, int& c_index, const int index_max, bool collapsed) { + if (proc_vec.size() > 1 and not paused) { + if (reverse) { + switch (v_index(sort_vector, sorting)) { + case 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads < b.entry.get().threads; }); break; + case 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem < b.entry.get().mem; }); break; + case 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p < b.entry.get().cpu_p; }); break; + case 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c < b.entry.get().cpu_c; }); break; + } + } + else { + switch (v_index(sort_vector, sorting)) { + case 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads > b.entry.get().threads; }); break; + case 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem > b.entry.get().mem; }); break; + case 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p > b.entry.get().cpu_p; }); break; + case 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c > b.entry.get().cpu_c; }); break; + } + } + } + + for (auto& r : proc_vec) { + r.entry.get().tree_index = (collapsed or r.entry.get().filtered ? index_max : c_index++); + if (not r.children.empty()) { + tree_sort(r.children, sorting, reverse, paused, c_index, (collapsed or r.entry.get().collapsed or r.entry.get().tree_index == (size_t)index_max)); + } + } + } + + auto matches_filter(const proc_info& proc, const std::string& filter) -> bool { + if (filter.starts_with("!")) { + if (filter.size() == 1) { + return true; + } + + // An incomplete regex throws, see issue https://github.com/aristocratos/btop/issues/1133 + try { + std::regex regex { filter.substr(1), std::regex::extended }; + return std::regex_search(std::to_string(proc.pid), regex) || std::regex_search(proc.name, regex) || + std::regex_match(proc.cmd, regex) || std::regex_search(proc.user, regex); + } catch (std::regex_error& /* unused */) { + return false; + } + } + + return std::to_string(proc.pid).contains(filter) || s_contains_ic(proc.name, filter) || + s_contains_ic(proc.cmd, filter) || s_contains_ic(proc.user, filter); + } + + void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, + int cur_depth, bool collapsed, const string& filter, bool found, bool no_update, bool should_filter) { + bool filtering = false; + + //? If filtering, include children of matching processes + if (not found and (should_filter or not filter.empty())) { + if (!matches_filter(cur_proc, filter)) { + filtering = true; + cur_proc.filtered = true; + filter_found++; + } + else { + found = true; + cur_depth = 0; + } + } + else if (cur_proc.filtered) cur_proc.filtered = false; + + cur_proc.depth = cur_depth; + + //? Set tree index position for process if not filtered out or currently in a collapsed sub-tree + out_procs.push_back({ cur_proc, {} }); + if (not collapsed and not filtering) { + cur_proc.tree_index = out_procs.size() - 1; + + //? Try to find name of the binary file and append to program name if not the same + if (cur_proc.short_cmd.empty() and not cur_proc.cmd.empty()) { + std::string_view cmd_view = cur_proc.cmd; + cmd_view = cmd_view.substr((size_t)0, std::min(cmd_view.find(' '), cmd_view.size())); + cmd_view = cmd_view.substr(std::min(cmd_view.find_last_of('/') + 1, cmd_view.size())); + cur_proc.short_cmd = string{cmd_view}; + } + } + else { + cur_proc.tree_index = in_procs.size(); + } + + //? Recursive iteration over all children + for (auto& p : rng::equal_range(in_procs, cur_proc.pid, rng::less{}, &proc_info::ppid)) { + if (collapsed and not filtering) { + cur_proc.filtered = true; + } + + _tree_gen(p, in_procs, out_procs.back().children, cur_depth + 1, (collapsed or cur_proc.collapsed), filter, found, no_update, should_filter); + + if (not no_update and not filtering and (collapsed or cur_proc.collapsed)) { + //auto& parent = cur_proc; + if (p.state != 'X') { + cur_proc.cpu_p += p.cpu_p; + cur_proc.cpu_c += p.cpu_c; + cur_proc.mem += p.mem; + cur_proc.threads += p.threads; + } + filter_found++; + p.filtered = true; + } + else if (not no_update and Config::getB("proc_aggregate") and p.state != 'X') { + cur_proc.cpu_p += p.cpu_p; + cur_proc.cpu_c += p.cpu_c; + cur_proc.mem += p.mem; + cur_proc.threads += p.threads; + } + } + } + + void _collect_prefixes(tree_proc &t, const bool is_last, const string &header) { + const bool is_filtered = t.entry.get().filtered; + if (is_filtered) t.entry.get().depth = 0; + + if (!t.children.empty()) t.entry.get().prefix = header + (t.entry.get().collapsed ? "[+]─": "[-]─"); + else t.entry.get().prefix = header + (is_last ? " └─": " ├─"); + + for (auto child = t.children.begin(); child != t.children.end(); ++child) { + _collect_prefixes(*child, child == (t.children.end() - 1), + is_filtered ? "": header + (is_last ? " ": " │ ")); + } + } + + void toggle_tree_collapse(std::vector& current_procs) { + //? Build sets of all pids and parent pids to identify root processes + std::unordered_set pid_set, parent_pids; + for (const auto& p : current_procs) { + pid_set.insert(p.pid); + parent_pids.insert(static_cast(p.ppid)); + } + //? If any non-root parent is expanded, collapse; otherwise expand + const bool do_collapse = rng::any_of(current_procs, [&parent_pids, &pid_set](const proc_info& p) { + return parent_pids.contains(p.pid) + and pid_set.contains(static_cast(p.ppid)) + and not p.collapsed; + }); + //? Root processes (parent not in tracked list) are never touched + for (auto& p : current_procs) { + if (not pid_set.contains(static_cast(p.ppid))) continue; + p.collapsed = do_collapse; + } + } + + void _auto_collapse_oversized(std::vector& current_procs, const bool tree_mode_change) { + //? Only act when the user just switched into tree view + const int threshold = Config::getI("proc_tree_auto_collapse"); + if (threshold <= 0 or not tree_mode_change) return; + //? Never collapse the root process or its direct children, only deeper busy parents + const size_t root_ppid = static_cast(current_procs.at(0).ppid); + std::unordered_set root_pids; + for (const auto& p : current_procs) { + if (static_cast(p.ppid) == root_ppid) root_pids.insert(p.pid); + } + for (auto& p : current_procs) { + if (static_cast(p.ppid) == root_ppid or root_pids.contains(static_cast(p.ppid))) continue; + if (rng::count(current_procs, p.pid, &proc_info::ppid) >= threshold) { + p.collapsed = true; + } + } + } +} + +auto detect_container() -> std::optional { + std::error_code err; + + if (fs::exists(fs::path("/run/.containerenv"), err)) { + return std::make_optional(std::string { "podman" }); + } + if (fs::exists(fs::path("/.dockerenv"), err)) { + return std::make_optional(std::string { "docker" }); + } + auto systemd_container = fs::path("/run/systemd/container"); + if (fs::exists(systemd_container, err)) { + auto stream = std::ifstream { systemd_container }; + auto buf = std::string {}; + stream >> buf; + return std::make_optional(buf); + } + + return std::nullopt; +} + +#if defined(GPU_SUPPORT) +const array Gpu::mem_names { "used", "free" }; +#endif + +const vector Proc::sort_vector = { + "pid", + "name", + "command", + "threads", + "user", + "memory", + "cpu direct", + "cpu lazy", +}; + +const std::unordered_map Proc::proc_states = { + {'R', "Running"}, + {'S', "Sleeping"}, + {'D', "Waiting"}, + {'Z', "Zombie"}, + {'T', "Stopped"}, + {'t', "Tracing"}, + {'X', "Dead"}, + {'x', "Dead"}, + {'K', "Wakekill"}, + {'W', "Unknown"}, + {'P', "Parked"} +}; diff --git a/vendor/btop/src/btop_shared.hpp b/vendor/btop/src/btop_shared.hpp new file mode 100644 index 000000000..0abd18c60 --- /dev/null +++ b/vendor/btop/src/btop_shared.hpp @@ -0,0 +1,462 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// From `man 3 getifaddrs`: must be included before +// clang-format off +#include +#include +// clang-format on + +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) +# include +#endif + +using std::array; +using std::atomic; +using std::deque; +using std::string; +using std::tuple; +using std::vector; + +using namespace std::literals; // for operator""s + +namespace Tools { + class atomic_waiting_lock; +} + +void term_resize(bool force=false); +void banner_gen(); + +extern void clean_quit(int sig); + +namespace Global { + extern const vector> Banner_src; + extern const string Version; + extern atomic quitting; + extern string exit_error_msg; + extern atomic thread_exception; + extern string banner; + extern atomic resized; + extern string overlay; + extern string clock; + extern uid_t real_uid, set_uid; + extern atomic init_conf; +} + +namespace Runner { + extern Tools::atomic_waiting_lock active; + extern atomic reading; + extern atomic stopping; + extern atomic redraw; + extern atomic coreNum_reset; + extern bool pause_output; + extern string debug_bg; + + void run(const string& box = "", bool no_update = false, bool force_redraw = false); + void stop(); +} + +namespace Tools { + //* Platform specific function for system_uptime (seconds since last restart) + double system_uptime(); +} + +namespace Shared { + //* Initialize platform specific needed variables and check for errors + void init(); + + extern long coreCount, page_size, clk_tck; + +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) + struct KvmDeleter { + void operator()(kvm_t* handle) { + kvm_close(handle); + } + }; + using KvmPtr = std::unique_ptr; +#endif +} + +#if defined(GPU_SUPPORT) + +namespace Gpu { + extern vector box; + extern int width, total_height, min_width, min_height; + extern vector x_vec, y_vec; + extern vector redraw; + extern int shown; + extern int count; + extern vector shown_panels; + extern vector gpu_names; + extern vector gpu_b_height_offsets; + extern long long gpu_pwr_total_max; + + extern std::unordered_map> shared_gpu_percent; // averages, power/vram total + + extern const array mem_names; + + //* Container for process information // TODO + /*struct proc_info { + unsigned int pid; + unsigned long long mem; + };*/ + + //* Container for supported Gpu::*::collect() functions + struct gpu_info_supported { + bool gpu_utilization = true, + mem_utilization = true, + gpu_clock = true, + mem_clock = true, + pwr_usage = true, + pwr_state = true, + temp_info = true, + mem_total = true, + mem_used = true, + pcie_txrx = true, + encoder_utilization = true, + decoder_utilization = true; + }; + + //* Per-device container for GPU info + struct gpu_info { + std::unordered_map> gpu_percent = { + {"gpu-totals", {}}, + {"gpu-vram-totals", {}}, + {"gpu-pwr-totals", {}}, + }; + unsigned int gpu_clock_speed; // MHz + + long long pwr_usage; // mW + long long pwr_max_usage = 255000; + long long pwr_state; + + deque temp = {0}; + long long temp_max = 110; + + long long mem_total = 0; + long long mem_used = 0; + deque mem_utilization_percent = {0}; // TODO: properly handle GPUs that can't report some stats + long long mem_clock_speed = 0; // MHz + + long long pcie_tx = 0; // KB/s + long long pcie_rx = 0; + + long long encoder_utilization = 0; + long long decoder_utilization = 0; + + gpu_info_supported supported_functions; + + // vector graphics_processes = {}; // TODO + // vector compute_processes = {}; + }; + + namespace Nvml { + extern bool shutdown(); + } + namespace Rsmi { + extern bool shutdown(); + } + namespace Asysfs { + extern bool shutdown(); + } + #ifdef __APPLE__ + namespace AppleSilicon { + extern bool shutdown(); + } + #endif + + //* Collect gpu stats and temperatures + auto collect(bool no_update = false) -> vector&; + + //* Draw contents of gpu box using as source + string draw(const gpu_info& gpu, unsigned long index, bool force_redraw, bool data_same); +} + +#endif // GPU_SUPPORT + +namespace Cpu { + extern string box; + extern int x, y, width, height, min_width, min_height; + extern bool shown, redraw, got_sensors, cpu_temp_only, has_battery, supports_watts; + extern string cpuName, cpuHz; + extern vector available_fields; + extern vector available_sensors; + extern tuple current_bat; + extern std::optional container_engine; + + struct cpu_info { + std::unordered_map> cpu_percent = { + {"total", {}}, + {"user", {}}, + {"nice", {}}, + {"system", {}}, + {"idle", {}}, + {"iowait", {}}, + {"irq", {}}, + {"softirq", {}}, + {"steal", {}}, + {"guest", {}}, + {"guest_nice", {}} + }; + vector> core_percent; + vector> temp; + long long temp_max = 0; + array load_avg; + float usage_watts = 0; + std::optional> active_cpus; + }; + + //* Collect cpu stats and temperatures + auto collect(bool no_update = false) -> cpu_info&; + + //* Draw contents of cpu box using as source + string draw( + const cpu_info& cpu, +#if defined(GPU_SUPPORT) + const vector& gpu, +#endif + bool force_redraw = false, + bool data_same = false + ); + + //* Parse /proc/cpu info for mapping of core ids + auto get_core_mapping() -> std::unordered_map; + extern std::unordered_map core_mapping; + + auto get_cpuHz() -> string; + + //* Get battery info from /sys + auto get_battery() -> tuple; + + string trim_name(string); +} + +namespace Mem { + extern string box; + extern int x, y, width, height, min_width, min_height; + extern bool has_swap, shown, redraw; + const array mem_names { "used"s, "available"s, "cached"s, "free"s }; + const array swap_names { "swap_used"s, "swap_free"s }; + extern int disk_ios; + + struct disk_info { + std::filesystem::path dev; + string name; + string fstype{}; // defaults to "" + std::filesystem::path stat{}; // defaults to "" + int64_t total{}; + int64_t used{}; + int64_t free{}; + int used_percent{}; + int free_percent{}; + + array old_io = {0, 0, 0}; + deque io_read = {}; + deque io_write = {}; + deque io_activity = {}; + }; + + struct mem_info { + std::unordered_map stats = + {{"used", 0}, {"available", 0}, {"cached", 0}, {"free", 0}, + {"swap_total", 0}, {"swap_used", 0}, {"swap_free", 0}}; + std::unordered_map> percent = + {{"used", {}}, {"available", {}}, {"cached", {}}, {"free", {}}, + {"swap_total", {}}, {"swap_used", {}}, {"swap_free", {}}}; + std::unordered_map disks; + vector disks_order; + }; + + //?* Get total system memory + uint64_t get_totalMem(); + + //* Collect mem & disks stats + auto collect(bool no_update = false) -> mem_info&; + + //* Draw contents of mem box using as source + string draw(const mem_info& mem, bool force_redraw = false, bool data_same = false); + +} + +namespace Net { + extern string box; + extern int x, y, width, height, min_width, min_height; + extern bool shown, redraw; + extern string selected_iface; + extern vector interfaces; + extern bool rescale; + extern std::unordered_map graph_max; + + struct net_stat { + uint64_t speed{}; + uint64_t top{}; + uint64_t total{}; + uint64_t last{}; + uint64_t offset{}; + uint64_t rollover{}; + }; + + struct net_info { + std::unordered_map> bandwidth = { {"download", {}}, {"upload", {}} }; + std::unordered_map stat = { {"download", {}}, {"upload", {}} }; + string ipv4{}; // defaults to "" + string ipv6{}; // defaults to "" + bool connected{}; + }; + + class IfAddrsPtr { + struct ifaddrs* ifaddr; + int status; + public: + IfAddrsPtr() { status = getifaddrs(&ifaddr); } + ~IfAddrsPtr() noexcept { freeifaddrs(ifaddr); } + IfAddrsPtr(const IfAddrsPtr &) = delete; + IfAddrsPtr& operator=(IfAddrsPtr& other) = delete; + IfAddrsPtr(IfAddrsPtr &&) = delete; + IfAddrsPtr& operator=(IfAddrsPtr&& other) = delete; + [[nodiscard]] constexpr auto operator()() -> struct ifaddrs* { return ifaddr; } + [[nodiscard]] constexpr auto get() -> struct ifaddrs* { return ifaddr; } + [[nodiscard]] constexpr auto get_status() const noexcept -> int { return status; }; + }; + + extern std::unordered_map current_net; + + //* Collect net upload/download stats + auto collect(bool no_update=false) -> net_info&; + + //* Draw contents of net box using as source + string draw(const net_info& net, bool force_redraw = false, bool data_same = false); +} + +namespace Proc { + extern atomic numpids; + + extern string box; + extern int x, y, width, height, min_width, min_height; + extern bool shown, redraw; + extern int select_max; + extern atomic detailed_pid; + extern int selected_pid, start, selected, collapse, expand, filter_found, selected_depth, toggle_children, collapse_all; + extern int scroll_pos; + extern string selected_name; + extern atomic resized; + + //? Contains the valid sorting options for processes + extern const vector sort_vector; + + //? Translation from process state char to explanative string + extern const std::unordered_map proc_states; + + //* Container for process information + struct proc_info { + size_t pid{}; + string name{}; // defaults to "" + string cmd{}; // defaults to "" + string short_cmd{}; // defaults to "" + size_t threads{}; + int name_offset{}; + string user{}; // defaults to "" + uint64_t mem{}; + double cpu_p{}; // defaults to = 0.0 + double cpu_c{}; // defaults to = 0.0 + char state = '0'; + int64_t p_nice{}; + uint64_t ppid{}; + uint64_t cpu_s{}; + uint64_t cpu_t{}; + uint64_t death_time{}; + string prefix{}; // defaults to "" + size_t depth{}; + size_t tree_index{}; + bool collapsed{}; + bool filtered{}; + }; + + //* Container for process info box + struct detail_container { + size_t last_pid{}; + bool skip_smaps{}; + proc_info entry; + string elapsed, parent, status, io_read, io_write, memory; + long long first_mem = -1; + deque cpu_percent; + deque mem_bytes; + }; + + //? Contains all info for proc detailed box + extern detail_container detailed; + + //* Collect and sort process information from /proc + auto collect(bool no_update = false) -> vector&; + + //* Update current selection and view, returns -1 if no change otherwise the current selection + int selection(const std::string_view cmd_key); + + //* Draw contents of proc box using as data source + string draw(const vector& plist, bool force_redraw = false, bool data_same = false); + + struct tree_proc { + std::reference_wrapper entry; + vector children; + }; + + //* Change priority (nice) of pid, returns true on success otherwise false + bool set_priority(pid_t pid, int priority); + + //* Sort vector of proc_info's + void proc_sorter(vector& proc_vec, const string& sorting, bool reverse, bool tree = false); + + //* Recursive sort of process tree + void tree_sort(vector& proc_vec, const string& sorting, bool reverse, bool paused, + int& c_index, const int index_max, bool collapsed = false); + + auto matches_filter(const proc_info& proc, const std::string& filter) -> bool; + + //* Generate process tree list + void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, + int cur_depth, bool collapsed, const string& filter, + bool found = false, bool no_update = false, bool should_filter = false); + + //* Build prefixes for tree view + void _collect_prefixes(tree_proc& t, bool is_last, const string &header = ""); + + //* Toggle collapse/expand of all tree entries + void toggle_tree_collapse(std::vector& current_procs); + + //* Auto-collapse processes with many direct children when entering tree mode + void _auto_collapse_oversized(std::vector& current_procs, const bool tree_mode_change); +} + +/// Detect container engine. +auto detect_container() -> std::optional; diff --git a/vendor/btop/src/btop_theme.cpp b/vendor/btop/src/btop_theme.cpp new file mode 100644 index 000000000..5710d6ce4 --- /dev/null +++ b/vendor/btop/src/btop_theme.cpp @@ -0,0 +1,473 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#include +#include +#include + +#include "btop_config.hpp" +#include "btop_log.hpp" +#include "btop_theme.hpp" +#include "btop_tools.hpp" + +using std::round; +using std::stoi; +using std::to_string; +using std::vector; +using std::views::iota; + +using namespace Tools; + +namespace fs = std::filesystem; + +string Term::fg, Term::bg; +string Fx::reset = reset_base; + +namespace Theme { + + fs::path theme_dir; + fs::path user_theme_dir; + fs::path custom_theme_dir; + vector themes; + std::unordered_map colors; + std::unordered_map> rgbs; + std::unordered_map> gradients; + + const std::unordered_map Default_theme = { + { "main_bg", "#00" }, + { "main_fg", "#cc" }, + { "title", "#ee" }, + { "hi_fg", "#b54040" }, + { "selected_bg", "#6a2f2f" }, + { "selected_fg", "#ee" }, + { "inactive_fg", "#40" }, + { "graph_text", "#60" }, + { "meter_bg", "#40" }, + { "proc_misc", "#0de756" }, + { "cpu_box", "#556d59" }, + { "mem_box", "#6c6c4b" }, + { "net_box", "#5c588d" }, + { "proc_box", "#805252" }, + { "div_line", "#30" }, + { "temp_start", "#4897d4" }, + { "temp_mid", "#5474e8" }, + { "temp_end", "#ff40b6" }, + { "cpu_start", "#77ca9b" }, + { "cpu_mid", "#cbc06c" }, + { "cpu_end", "#dc4c4c" }, + { "free_start", "#384f21" }, + { "free_mid", "#b5e685" }, + { "free_end", "#dcff85" }, + { "cached_start", "#163350" }, + { "cached_mid", "#74e6fc" }, + { "cached_end", "#26c5ff" }, + { "available_start", "#4e3f0e" }, + { "available_mid", "#ffd77a" }, + { "available_end", "#ffb814" }, + { "used_start", "#592b26" }, + { "used_mid", "#d9626d" }, + { "used_end", "#ff4769" }, + { "download_start", "#291f75" }, + { "download_mid", "#4f43a3" }, + { "download_end", "#b0a9de" }, + { "upload_start", "#620665" }, + { "upload_mid", "#7d4180" }, + { "upload_end", "#dcafde" }, + { "process_start", "#80d0a3" }, + { "process_mid", "#dcd179" }, + { "process_end", "#d45454" }, + { "proc_pause_bg", "#b54040" }, + { "proc_follow_bg", "#4040b5"}, + { "proc_banner_bg", "#7b407b"}, + { "proc_banner_fg", "#ee"}, + { "followed_bg", "#4040b5"}, + { "followed_fg", "#ee"}, + }; + + const std::unordered_map TTY_theme = { + { "main_bg", "\x1b[0;40m" }, + { "main_fg", "\x1b[37m" }, + { "title", "\x1b[97m" }, + { "hi_fg", "\x1b[91m" }, + { "selected_bg", "\x1b[41m" }, + { "selected_fg", "\x1b[97m" }, + { "inactive_fg", "\x1b[90m" }, + { "graph_text", "\x1b[90m" }, + { "meter_bg", "\x1b[90m" }, + { "proc_misc", "\x1b[92m" }, + { "cpu_box", "\x1b[32m" }, + { "mem_box", "\x1b[33m" }, + { "net_box", "\x1b[35m" }, + { "proc_box", "\x1b[31m" }, + { "div_line", "\x1b[90m" }, + { "temp_start", "\x1b[94m" }, + { "temp_mid", "\x1b[96m" }, + { "temp_end", "\x1b[95m" }, + { "cpu_start", "\x1b[92m" }, + { "cpu_mid", "\x1b[93m" }, + { "cpu_end", "\x1b[91m" }, + { "free_start", "\x1b[32m" }, + { "free_mid", "" }, + { "free_end", "\x1b[92m" }, + { "cached_start", "\x1b[36m" }, + { "cached_mid", "" }, + { "cached_end", "\x1b[96m" }, + { "available_start", "\x1b[33m" }, + { "available_mid", "" }, + { "available_end", "\x1b[93m" }, + { "used_start", "\x1b[31m" }, + { "used_mid", "" }, + { "used_end", "\x1b[91m" }, + { "download_start", "\x1b[34m" }, + { "download_mid", "" }, + { "download_end", "\x1b[94m" }, + { "upload_start", "\x1b[35m" }, + { "upload_mid", "" }, + { "upload_end", "\x1b[95m" }, + { "process_start", "\x1b[32m" }, + { "process_mid", "\x1b[33m" }, + { "process_end", "\x1b[31m" }, + { "proc_pause_bg", "\x1b[41m" }, + { "proc_follow_bg", "\x1b[44m" }, + { "proc_banner_bg", "\x1b[45m" }, + { "proc_banner_fg", "\x1b[97m" }, + { "followed_bg", "\x1b[44m" }, + { "followed_fg", "\x1b[97m" }, + }; + + namespace { + //* Convert 24-bit colors to 256 colors + int truecolor_to_256(const int& r, const int& g, const int& b) { + //? Use upper 232-255 greyscale values if the downscaled red, green and blue are the same value + if (const int red = round((double)r / 11); red == round((double)g / 11) and red == round((double)b / 11)) { + return 232 + red; + } + //? Else use 6x6x6 color cube to calculate approximate colors + else { + return round((double)r / 51) * 36 + round((double)g / 51) * 6 + round((double)b / 51) + 16; + } + } + } + + string hex_to_color(string hexa, bool t_to_256, const string& depth) { + if (hexa.size() > 1) { + hexa.erase(0, 1); + for (auto& c : hexa) { + if (not isxdigit(c)) { + Logger::error("Invalid hex value: {}", hexa); + return ""; + } + } + string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;"); + + if (hexa.size() == 2) { + int h_int = stoi(hexa, nullptr, 16); + if (t_to_256) { + return pre + to_string(truecolor_to_256(h_int, h_int, h_int)) + "m"; + } else { + string h_str = to_string(h_int); + return pre + h_str + ";" + h_str + ";" + h_str + "m"; + } + } + else if (hexa.size() == 6) { + if (t_to_256) { + return pre + to_string(truecolor_to_256( + stoi(hexa.substr(0, 2), nullptr, 16), + stoi(hexa.substr(2, 2), nullptr, 16), + stoi(hexa.substr(4, 2), nullptr, 16))) + "m"; + } else { + return pre + + to_string(stoi(hexa.substr(0, 2), nullptr, 16)) + ";" + + to_string(stoi(hexa.substr(2, 2), nullptr, 16)) + ";" + + to_string(stoi(hexa.substr(4, 2), nullptr, 16)) + "m"; + } + } + else Logger::error("Invalid size of hex value: {}", hexa); + } + else Logger::error("Hex value missing: {}", hexa); + return ""; + } + + string dec_to_color(int r, int g, int b, bool t_to_256, const string& depth) { + string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;"); + r = std::clamp(r, 0, 255); + g = std::clamp(g, 0, 255); + b = std::clamp(b, 0, 255); + if (t_to_256) return pre + to_string(truecolor_to_256(r, g, b)) + "m"; + else return pre + to_string(r) + ";" + to_string(g) + ";" + to_string(b) + "m"; + } + + namespace { + //* Convert hex color to a array of decimals + array hex_to_dec(string hexa) { + if (hexa.size() > 1) { + hexa.erase(0, 1); + for (auto& c : hexa) { + if (not isxdigit(c)) + return array{-1, -1, -1}; + } + + if (hexa.size() == 2) { + int h_int = stoi(hexa, nullptr, 16); + return array{h_int, h_int, h_int}; + } + else if (hexa.size() == 6) { + return array{ + stoi(hexa.substr(0, 2), nullptr, 16), + stoi(hexa.substr(2, 2), nullptr, 16), + stoi(hexa.substr(4, 2), nullptr, 16) + }; + } + } + return {-1 ,-1 ,-1}; + } + + //* Generate colors and rgb decimal vectors for the theme + void generateColors(const std::unordered_map& source) { + vector t_rgb; + string depth; + bool t_to_256 = Config::getB("lowcolor"); + colors.clear(); rgbs.clear(); + for (const auto& [name, color] : Default_theme) { + if (name == "main_bg" and not Config::getB("theme_background")) { + colors[name] = "\x1b[49m"; + rgbs[name] = {-1, -1, -1}; + continue; + } + depth = (name.ends_with("bg") and name != "meter_bg") ? "bg" : "fg"; + if (source.contains(name)) { + if (name == "main_bg" and source.at(name).empty()) { + colors[name] = "\x1b[49m"; + rgbs[name] = {-1, -1, -1}; + continue; + } + else if (source.at(name).empty() and (name.ends_with("_mid") or name.ends_with("_end"))) { + colors[name] = ""; + rgbs[name] = {-1, -1, -1}; + continue; + } + else if (source.at(name).starts_with('#')) { + colors[name] = hex_to_color(source.at(name), t_to_256, depth); + rgbs[name] = hex_to_dec(source.at(name)); + } + else if (not source.at(name).empty()) { + t_rgb = ssplit(source.at(name)); + if (t_rgb.size() != 3) { + Logger::error("Invalid RGB decimal value: \"{}\"", source.at(name)); + } else { + colors[name] = dec_to_color(stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2]), t_to_256, depth); + rgbs[name] = array{stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2])}; + + } + } + } + if (not colors.contains(name) and not is_in(name, "meter_bg", "process_start", "process_mid", "process_end", "graph_text")) { + Logger::debug("Missing color value for \"{}\". Using value from default.", name); + colors[name] = hex_to_color(color, t_to_256, depth); + rgbs[name] = hex_to_dec(color); + } + } + //? Set fallback values for optional colors not defined in theme file + if (not colors.contains("meter_bg")) { + colors["meter_bg"] = colors.at("inactive_fg"); + rgbs["meter_bg"] = rgbs.at("inactive_fg"); + } + if (not colors.contains("process_start")) { + colors["process_start"] = colors.at("cpu_start"); + colors["process_mid"] = colors.at("cpu_mid"); + colors["process_end"] = colors.at("cpu_end"); + rgbs["process_start"] = rgbs.at("cpu_start"); + rgbs["process_mid"] = rgbs.at("cpu_mid"); + rgbs["process_end"] = rgbs.at("cpu_end"); + } + if (not colors.contains("graph_text")) { + colors["graph_text"] = colors.at("inactive_fg"); + rgbs["graph_text"] = rgbs.at("inactive_fg"); + } + } + + //* Generate color gradients from two or three colors, 101 values indexed 0-100 + void generateGradients() { + gradients.clear(); + bool t_to_256 = Config::getB("lowcolor"); + + //? Insert values for processes greyscale gradient and processes color gradient + rgbs.insert({ + { "proc_start", rgbs["main_fg"] }, + { "proc_mid", {-1, -1, -1} }, + { "proc_end", rgbs["inactive_fg"] }, + { "proc_color_start", rgbs["inactive_fg"] }, + { "proc_color_mid", {-1, -1, -1} }, + { "proc_color_end", rgbs["process_start"] }, + }); + + for (const auto& [name, source_arr] : rgbs) { + if (not name.ends_with("_start")) continue; + const string color_name { rtrim(name, "_start") }; + + //? input_colors[start,mid,end][red,green,blue] + const array, 3> input_colors = { + source_arr, + rgbs[color_name + "_mid"], + rgbs[color_name + "_end"] + }; + + //? output_colors[red,green,blue][0-100] + array, 101> output_colors; + output_colors[0][0] = -1; + + //? Only start iteration if gradient has an end color defined + if (input_colors[2][0] >= 0) { + + //? Split iteration in two passes of 50 + 51 instead of one pass of 101 if gradient has start, mid and end values defined + int current_range = (input_colors[1][0] >= 0) ? 50 : 100; + for (int rgb : iota(0, 3)) { + int start = 0, offset = 0; + int end = (current_range == 50) ? 1 : 2; + for (int i : iota(0, 101)) { + output_colors[i][rgb] = input_colors[start][rgb] + (i - offset) * (input_colors[end][rgb] - input_colors[start][rgb]) / current_range; + + //? Switch source arrays from start->mid to mid->end at 50 passes if mid is defined + if (i == current_range) { ++start; ++end; offset = 50; } + } + } + } + //? Generate color escape codes for the generated rgb decimals + array color_gradient; + if (output_colors[0][0] != -1) { + for (int y = 0; const auto& [red, green, blue] : output_colors) + color_gradient[y++] = dec_to_color(red, green, blue, t_to_256); + } + else { + //? If only start was defined fill array with start color + color_gradient.fill(colors[name]); + } + gradients[color_name] = std::move(color_gradient); + } + } + + //* Set colors and generate gradients for the TTY theme + void generateTTYColors() { + rgbs.clear(); + gradients.clear(); + colors = TTY_theme; + if (not Config::getB("theme_background")) + colors["main_bg"] = "\x1b[49m"; + + for (const auto& c : colors) { + if (not c.first.ends_with("_start")) continue; + const string base_name { rtrim(c.first, "_start") }; + string section = "_start"; + int split = colors.at(base_name + "_mid").empty() ? 50 : 33; + for (int i : iota(0, 101)) { + gradients[base_name][i] = colors.at(base_name + section); + if (i == split) { + section = (split == 33) ? "_mid" : "_end"; + split *= 2; + } + } + } + } + + //* Load a .theme file from disk + auto loadFile(const string& filename) { + const fs::path filepath = filename; + if (not fs::exists(filepath)) + return Default_theme; + + std::ifstream themefile(filepath); + if (themefile.good()) { + std::unordered_map theme_out; + Logger::debug("Loading theme file: {}", filename); + while (not themefile.bad()) { + if (themefile.peek() == '#') { + themefile.ignore(SSmax, '\n'); + continue; + } + themefile.ignore(SSmax, '['); + if (themefile.eof()) break; + string name, value; + getline(themefile, name, ']'); + if (not Default_theme.contains(name)) { + themefile.ignore(SSmax, '\n'); + continue; + } + themefile.ignore(SSmax, '='); + themefile >> std::ws; + if (themefile.eof()) break; + if (themefile.peek() == '"') { + themefile.ignore(1); + getline(themefile, value, '"'); + themefile.ignore(SSmax, '\n'); + } + else getline(themefile, value, '\n'); + + theme_out[name] = value; + } + return theme_out; + } + return Default_theme; + } + } + + void updateThemes() { + themes.clear(); + themes.push_back("Default"); + themes.push_back("TTY"); + + //? Priority: custom_theme_dir -> user_theme_dir -> theme_dir + for (const auto& path : { custom_theme_dir, user_theme_dir, theme_dir } ) { + if (path.empty()) continue; + for (auto& file : fs::directory_iterator(path)) { + if (file.path().extension() == ".theme" and access(file.path().c_str(), R_OK) != -1 and not v_contains(themes, file.path().c_str())) { + themes.push_back(file.path().c_str()); + } + } + } + + //? Sort themes alphabetically + std::stable_sort(themes.begin() + 2, themes.end(), [](const string& a, const string& b) { + return fs::path(a).filename().string() < fs::path(b).filename().string(); + }); + + } + + void setTheme() { + const auto& theme = Config::getS("color_theme"); + const auto theme_cfg_path = fs::path(theme); + fs::path theme_path; + for (const fs::path p : themes) { + //? Check for match by full path, filename, stem or legacy absolute path + if (p == theme or p.filename() == theme or p.stem() == theme or (theme_cfg_path.is_absolute() and theme_cfg_path.filename() == p.filename())) { + theme_path = p; + break; + } + } + if (theme == "TTY" or Config::getB("tty_mode")) + generateTTYColors(); + else { + generateColors((theme == "Default" or theme_path.empty() ? Default_theme : loadFile(theme_path))); + generateGradients(); + } + Term::fg = colors.at("main_fg"); + Term::bg = colors.at("main_bg"); + Fx::reset = Fx::reset_base + Term::fg + Term::bg; + } + +} diff --git a/vendor/btop/src/btop_theme.hpp b/vendor/btop/src/btop_theme.hpp new file mode 100644 index 000000000..695fd3d13 --- /dev/null +++ b/vendor/btop/src/btop_theme.hpp @@ -0,0 +1,70 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#include +#include +#include +#include +#include + +using std::array; +using std::string; +using std::vector; + +namespace Theme { + extern std::filesystem::path theme_dir; + extern std::filesystem::path user_theme_dir; + extern std::filesystem::path custom_theme_dir; + + //* Contains "Default" and "TTY" at indices 0 and 1, otherwise full paths to theme files + extern vector themes; + + //* Generate escape sequence for 24-bit or 256 color and return as a string + //* Args hexa: ["#000000"-"#ffffff"] for color, ["#00"-"#ff"] for greyscale + //* t_to_256: [true|false] convert 24bit value to 256 color value + //* depth: ["fg"|"bg"] for either a foreground color or a background color + string hex_to_color(string hexa, bool t_to_256=false, const string& depth="fg"); + + //* Generate escape sequence for 24-bit or 256 color and return as a string + //* Args r: [0-255], g: [0-255], b: [0-255] + //* t_to_256: [true|false] convert 24bit value to 256 color value + //* depth: ["fg"|"bg"] for either a foreground color or a background color + string dec_to_color(int r, int g, int b, bool t_to_256=false, const string& depth="fg"); + + //* Update list of paths for available themes + void updateThemes(); + + //* Set current theme from current "color_theme" value in config + void setTheme(); + + extern std::unordered_map colors; + extern std::unordered_map> rgbs; + extern std::unordered_map> gradients; + + //* Return escape code for color + inline const string& c(const string& name) { return colors.at(name); } + + //* Return array of escape codes for color gradient + inline const array& g(const string& name) { return gradients.at(name); } + + //* Return array of red, green and blue in decimal for color + inline const std::array& dec(const string& name) { return rgbs.at(name); } + +} diff --git a/vendor/btop/src/btop_tools.cpp b/vendor/btop/src/btop_tools.cpp new file mode 100644 index 000000000..f0e0de63e --- /dev/null +++ b/vendor/btop/src/btop_tools.cpp @@ -0,0 +1,769 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "widechar_width.hpp" +#include "btop_log.hpp" +#include "btop_shared.hpp" +#include "btop_tools.hpp" +#include "btop_config.hpp" + +using std::cout; +using std::floor; +using std::flush; +using std::max; +using std::string_view; +using std::to_string; + +using namespace std::literals; // to use operator""s + +namespace fs = std::filesystem; + +//? ------------------------------------------------- NAMESPACES ------------------------------------------------------ + +//* Collection of escape codes and functions for terminal manipulation +namespace Term { + + atomic initialized{}; + atomic width{}; + atomic height{}; + string current_tty; + + namespace { + struct termios initial_settings; + + //* Toggle terminal input echo + bool echo(bool on=true) { + struct termios settings; + if (tcgetattr(STDIN_FILENO, &settings)) return false; + if (on) settings.c_lflag |= ECHO; + else settings.c_lflag &= ~(ECHO); + return 0 == tcsetattr(STDIN_FILENO, TCSANOW, &settings); + } + + //* Toggle need for return key when reading input + bool linebuffered(bool on=true) { + struct termios settings; + if (tcgetattr(STDIN_FILENO, &settings)) return false; + if (on) settings.c_lflag |= ICANON; + else { + settings.c_lflag &= ~(ICANON); + settings.c_cc[VMIN] = 0; + settings.c_cc[VTIME] = 0; + } + if (tcsetattr(STDIN_FILENO, TCSANOW, &settings)) return false; + if (on) setlinebuf(stdin); + else setbuf(stdin, nullptr); + return true; + } + } + + bool refresh(bool only_check) { + // Query dimensions of '/dev/tty' of the 'STDOUT_FILENO' isn't available. + // This variable is set in those cases to avoid calls to ioctl + constinit static bool uses_dev_tty = false; + struct winsize wsize {}; + if (uses_dev_tty || ioctl(STDOUT_FILENO, TIOCGWINSZ, &wsize) < 0 || (wsize.ws_col == 0 && wsize.ws_row == 0)) { + Logger::error(R"(Couldn't determine terminal size of "STDOUT_FILENO"!)"); + auto dev_tty = open("/dev/tty", O_RDONLY | O_CLOEXEC); + if (dev_tty != -1) { + ioctl(dev_tty, TIOCGWINSZ, &wsize); + close(dev_tty); + } + else { + Logger::error(R"(Couldn't determine terminal size of "/dev/tty"!)"); + return false; + } + uses_dev_tty = true; + } + if (width != wsize.ws_col or height != wsize.ws_row) { + if (not only_check) { + width = wsize.ws_col; + height = wsize.ws_row; + } + return true; + } + return false; + } + + auto get_min_size(const string& boxes) -> array { + bool cpu = boxes.find("cpu") != string::npos; + bool mem = boxes.find("mem") != string::npos; + bool net = boxes.find("net") != string::npos; + bool proc = boxes.find("proc") != string::npos; + #ifdef GPU_SUPPORT + int gpu = 0; + if (Gpu::count > 0) + for (char i = '0'; i <= '5'; i++) + gpu += (boxes.contains("gpu"s + i) ? 1 : 0); + #endif + int width = 0; + if (mem) width = Mem::min_width; + else if (net) width = Mem::min_width; + width += (proc ? Proc::min_width : 0); + if (cpu and width < Cpu::min_width) width = Cpu::min_width; + #ifdef GPU_SUPPORT + if (gpu != 0 and width < Gpu::min_width) width = Gpu::min_width; + #endif + + int height = (cpu ? Cpu::min_height : 0); + if (proc) height += Proc::min_height; + else height += (mem ? Mem::min_height : 0) + (net ? Net::min_height : 0); + #ifdef GPU_SUPPORT + for (int i = 0; i < gpu; i++) + height += Gpu::gpu_b_height_offsets[i] + 4; + #endif + + return { width, height }; + } + + bool init() { + if (not initialized) { + initialized = (bool)isatty(STDIN_FILENO); + if (initialized) { + tcgetattr(STDIN_FILENO, &initial_settings); + current_tty = (ttyname(STDIN_FILENO) != nullptr ? static_cast(ttyname(STDIN_FILENO)) : "unknown"); + + //? Disable stream sync - this does not seem to work on OpenBSD +#ifndef __OpenBSD__ + cout.sync_with_stdio(false); +#endif + + //? Disable stream ties + cout.tie(nullptr); + echo(false); + linebuffered(false); + refresh(); + + const auto is_mouse_enabled = !Config::getB("disable_mouse"); + cout << alt_screen << hide_cursor << (is_mouse_enabled ? mouse_on : mouse_off) << flush; + Global::resized = false; + } + } + return initialized; + } + + void restore() { + if (initialized) { + tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings); + cout << mouse_off << clear << Fx::reset << normal_screen << show_cursor << flush; + initialized = false; + } + } +} + +//? --------------------------------------------------- FUNCTIONS ----------------------------------------------------- + +// ! Disabled due to issue when compiling with musl, reverted back to using regex +// namespace Fx { +// string uncolor(const string& s) { +// string out = s; +// for (size_t offset = 0, start_pos = 0, end_pos = 0;;) { +// start_pos = (offset == 0) ? out.find('\x1b') : offset; +// if (start_pos == string::npos) +// break; +// offset = start_pos + 1; +// end_pos = out.find('m', offset); +// if (end_pos == string::npos) +// break; +// else if (auto next_pos = out.find('\x1b', offset); not isdigit(out[end_pos - 1]) or end_pos > next_pos) { +// offset = next_pos; +// continue; +// } + +// out.erase(start_pos, (end_pos - start_pos)+1); +// offset = 0; +// } +// out.shrink_to_fit(); +// return out; +// } +// } + +namespace Tools { + + string replace_ascii_control(string str, const char replacement) { + if (str.empty()) + return str; + const char* str_data = &str.data()[0]; + size_t w_len = 1 + std::mbstowcs(nullptr, str_data, 0); + if (w_len <= 1) { + std::ranges::for_each(str, [&replacement](char& c) { if (c < 0x20) c = replacement; }); + return str; + } + vector w_str(w_len); + std::mbstowcs(&w_str[0], str_data, w_len); + for (size_t i = 0; i < w_str.size() - 1; i++) { + if (widechar_wcwidth(w_str[i]) > 1) + continue; + if (w_str[i] < 0x20) + w_str[i] = replacement; + } + size_t bytes = std::wcstombs(nullptr, w_str.data(), 0); + if (bytes == static_cast(-1)) + return str; + str.resize(bytes); + std::wcstombs(&str[0], &w_str[0], bytes); + + return str; + } + + size_t wide_ulen(const std::string_view str) { + if (str.empty()) + return 0; + unsigned int chars = 0; + + const char* str_data = &str.data()[0]; + size_t w_len = 1 + std::mbstowcs(nullptr, str_data, 0); + if (w_len <= 1) + return ulen(str); + vector w_str(w_len); + std::mbstowcs(&w_str[0], str_data, w_len); + + for (auto c : w_str) { + chars += widechar_wcwidth(c); + } + + return chars; + } + + size_t wide_ulen(const vector w_str) { + unsigned int chars = 0; + + for (auto c : w_str) { + chars += widechar_wcwidth(c); + } + + return chars; + } + + string uresize(string str, const size_t len, bool wide) { + if (len < 1 or str.empty()) + return ""; + + if (wide) { + const char* str_data = &str.data()[0]; + size_t w_len = 1 + std::mbstowcs(nullptr, str_data, 0); + if (w_len <= 1) + return uresize(str, len, false); + vector w_str(w_len); + std::mbstowcs(&w_str[0], str_data, w_len); + + while (wide_ulen(w_str) > len) w_str.pop_back(); + + string n_str; + n_str.resize(w_str.size()); + std::wcstombs(&n_str[0], &w_str[0], w_str.size()); + + return n_str; + } + else { + for (size_t x = 0, i = 0; i < str.size(); i++) { + if ((static_cast(str.at(i)) & 0xC0) != 0x80) x++; + if (x >= len + 1) { + str.resize(i); + break; + } + } + } + str.shrink_to_fit(); + return str; + } + + string luresize(string str, const size_t len, bool wide) { + if (len < 1 or str.empty()) + return ""; + + for (size_t x = 0, last_pos = 0, i = str.size() - 1; i > 0 ; i--) { + if (wide and static_cast(str.at(i)) > 0xef) { + x += 2; + last_pos = max((size_t)0, i - 1); + } + else if ((static_cast(str.at(i)) & 0xC0) != 0x80) { + x++; + last_pos = i; + } + if (x >= len) { + str = str.substr(last_pos); + str.shrink_to_fit(); + break; + } + } + return str; + } + + string s_replace(const string& str, const string& from, const string& to) { + string out = str; + for (size_t start_pos = out.find(from); start_pos != std::string::npos; start_pos = out.find(from)) { + out.replace(start_pos, from.length(), to); + } + return out; + } + + string_view ltrim(string_view str, const string_view t_str) { + while (str.starts_with(t_str)) + str.remove_prefix(t_str.size()); + + return str; + } + + string_view rtrim(string_view str, const string_view t_str) { + while (str.ends_with(t_str)) + str.remove_suffix(t_str.size()); + + return str; + } + + string ljust(string str, const size_t x, bool utf, bool wide, bool limit) { + if (utf) { + if (limit and ulen(str, wide) > x) + return uresize(str, x, wide); + + return str + string(max((int)(x - ulen(str)), 0), ' '); + } + else { + if (limit and str.size() > x) { + str.resize(x); + return str; + } + return str + string(max((int)(x - str.size()), 0), ' '); + } + } + + string rjust(string str, const size_t x, bool utf, bool wide, bool limit) { + if (utf) { + if (limit and ulen(str, wide) > x) + return uresize(str, x, wide); + + return string(max((int)(x - ulen(str)), 0), ' ') + str; + } + else { + if (limit and str.size() > x) { + str.resize(x); + return str; + }; + return string(max((int)(x - str.size()), 0), ' ') + str; + } + } + + string cjust(string str, const size_t x, bool utf, bool wide, bool limit) { + if (utf) { + if (limit and ulen(str, wide) > x) + return uresize(str, x, wide); + + return string(max((int)ceil((double)(x - ulen(str)) / 2), 0), ' ') + str + string(max((int)floor((double)(x - ulen(str)) / 2), 0), ' '); + } + else { + if (limit and str.size() > x) { + str.resize(x); + return str; + } + return string(max((int)ceil((double)(x - str.size()) / 2), 0), ' ') + str + string(max((int)floor((double)(x - str.size()) / 2), 0), ' '); + } + } + + string trans(const string& str) { + std::string_view oldstr{str}; + string newstr; + newstr.reserve(str.size()); + for (size_t pos; (pos = oldstr.find(' ')) != string::npos;) { + newstr.append(oldstr.substr(0, pos)); + size_t x = 0; + while (pos + x < oldstr.size() and oldstr.at(pos + x) == ' ') x++; + newstr.append(Mv::r(x)); + oldstr.remove_prefix(pos + x); + } + return (newstr.empty()) ? str : newstr + string{oldstr}; + } + + string sec_to_dhms(size_t seconds, bool no_days, bool no_seconds) { + size_t days = seconds / 86400; seconds %= 86400; + size_t hours = seconds / 3600; seconds %= 3600; + size_t minutes = seconds / 60; seconds %= 60; + string out = (not no_days and days > 0 ? to_string(days) + "d " : "") + + (hours < 10 ? "0" : "") + to_string(hours) + ':' + + (minutes < 10 ? "0" : "") + to_string(minutes) + + (not no_seconds ? ":" + string(std::cmp_less(seconds, 10) ? "0" : "") + to_string(seconds) : ""); + return out; + } + + string floating_humanizer(uint64_t value, bool shorten, size_t start, bool bit, bool per_second) { + string out; + const size_t mult = (bit) ? 8 : 1; + + bool mega = Config::getB("base_10_sizes"); + + // Bitrates + if(bit && per_second) { + const auto& base_10_bitrate = Config::getS("base_10_bitrate"); + if(base_10_bitrate == "True") { + mega = true; + } else if(base_10_bitrate == "False") { + mega = false; + } + // Default or "Auto": Uses base_10_sizes for bitrates + } + + // taking advantage of type deduction for array creation (since C++17) + // combined with string literals (operator""s) + static const array mebiUnits_bit { + "bit"s, "Kib"s, "Mib"s, + "Gib"s, "Tib"s, "Pib"s, + "Eib"s, "Zib"s, "Yib"s, + "Rib"s, "Qib"s + }; + static const array mebiUnits_byte { + "Byte"s, "KiB"s, "MiB"s, + "GiB"s, "TiB"s, "PiB"s, + "EiB"s, "ZiB"s, "YiB"s, + "RiB"s, "QiB"s + }; + static const array megaUnits_bit { + "bit"s, "kb"s, "Mb"s, + "Gb"s, "Tb"s, "Pb"s, + "Eb"s, "Zb"s, "Yb"s, + "Rb"s, "Qb"s + }; + static const array megaUnits_byte { + "Byte"s, "kB"s, "MB"s, + "GB"s, "TB"s, "PB"s, + "EB"s, "ZB"s, "YB"s, + "RB"s, "QB"s + }; + const auto& units = (bit) ? ( mega ? megaUnits_bit : mebiUnits_bit) : ( mega ? megaUnits_byte : mebiUnits_byte); + + value *= 100 * mult; + + if (mega) { + while (value >= 100000) { + value /= 1000; + start++; + } + } + else { + while (value >= 102400) { + value >>= 10; + start++; + } + } + if (out.empty()) { + out = fmt::format("{}", value); + if (not mega and out.size() == 4 and start > 0) { + out.pop_back(); + out.insert(2, "."); + } + else if (out.size() == 3 and start > 0) { + out.insert(1, "."); + } + else if (out.size() >= 2) { + out.resize(out.size() - 2); + } + if (out.empty()) { + out = "0"; + } + } + + if (shorten) { + auto has_sep = out.find(".") != string::npos; + if (has_sep) { + out = fmt::format("{:.1f}", stod(out)); + } + if (out.size() > 3) { + // if out is of the form xy.z + if (has_sep) { + out = fmt::format("{:.0f}", stod(out)); + } + // if out is of the form xyzw (only when not using base 10) + else { + out = fmt::format("{:d}.0", out[0] - '0'); + start++; + } + } + out.push_back(units[start][0]); + } + else out += " " + units[start]; + + if (per_second) out += (bit) ? "ps" : "/s"; + return out; + } + + std::string operator*(const string& str, int64_t n) { + if (n < 1 or str.empty()) { + return ""; + } + else if (n == 1) { + return str; + } + + string new_str; + new_str.reserve(str.size() * n); + + for (; n > 0; n--) + new_str.append(str); + + return new_str; + } + + string strf_time(const string& strf) { + auto in_time_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + std::tm bt {}; + std::stringstream ss; + ss << std::put_time(localtime_r(&in_time_t, &bt), strf.c_str()); + return ss.str(); + } + + void atomic_wait(const atomic& atom, bool old) noexcept { + atom.wait(old, std::memory_order_acquire); + } + + atomic_lock::atomic_lock(atomic& atom, bool wait) : atom(atom) { + if (wait) { + bool expected = false; + while (not this->atom.compare_exchange_strong(expected, true, std::memory_order_acquire, std::memory_order_relaxed)) expected = false; + } + else this->atom.store(true, std::memory_order_release); + this->atom.notify_one(); + } + + atomic_lock::~atomic_lock() noexcept { + this->atom.store(false, std::memory_order_release); + this->atom.notify_one(); + } + + void atomic_waiting_lock::store(bool new_value) noexcept { + { + std::lock_guard lock {mtx}; + value = new_value; + } + cv.notify_all(); + } + + void atomic_waiting_lock::wait(bool old) const noexcept { + std::unique_lock lock {mtx}; + cv.wait(lock, [this, old] { return value != old; }); + } + + void atomic_waiting_lock::wait_for(bool old, uint64_t wait_ms) const noexcept { + std::unique_lock lock {mtx}; + const auto start = uptime_micros(); + const auto wait_us = wait_ms * 1'000ULL; + while (value == old) { + const auto elapsed = uptime_micros() - start; + if (elapsed >= wait_us) break; + cv.wait_for(lock, std::chrono::microseconds(wait_us - elapsed), [this, old] { return value != old; }); + } + } + + atomic_waiting_lock::guard atomic_waiting_lock::lock(bool wait) { + return guard(*this, wait); + } + + atomic_waiting_lock::operator bool() const noexcept { + std::lock_guard lock {mtx}; + return value; + } + + atomic_waiting_lock::guard::guard(atomic_waiting_lock& atom, bool wait) : atom(atom) { + if (wait) { + std::unique_lock lock {this->atom.mtx}; + this->atom.cv.wait(lock, [this] { return not this->atom.value; }); + this->atom.value = true; + } + else { + std::lock_guard lock {this->atom.mtx}; + this->atom.value = true; + } + this->atom.cv.notify_one(); + } + + atomic_waiting_lock::guard::~guard() noexcept { + { + std::lock_guard lock {this->atom.mtx}; + this->atom.value = false; + } + this->atom.cv.notify_one(); + } + + void atomic_wait(const atomic_waiting_lock& atom, bool old) noexcept { + atom.wait(old); + } + + void atomic_wait_for(const atomic_waiting_lock& atom, bool old, const uint64_t wait_ms) { + atom.wait_for(old, wait_ms); + } + + string readfile(const std::filesystem::path& path, const string& fallback) { + if (not fs::exists(path)) return fallback; + string out; + try { + std::ifstream file(path); + for (string readstr; getline(file, readstr); out += readstr); + } + catch (const std::exception& e) { + Logger::error("readfile() : Exception when reading {} : {}", path, e.what()); + return fallback; + } + return (out.empty() ? fallback : out); + } + + auto celsius_to(const long long& celsius, const string& scale) -> tuple { + if (scale == "celsius") + return {celsius, "°C"}; + else if (scale == "fahrenheit") + return {(long long)round((double)celsius * 1.8 + 32), "°F"}; + else if (scale == "kelvin") + return {(long long)round((double)celsius + 273.15), "K "}; + else if (scale == "rankine") + return {(long long)round((double)celsius * 1.8 + 491.67), "°R"}; + return {0, ""}; + } + + string hostname() { + char host[HOST_NAME_MAX]; + gethostname(host, HOST_NAME_MAX); + host[HOST_NAME_MAX - 1] = '\0'; + return string{host}; + } + + string username() { + auto user = getenv("LOGNAME"); + if (user == nullptr or strlen(user) == 0) user = getenv("USER"); + return (user != nullptr ? user : ""); + } + + DebugTimer::DebugTimer(string name, bool start, bool delayed_report) + : name(std::move(name)), delayed_report(delayed_report) { + if (start) + this->start(); + } + + DebugTimer::~DebugTimer() { + if (running) + this->stop(true); + this->force_report(); + } + + void DebugTimer::start() { + if (running) return; + running = true; + start_time = time_micros(); + } + + void DebugTimer::stop(bool report) { + if (not running) return; + running = false; + elapsed_time = time_micros() - start_time; + if (report) this->report(); + } + + void DebugTimer::reset(bool restart) { + running = false; + start_time = 0; + elapsed_time = 0; + if (restart) this->start(); + } + + void DebugTimer::stop_rename_reset(const string &new_name, bool report, bool restart) { + this->stop(report); + name = new_name; + this->reset(restart); + } + + void DebugTimer::report() { + string report_line; + if (start_time == 0 and elapsed_time == 0) + report_line = fmt::format("DebugTimer::report() warning -> Timer [{}] has not been started!", name); + else if (running) + report_line = fmt::format(custom_locale, "Timer [{}] (running) currently at {:L} μs", name, time_micros() - start_time); + else + report_line = fmt::format(custom_locale, "Timer [{}] took {:L} μs", name, elapsed_time); + + if (delayed_report) + report_buffer.emplace_back(report_line); + else + Logger::debug("{}", report_line); + } + + void DebugTimer::force_report() { + if (report_buffer.empty()) return; + for (const auto& line : report_buffer) + Logger::debug("{}", line); + report_buffer.clear(); + } + + uint64_t DebugTimer::elapsed() { + if (running) + return time_micros() - start_time; + return elapsed_time; + } + + bool DebugTimer::is_running() { + return running; + } +} + +const string Fx::e = "\x1b["; //* Escape sequence start +const string Fx::b = e + "1m"; //* Bold on/off +const string Fx::ub = e + "22m"; //* Bold off +const string Fx::d = e + "2m"; //* Dark on +const string Fx::ud = e + "22m"; //* Dark off +const string Fx::i = e + "3m"; //* Italic on +const string Fx::ui = e + "23m"; //* Italic off +const string Fx::ul = e + "4m"; //* Underline on +const string Fx::uul = e + "24m"; //* Underline off +const string Fx::bl = e + "5m"; //* Blink on +const string Fx::ubl = e + "25m"; //* Blink off +const string Fx::s = e + "9m"; //* Strike/crossed-out on +const string Fx::us = e + "29m"; //* Strike/crossed-out on/off + +//* Reset foreground/background color and text effects +const string Fx::reset_base = e + "0m"; + +//* Regex for matching color, style and cursor move escape sequences +const std::regex Fx::escape_regex("\033\\[\\d+;?\\d?;?\\d*;?\\d*;?\\d*(m|f|s|u|C|D|A|B){1}"); + +//* Regex for matching only color and style escape sequences +const std::regex Fx::color_regex("\033\\[\\d+;?\\d?;?\\d*;?\\d*;?\\d*(m){1}"); + +const string Term::hide_cursor = Fx::e + "?25l"; +const string Term::show_cursor = Fx::e + "?25h"; +const string Term::alt_screen = Fx::e + "?1049h"; +const string Term::normal_screen = Fx::e + "?1049l"; +const string Term::clear = Fx::e + "2J" + Fx::e + "0;0f"; +const string Term::clear_end = Fx::e + "0J"; +const string Term::clear_begin = Fx::e + "1J"; +const string Term::mouse_on = Fx::e + "?1002h" + Fx::e + "?1015h" + Fx::e + "?1006h"; //? Enable reporting of mouse position on click and release +const string Term::mouse_off = Fx::e + "?1002l" + Fx::e + "?1015l" + Fx::e + "?1006l"; +const string Term::mouse_direct_on = Fx::e + "?1003h"; //? Enable reporting of mouse position at any movement +const string Term::mouse_direct_off = Fx::e + "?1003l"; +const string Term::sync_start = Fx::e + "?2026h"; //? Start of terminal synchronized output +const string Term::sync_end = Fx::e + "?2026l"; //? End of terminal synchronized output diff --git a/vendor/btop/src/btop_tools.hpp b/vendor/btop/src/btop_tools.hpp new file mode 100644 index 000000000..3249e8f2e --- /dev/null +++ b/vendor/btop/src/btop_tools.hpp @@ -0,0 +1,466 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#if !defined(NDEBUG) +# define BTOP_DEBUG +#endif + +#include // for std::ranges::count_if +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef BTOP_DEBUG +#include +#endif +#ifndef HOST_NAME_MAX + #ifdef __APPLE__ + #define HOST_NAME_MAX 255 + #else + #define HOST_NAME_MAX 64 + #endif +#endif + +#include +#include + +#include "btop_log.hpp" + +using std::array; +using std::atomic; +using std::string; +using std::to_string; +using std::string_view; +using std::tuple; +using std::vector; +using namespace fmt::literals; + +//? ------------------------------------------------- NAMESPACES ------------------------------------------------------ + +//* Collection of escape codes for text style and formatting +namespace Fx { + extern const string e; //* Escape sequence start + extern const string b; //* Bold on/off + extern const string ub; //* Bold off + extern const string d; //* Dark on + extern const string ud; //* Dark off + extern const string i; //* Italic on + extern const string ui; //* Italic off + extern const string ul; //* Underline on + extern const string uul;//* Underline off + extern const string bl; //* Blink on + extern const string ubl;//* Blink off + extern const string s; //* Strike/crossed-out on + extern const string us; //* Strike/crossed-out on/off + + //* Reset foreground/background color and text effects + extern const string reset_base; + + //* Reset text effects and restore theme foregrund and background color + extern string reset; + + //* Regex for matching color, style and cursor move escape sequences + extern const std::regex escape_regex; + + //* Regex for matching only color and style escape sequences + extern const std::regex color_regex; + + //* Return a string with all colors and text styling removed + inline string uncolor(const string& s) { return std::regex_replace(s, color_regex, ""); } + // string uncolor(const string& s); + +} + +//* Collection of escape codes and functions for cursor manipulation +namespace Mv { + //* Move cursor to , + inline string to(int line, int col) { return Fx::e + to_string(line) + ';' + to_string(col) + 'f'; } + + //* Move cursor right columns + inline string r(int x) { return Fx::e + to_string(x) + 'C'; } + + //* Move cursor left columns + inline string l(int x) { return Fx::e + to_string(x) + 'D'; } + + //* Move cursor up x lines + inline string u(int x) { return Fx::e + to_string(x) + 'A'; } + + //* Move cursor down x lines + inline string d(int x) { return Fx::e + to_string(x) + 'B'; } + + //* Save cursor position + const string save = Fx::e + "s"; + + //* Restore saved cursor position + const string restore = Fx::e + "u"; +} + +//* Collection of escape codes and functions for terminal manipulation +namespace Term { + extern atomic initialized; + extern atomic width; + extern atomic height; + extern string fg, bg, current_tty; + + extern const string hide_cursor; + extern const string show_cursor; + extern const string alt_screen; + extern const string normal_screen; + extern const string clear; + extern const string clear_end; + extern const string clear_begin; + extern const string mouse_on; //? Enable reporting of mouse position on click and release + extern const string mouse_off; + extern const string mouse_direct_on; //? Enable reporting of mouse position at any movement + extern const string mouse_direct_off; + extern const string sync_start; //? Start of terminal synchronized output + extern const string sync_end; //? End of terminal synchronized output + + //* Returns true if terminal has been resized and updates width and height + bool refresh(bool only_check=false); + + //* Returns an array with the lowest possible width, height with current box config + auto get_min_size(const string& boxes) -> array; + + //* Check for a valid tty, save terminal options and set new options + bool init(); + + //* Restore terminal options + void restore(); +} + +//? --------------------------------------------------- FUNCTIONS ----------------------------------------------------- + +namespace Tools { + constexpr auto SSmax = std::numeric_limits::max(); + + class MyNumPunct : public std::numpunct { + protected: + virtual char do_thousands_sep() const override { return '\''; } + virtual std::string do_grouping() const override { return "\03"; } + }; + + size_t wide_ulen(const std::string_view str); + size_t wide_ulen(const vector w_str); + + //* Return number of UTF8 characters in a string (wide=true for column size needed on terminal) + inline size_t ulen(const std::string_view str, bool wide = false) { + return (wide ? wide_ulen(str) : std::ranges::count_if(str, [](char c) { return (static_cast(c) & 0xC0) != 0x80; })); + } + + //* Resize a string consisting of UTF8 characters (only reduces size) + string uresize(const string str, const size_t len, bool wide = false); + + //* Resize a string consisting of UTF8 characters from left (only reduces size) + string luresize(const string str, const size_t len, bool wide = false); + + //* Replace in with and return new string + string s_replace(const string& str, const string& from, const string& to); + + //* Replace ascii control characters with in and return new string + string replace_ascii_control(string str, const char replacement = ' '); + + //* Capitalize + inline string capitalize(string str) { + str.at(0) = toupper(str.at(0)); + return str; + } + + //* Return with only uppercase characters + inline auto str_to_upper(string str) { + std::ranges::for_each(str, [](auto& c) { c = ::toupper(c); } ); + return str; + } + + //* Return with only lowercase characters + inline auto str_to_lower(string str) { + std::ranges::for_each(str, [](char& c) { c = ::tolower(c); } ); + return str; + } + + //* Check if vector contains value + template + inline bool v_contains(const vector& vec, const T2& find_val) { + return std::ranges::find(vec, find_val) != vec.end(); + } + + //* Check if string contains string , while ignoring case + inline bool s_contains_ic(const std::string_view str, const std::string_view find_val) { + auto it = std::search( + str.begin(), str.end(), + find_val.begin(), find_val.end(), + [](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); } + ); + return it != str.end(); + } + + //* Return index of from vector , returns size of if is not present + template + inline size_t v_index(const vector& vec, const T& find_val) { + return std::ranges::distance(vec.begin(), std::ranges::find(vec, find_val)); + } + + //* Compare with all following values + template + inline bool is_in(const First& first, const T& ... t) { + return ((first == t) or ...); + } + + //* Return current time since epoch in seconds + inline uint64_t time_s() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + } + + //* Return current time since epoch in milliseconds + inline uint64_t time_ms() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + } + + //* Return current time since epoch in microseconds + inline uint64_t time_micros() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + } + + //* Return uptime in microseconds, excluding time spent in system suspend + inline uint64_t uptime_micros() { + struct timespec ts{}; +#ifdef __APPLE__ + if (clock_gettime(CLOCK_UPTIME_RAW, &ts) != 0) return 0; +#elif defined(__FreeBSD__) + if (clock_gettime(CLOCK_UPTIME, &ts) != 0) return 0; +#else + if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; +#endif + return static_cast(ts.tv_sec) * 1'000'000 + static_cast(ts.tv_nsec) / 1000; + } + + //* Check if a string is a valid bool value + inline bool isbool(const std::string_view str) { + return is_in(str, "true", "false", "True", "False"); + } + + //* Convert string to bool, returning any value not equal to "true" or "True" as false + inline bool stobool(const std::string_view str) { + return is_in(str, "true", "True"); + } + + //* Check if a string is a valid integer value (only positive) + constexpr bool isint(const std::string_view str) { + return std::ranges::all_of(str, ::isdigit); + } + + //* Left-trim from and return new string + string_view ltrim(string_view str, string_view t_str = " "); + + //* Right-trim from and return new string + string_view rtrim(string_view str, string_view t_str = " "); + + //* Left/right-trim from and return new string + inline string_view trim(string_view str, string_view t_str = " ") { + return ltrim(rtrim(str, t_str), t_str); + } + + //* Split at all occurrences of and return as vector of strings + constexpr auto ssplit(std::string_view str, char delim = ' ') { + return str | std::views::split(delim) | std::views::filter([](auto&& range) { return !std::ranges::empty(range); }) | + std::ranges::to>(); + } + + //* Put current thread to sleep for milliseconds + inline void sleep_ms(const size_t& ms) { + std::this_thread::sleep_for(std::chrono::milliseconds(ms)); + } + + //* Put current thread to sleep for microseconds + inline void sleep_micros(const size_t& micros) { + std::this_thread::sleep_for(std::chrono::microseconds(micros)); + } + + //* Left justify string if is greater than length, limit return size to by default + string ljust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true); + + //* Right justify string if is greater than length, limit return size to by default + string rjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true); + + //* Center justify string if is greater than length, limit return size to by default + string cjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true); + + //* Replace whitespaces " " with escape code for move right + string trans(const string& str); + + //* Convert seconds to format "d ::" and return string + string sec_to_dhms(size_t seconds, bool no_days = false, bool no_seconds = false); + + //* Scales up in steps of 1024 to highest positive value unit and returns string with unit suffixed + //* bit=true or defaults to bytes + //* start=int to set 1024 multiplier starting unit + //* shorten=true shortens value to at most 3 characters and shortens unit to 1 character + string floating_humanizer(uint64_t value, bool shorten = false, size_t start = 0, bool bit = false, bool per_second = false); + + //* Add std::string operator * : Repeat string number of times + std::string operator*(const string& str, int64_t n); + + template +#ifdef BTOP_DEBUG + const T& safeVal(const std::unordered_map& map, const K& key, const T& fallback = T{}, std::source_location loc = std::source_location::current()) { + if (auto it = map.find(key); it != map.end()) { + return it->second; + } else { + Logger::error("safeVal() called with invalid key: [{}] in file: {} on line: {}", key, loc.file_name(), loc.line()); + return fallback; + } + }; +#else + const T& safeVal(const std::unordered_map& map, const K& key, const T& fallback = T{}) { + if (auto it = map.find(key); it != map.end()) { + return it->second; + } else { + Logger::error("safeVal() called with invalid key: [{}] (Compile btop with DEBUG=true for more extensive logging!)", key); + return fallback; + } + }; +#endif + + template +#ifdef BTOP_DEBUG + const T& safeVal(const std::vector& vec, const size_t& index, const T& fallback = T{}, std::source_location loc = std::source_location::current()) { + if (index < vec.size()) { + return vec[index]; + } else { + Logger::error("safeVal() called with invalid index: [{}] in file: {} on line: {}", index, loc.file_name(), loc.line()); + return fallback; + } + }; +#else + const T& safeVal(const std::vector& vec, const size_t& index, const T& fallback = T{}) { + if (index < vec.size()) { + return vec[index]; + } else { + Logger::error("safeVal() called with invalid index: [{}] (Compile btop with DEBUG=true for more extensive logging!)", index); + return fallback; + } + }; +#endif + + + + //* Return current time in format + string strf_time(const string& strf); + + string hostname(); + string username(); + + void atomic_wait(const atomic& atom, bool old = true) noexcept; + + //* Sets atomic to true on construct, sets to false on destruct + class atomic_lock { + atomic& atom; + public: + explicit atomic_lock(atomic& atom, bool wait = false); + ~atomic_lock() noexcept; + atomic_lock(const atomic_lock& other) = delete; + atomic_lock& operator=(const atomic_lock& other) = delete; + atomic_lock(atomic_lock&& other) = delete; + atomic_lock& operator=(atomic_lock&& other) = delete; + }; + + class atomic_waiting_lock { + bool value{}; + mutable std::mutex mtx; + mutable std::condition_variable cv; + + public: + class guard { + atomic_waiting_lock& atom; + public: + explicit guard(atomic_waiting_lock& atom, bool wait = false); + ~guard() noexcept; + guard(const guard& other) = delete; + guard& operator=(const guard& other) = delete; + guard(guard&& other) = delete; + guard& operator=(guard&& other) = delete; + }; + + void store(bool value) noexcept; + void wait(bool old = true) const noexcept; + void wait_for(bool old, uint64_t wait_ms) const noexcept; + [[nodiscard]] guard lock(bool wait = false); + explicit operator bool() const noexcept; + }; + + void atomic_wait(const atomic_waiting_lock& atom, bool old = true) noexcept; + + void atomic_wait_for(const atomic_waiting_lock& atom, bool old = true, const uint64_t wait_ms = 0); + + //* Read a complete file and return as a string + string readfile(const std::filesystem::path& path, const string& fallback = ""); + + //* Convert a celsius value to celsius, fahrenheit, kelvin or rankin and return tuple with new value and unit. + auto celsius_to(const long long& celsius, const string& scale) -> tuple; +} + +namespace Tools { + //* Creates a named timer that is started on construct (by default) and reports elapsed time in microseconds to Logger::debug() on destruct if running + //* Unless delayed_report is set to false, all reporting is buffered and delayed until DebugTimer is destructed or .force_report() is called + //* Usage example: Tools::DebugTimer timer(name:"myTimer", [start:true], [delayed_report:true]) // Create timer and start + //* timer.stop(); // Stop timer and report elapsed time + //* timer.stop_rename_reset("myTimer2"); // Stop timer, report elapsed time, rename timer, reset and restart + class DebugTimer { + uint64_t start_time{}; + uint64_t elapsed_time{}; + bool running{}; + std::locale custom_locale = std::locale(std::locale::classic(), new Tools::MyNumPunct); + vector report_buffer{}; + string name{}; + bool delayed_report{}; + public: + DebugTimer() = default; + explicit DebugTimer(string name, bool start = true, bool delayed_report = true); + ~DebugTimer(); + DebugTimer(const DebugTimer& other) = delete; + DebugTimer& operator=(const DebugTimer& other) = delete; + DebugTimer(DebugTimer&& other) = delete; + DebugTimer& operator=(DebugTimer&& other) = delete; + + void start(); + void stop(bool report = true); + void reset(bool restart = true); + //* Stops and reports (default), renames timer then resets and restarts (default) + void stop_rename_reset(const string& new_name, bool report = true, bool restart = true); + void report(); + void force_report(); + uint64_t elapsed(); + bool is_running(); + }; + +} diff --git a/vendor/btop/src/linux/btop_collect.cpp b/vendor/btop/src/linux/btop_collect.cpp new file mode 100644 index 000000000..fe4c8ba47 --- /dev/null +++ b/vendor/btop/src/linux/btop_collect.cpp @@ -0,0 +1,3643 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include // for inet_ntop() +#include +#include +#include +#include +#include +#include + +#include +#include + +#if defined(RSMI_STATIC) + #include +#endif + +#if !(defined(STATIC_BUILD) && defined(__GLIBC__)) + #include +#endif + +#include "../btop_config.hpp" +#include "../btop_log.hpp" +#include "../btop_shared.hpp" +#include "../btop_tools.hpp" + +#if defined(GPU_SUPPORT) + // Redefining C++ keywords fortunately has a warning in clang, however it's unavoidable here + // since the C library uses "class" as a struct member and keywords are not allowed to be used + // as identifiers in C++. + #if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wkeyword-macro" + #endif // __clang__ + + #define class class_ +extern "C" { + #include "intel_gpu_top/intel_gpu_top.h" +} + #undef class + + #if defined(__clang__) + #pragma clang diagnostic pop + #endif // __clang__ +#endif + +using std::abs; +using std::clamp; +using std::cmp_greater; +using std::cmp_less; +using std::ifstream; +using std::max; +using std::min; +using std::numeric_limits; +using std::round; +using std::streamsize; +using std::vector; +using std::future; +using std::async; +using std::pair; + + +namespace fs = std::filesystem; +namespace rng = std::ranges; + +using namespace Tools; +using namespace std::literals; // for operator""s +using namespace std::chrono_literals; +//? --------------------------------------------------- FUNCTIONS ----------------------------------------------------- + +namespace +{ + +long long get_monotonicTimeUSec() +{ + struct timespec time; + clock_gettime(CLOCK_MONOTONIC, &time); + return time.tv_sec * 1000000 + time.tv_nsec / 1000; +} + +// Wrapper with join behavior of std::jthread to avoid -fexperimental-library +// flag usage for Clang 19, ideally replace once flag is no longer needed. +struct join_thread +{ + std::thread t; + + join_thread() noexcept = default; + + template + explicit join_thread(Args&&... args) : t(std::forward(args)...) {} + + ~join_thread() { if (t.joinable()) t.join(); } + + join_thread(join_thread&&) noexcept = default; + + join_thread& operator=(join_thread&& other) noexcept { + if (t.joinable()) t.join(); + t = std::move(other.t); + return *this; + } + + void join() { + t.join(); + } + +}; + +} + +namespace Cpu { + vector core_old_totals; + vector core_old_idles; + vector core_freq; + vector available_fields = {"Auto", "total"}; + vector available_sensors = {"Auto"}; + cpu_info current_cpu; + bool got_sensors{}; + bool cpu_temp_only{}; + bool supports_watts = true; + + //* Populate found_sensors map + bool get_sensors(); + + //* Get current cpu clock speed + string get_cpuHz(); + + //* Search /proc/cpuinfo for a cpu name + string get_cpuName(); + + struct Sensor { + fs::path path; + int64_t temp{}; + int64_t crit{}; + }; + + std::unordered_map found_sensors; + string cpu_sensor; + vector core_sensors; + std::unordered_map core_mapping; +} + +#if defined(GPU_SUPPORT) + +namespace Gpu { + vector gpus; + //? NVIDIA data collection + namespace Nvml { + //? NVML defines, structs & typedefs + #define NVML_DEVICE_NAME_BUFFER_SIZE 64 + #define NVML_SUCCESS 0 + #define NVML_TEMPERATURE_THRESHOLD_SHUTDOWN 0 + #define NVML_CLOCK_GRAPHICS 0 + #define NVML_CLOCK_MEM 2 + #define NVML_TEMPERATURE_GPU 0 + #define NVML_PCIE_UTIL_TX_BYTES 0 + #define NVML_PCIE_UTIL_RX_BYTES 1 + + typedef void* nvmlDevice_t; // we won't be accessing any of the underlying struct's properties, so this is fine + typedef int nvmlReturn_t, // enums are basically ints + nvmlTemperatureThresholds_t, + nvmlClockType_t, + nvmlPstates_t, + nvmlTemperatureSensors_t, + nvmlPcieUtilCounter_t; + + struct nvmlUtilization_t {unsigned int gpu, memory;}; + struct nvmlMemory_t {unsigned long long total, free, used;}; + + //? Function pointers + const char* (*nvmlErrorString)(nvmlReturn_t); + nvmlReturn_t (*nvmlInit)(); + nvmlReturn_t (*nvmlShutdown)(); + nvmlReturn_t (*nvmlDeviceGetCount)(unsigned int*); + nvmlReturn_t (*nvmlDeviceGetHandleByIndex)(unsigned int, nvmlDevice_t*); + nvmlReturn_t (*nvmlDeviceGetName)(nvmlDevice_t, char*, unsigned int); + nvmlReturn_t (*nvmlDeviceGetPowerManagementLimit)(nvmlDevice_t, unsigned int*); + nvmlReturn_t (*nvmlDeviceGetTemperatureThreshold)(nvmlDevice_t, nvmlTemperatureThresholds_t, unsigned int*); + nvmlReturn_t (*nvmlDeviceGetUtilizationRates)(nvmlDevice_t, nvmlUtilization_t*); + nvmlReturn_t (*nvmlDeviceGetClockInfo)(nvmlDevice_t, nvmlClockType_t, unsigned int*); + nvmlReturn_t (*nvmlDeviceGetPowerUsage)(nvmlDevice_t, unsigned int*); + nvmlReturn_t (*nvmlDeviceGetPowerState)(nvmlDevice_t, nvmlPstates_t*); + nvmlReturn_t (*nvmlDeviceGetTemperature)(nvmlDevice_t, nvmlTemperatureSensors_t, unsigned int*); + nvmlReturn_t (*nvmlDeviceGetMemoryInfo)(nvmlDevice_t, nvmlMemory_t*); + nvmlReturn_t (*nvmlDeviceGetPcieThroughput)(nvmlDevice_t, nvmlPcieUtilCounter_t, unsigned int*); + nvmlReturn_t (*nvmlDeviceGetEncoderUtilization)(nvmlDevice_t, unsigned int*, unsigned int*); + nvmlReturn_t (*nvmlDeviceGetDecoderUtilization)(nvmlDevice_t, unsigned int*, unsigned int*); + + //? Data + void* nvml_dl_handle; + bool initialized = false; + bool init(); + bool shutdown(); + template bool collect(gpu_info* gpus_slice); + vector devices; + unsigned int device_count = 0; + } + + //? AMD data collection + namespace Rsmi { + + //? RSMI defines, structs & typedefs + #define RSMI_DEVICE_NAME_BUFFER_SIZE 128 + + #if !defined(RSMI_STATIC) + #define RSMI_MAX_NUM_FREQUENCIES_V5 32 + #define RSMI_MAX_NUM_FREQUENCIES_V6 33 + #define RSMI_STATUS_SUCCESS 0 + #define RSMI_MEM_TYPE_VRAM 0 + #define RSMI_TEMP_CURRENT 0 + #define RSMI_TEMP_TYPE_EDGE 0 + #define RSMI_CLK_TYPE_MEM 4 + #define RSMI_CLK_TYPE_SYS 0 + #define RSMI_TEMP_MAX 1 + + typedef int rsmi_status_t, + rsmi_temperature_metric_t, + rsmi_clk_type_t, + rsmi_memory_type_t; + + struct rsmi_version_t {uint32_t major, minor, patch; const char* build;}; + struct rsmi_frequencies_t_v5 {uint32_t num_supported, current; uint64_t frequency[RSMI_MAX_NUM_FREQUENCIES_V5];}; + struct rsmi_frequencies_t_v6 {bool has_deep_sleep; uint32_t num_supported, current; uint64_t frequency[RSMI_MAX_NUM_FREQUENCIES_V6];}; + + //? Function pointers + rsmi_status_t (*rsmi_init)(uint64_t); + rsmi_status_t (*rsmi_shut_down)(); + rsmi_status_t (*rsmi_version_get)(rsmi_version_t*); + rsmi_status_t (*rsmi_num_monitor_devices)(uint32_t*); + rsmi_status_t (*rsmi_dev_name_get)(uint32_t, char*, size_t); + rsmi_status_t (*rsmi_dev_power_cap_get)(uint32_t, uint32_t, uint64_t*); + rsmi_status_t (*rsmi_dev_temp_metric_get)(uint32_t, uint32_t, rsmi_temperature_metric_t, int64_t*); + rsmi_status_t (*rsmi_dev_busy_percent_get)(uint32_t, uint32_t*); + rsmi_status_t (*rsmi_dev_memory_busy_percent_get)(uint32_t, uint32_t*); + rsmi_status_t (*rsmi_dev_gpu_clk_freq_get_v5)(uint32_t, rsmi_clk_type_t, rsmi_frequencies_t_v5*); + rsmi_status_t (*rsmi_dev_gpu_clk_freq_get_v6)(uint32_t, rsmi_clk_type_t, rsmi_frequencies_t_v6*); + rsmi_status_t (*rsmi_dev_power_ave_get)(uint32_t, uint32_t, uint64_t*); + rsmi_status_t (*rsmi_dev_memory_total_get)(uint32_t, rsmi_memory_type_t, uint64_t*); + rsmi_status_t (*rsmi_dev_memory_usage_get)(uint32_t, rsmi_memory_type_t, uint64_t*); + rsmi_status_t (*rsmi_dev_pci_throughput_get)(uint32_t, uint64_t*, uint64_t*, uint64_t*); + + uint32_t version_major = 0; + + //? Data + void* rsmi_dl_handle; + #endif + bool initialized = false; + bool init(); + bool shutdown(); + template bool collect(gpu_info* gpus_slice); + uint32_t device_count = 0; + } + + + //? Intel data collection + namespace Intel { + const char* device = "i915"; + struct engines *engines = nullptr; + + bool initialized = false; + bool init(); + bool shutdown(); + template bool collect(gpu_info* gpus_slice); + uint32_t device_count = 0; + } + + //? AMD sysfs (consumer GPU / iGPU) data collection — fallback when amd-smi/rocm-smi + //? cannot enumerate (e.g. APUs without /dev/kfd, or systems without ROCm libs installed). + //? Reads only standard amdgpu DRM sysfs nodes; no library dependency. + namespace Asysfs { + struct device_paths { + std::filesystem::path device; + std::filesystem::path hwmon; + std::filesystem::path power; //? empty if no power sensor + uint32_t pci_device_id; + bool has_temp; + bool has_freq; + bool has_busy; + bool has_vram; + }; + + bool initialized = false; + bool init(); + bool shutdown(); + template bool collect(gpu_info* gpus_slice); + uint32_t device_count = 0; + vector devices; + } +} + +#endif // GPU_SUPPORT + +namespace Mem { + double old_uptime; +} + +namespace Shared { + + fs::path procPath, passwd_path; + long pageSize, clkTck, coreCount; + + void init() { + + //? Shared global variables init + procPath = (fs::is_directory(fs::path("/proc")) and access("/proc", R_OK) != -1) ? "/proc" : ""; + if (procPath.empty()) + throw std::runtime_error("Proc filesystem not found or no permission to read from it!"); + + passwd_path = (fs::is_regular_file(fs::path("/etc/passwd")) and access("/etc/passwd", R_OK) != -1) ? "/etc/passwd" : ""; + if (passwd_path.empty()) + Logger::warning("Could not read /etc/passwd, will show UID instead of username."); + + coreCount = sysconf(_SC_NPROCESSORS_ONLN); + if (coreCount < 1) { + coreCount = sysconf(_SC_NPROCESSORS_CONF); + if (coreCount < 1) { + coreCount = 1; + Logger::warning("Could not determine number of cores, defaulting to 1."); + } + } + + pageSize = sysconf(_SC_PAGE_SIZE); + if (pageSize <= 0) { + pageSize = 4096; + Logger::warning("Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect."); + } + + clkTck = sysconf(_SC_CLK_TCK); + if (clkTck <= 0) { + clkTck = 100; + Logger::warning("Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect."); + } + + //? Init for namespace Cpu + Cpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {}); + Cpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {}); + Cpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0); + Cpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0); + + for (int i = 0; i < Shared::coreCount; ++i) { + Cpu::core_freq.push_back("/sys/devices/system/cpu/cpufreq/policy" + to_string(i) + "/scaling_cur_freq"); + if (not fs::exists(Cpu::core_freq.back()) or access(Cpu::core_freq.back().c_str(), R_OK) == -1) { + Cpu::core_freq.pop_back(); + } + } + + Cpu::collect(); + if (Runner::coreNum_reset) Runner::coreNum_reset = false; + for (auto& [field, vec] : Cpu::current_cpu.cpu_percent) { + if (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field); + } + Cpu::cpuName = Cpu::get_cpuName(); + Cpu::got_sensors = Cpu::get_sensors(); + for (const auto& [sensor, ignored] : Cpu::found_sensors) { + Cpu::available_sensors.push_back(sensor); + } + Cpu::core_mapping = Cpu::get_core_mapping(); + + Cpu::container_engine = detect_container(); + + //? Init for namespace Gpu + #ifdef GPU_SUPPORT + auto shown_gpus = Config::getS("shown_gpus"); + if (shown_gpus.contains("nvidia")) { + Gpu::Nvml::init(); + } + + if (shown_gpus.contains("amd")) { + Gpu::Rsmi::init(); + Gpu::Asysfs::init(); //? self-skips when rocm-smi already enumerated devices + } + + if (shown_gpus.contains("intel")) { + Gpu::Intel::init(); + } + + if (not Gpu::gpu_names.empty()) { + for (auto const& [key, _] : Gpu::gpus[0].gpu_percent) + Cpu::available_fields.push_back(key); + for (auto const& [key, _] : Gpu::shared_gpu_percent) + Cpu::available_fields.push_back(key); + + using namespace Gpu; + count = gpus.size(); + gpu_b_height_offsets.resize(gpus.size()); + for (size_t i = 0; i < gpu_b_height_offsets.size(); ++i) + gpu_b_height_offsets[i] = gpus[i].supported_functions.gpu_utilization + + gpus[i].supported_functions.pwr_usage + + (gpus[i].supported_functions.encoder_utilization or gpus[i].supported_functions.decoder_utilization) + + (gpus[i].supported_functions.mem_total or gpus[i].supported_functions.mem_used) + * (1 + 2*(gpus[i].supported_functions.mem_total and gpus[i].supported_functions.mem_used) + 2*gpus[i].supported_functions.mem_utilization); + } + #endif + + //? Init for namespace Mem + Mem::old_uptime = system_uptime(); + Mem::collect(); + + Logger::debug("Shared::init() : Initialized."); + } +} + +namespace Cpu { + string cpuName; + string cpuHz; + bool has_battery = true; + tuple current_bat; + + const array time_names { + "user"s, "nice"s, "system"s, "idle"s, "iowait"s, + "irq"s, "softirq"s, "steal"s, "guest"s, "guest_nice"s + }; + + std::unordered_map cpu_old = { + {"totals", 0}, + {"idles", 0}, + {"user", 0}, + {"nice", 0}, + {"system", 0}, + {"idle", 0}, + {"iowait", 0}, + {"irq", 0}, + {"softirq", 0}, + {"steal", 0}, + {"guest", 0}, + {"guest_nice", 0} + }; + + string get_cpuName() { + string name; + ifstream cpuinfo(Shared::procPath / "cpuinfo"); + if (cpuinfo.good()) { + for (string instr; getline(cpuinfo, instr, ':') and not instr.starts_with("model name");) + cpuinfo.ignore(SSmax, '\n'); + if (cpuinfo.bad()) return name; + else if (not cpuinfo.eof()) { + cpuinfo.ignore(1); + getline(cpuinfo, name); + } + else if (fs::exists("/sys/devices")) { + for (const auto& d : fs::directory_iterator("/sys/devices")) { + if (string(d.path().filename()).starts_with("arm")) { + name = d.path().filename(); + break; + } + } + if (not name.empty()) { + auto name_vec = ssplit(name, '_'); + if (name_vec.size() < 2) return capitalize(name); + else return capitalize(name_vec.at(1)) + (name_vec.size() > 2 ? ' ' + capitalize(name_vec.at(2)) : ""); + } + + } + + name = trim_name(name); + } + + return name; + } + + bool get_sensors() { + bool got_cpu = false, got_coretemp = false; + vector search_paths; + try { + //? Setup up paths to search for sensors + if (fs::exists(fs::path("/sys/class/hwmon")) and access("/sys/class/hwmon", R_OK) != -1) { + for (const auto& dir : fs::directory_iterator(fs::path("/sys/class/hwmon"))) { + fs::path add_path = fs::canonical(dir.path()); + if (v_contains(search_paths, add_path) or v_contains(search_paths, add_path / "device")) continue; + + if (std::string_view { add_path.c_str() }.contains("coretemp")) + got_coretemp = true; + + for (const auto & file : fs::directory_iterator(add_path)) { + if (file.path().filename() == "device") { + for (const auto & dev_file : fs::directory_iterator(file.path())) { + string dev_filename = dev_file.path().filename(); + if (dev_filename.starts_with("temp") and dev_filename.ends_with("_input")) { + search_paths.push_back(file.path()); + break; + } + } + } + + string filename = file.path().filename(); + if (filename.starts_with("temp") and filename.ends_with("_input")) { + search_paths.push_back(add_path); + break; + } + } + } + } + if (not got_coretemp and fs::exists(fs::path("/sys/devices/platform/coretemp.0/hwmon"))) { + for (auto& d : fs::directory_iterator(fs::path("/sys/devices/platform/coretemp.0/hwmon"))) { + fs::path add_path = fs::canonical(d.path()); + + for (const auto & file : fs::directory_iterator(add_path)) { + string filename = file.path().filename(); + if (filename.starts_with("temp") and filename.ends_with("_input") and not v_contains(search_paths, add_path)) { + search_paths.push_back(add_path); + got_coretemp = true; + break; + } + } + } + } + //? Scan any found directories for temperature sensors + if (not search_paths.empty()) { + for (const auto& path : search_paths) { + const string pname = readfile(path / "name", path.filename()); + for (const auto & file : fs::directory_iterator(path)) { + const string file_suffix = "input"; + const int file_id = atoi(file.path().filename().c_str() + 4); // skip "temp" prefix + string file_path = file.path(); + + if (!file_path.contains(file_suffix) or file_path.contains("nvme")) { + continue; + } + + const string basepath = file_path.erase(file_path.find(file_suffix), file_suffix.length()); + const string label = readfile(fs::path(basepath + "label"), "temp" + to_string(file_id)); + const string sensor_name = pname + "/" + label; + const int64_t temp = stol(readfile(fs::path(basepath + "input"), "0")) / 1000; + const int64_t crit = stol(readfile(fs::path(basepath + "crit"), "95000")) / 1000; + + found_sensors[sensor_name] = Sensor { fs::path(basepath + "input"), temp, crit }; + + if (not got_cpu and (label.starts_with("Package id") or label.starts_with("Tdie") or label.starts_with("SoC Temperature"))) { + got_cpu = true; + cpu_sensor = sensor_name; + } + else if (label.starts_with("Core") or label.starts_with("Tccd")) { + got_coretemp = true; + if (not v_contains(core_sensors, sensor_name)) core_sensors.push_back(sensor_name); + } + } + } + } + //? If no good candidate for cpu temp has been found scan /sys/class/thermal + if (not got_cpu and fs::exists(fs::path("/sys/class/thermal"))) { + const string rootpath = fs::path("/sys/class/thermal/thermal_zone"); + for (int i = 0; fs::exists(fs::path(rootpath + to_string(i))); i++) { + const fs::path basepath = rootpath + to_string(i); + if (not fs::exists(basepath / "temp")) continue; + const string label = readfile(basepath / "type", "temp" + to_string(i)); + const string sensor_name = "thermal" + to_string(i) + "/" + label; + const int64_t temp = stol(readfile(basepath / "temp", "0")) / 1000; + + int64_t high = 0; + int64_t crit = 0; + for (int ii = 0; fs::exists(basepath / fmt::format("trip_point_{}_temp", ii)); ii++) { + const string trip_type = readfile(basepath / fmt::format("trip_point_{}_type", ii)); + if (not is_in(trip_type, "high", "critical")) continue; + auto& val = (trip_type == "high" ? high : crit); + val = stol(readfile(basepath / fmt::format("trip_point_{}_temp", ii), "0")) / 1000; + } + if (high < 1) high = 80; + if (crit < 1) crit = 95; + + found_sensors[sensor_name] = Sensor { basepath / "temp", temp, crit }; + } + } + + } + catch (...) {} + + if (not got_coretemp or core_sensors.empty()) { + cpu_temp_only = true; + } + else { + rng::sort(core_sensors, rng::less{}); + rng::stable_sort(core_sensors, [](const auto& a, const auto& b){ + return a.size() < b.size(); + }); + } + + if (cpu_sensor.empty() and not found_sensors.empty()) { + for (const auto& [name, sensor] : found_sensors) { + if (str_to_lower(name).contains("cpu") or str_to_lower(name).contains("k10temp")) { + cpu_sensor = name; + break; + } + } + if (cpu_sensor.empty()) { + cpu_sensor = found_sensors.begin()->first; + Logger::warning("No good candidate for cpu sensor found, using random from all found sensors."); + } + } + + return not found_sensors.empty(); + } + + static void update_sensors() { + if (cpu_sensor.empty()) return; + + const auto& cpu_sensor = (not Config::getS("cpu_sensor").empty() and found_sensors.contains(Config::getS("cpu_sensor")) ? Config::getS("cpu_sensor") : Cpu::cpu_sensor); + + found_sensors.at(cpu_sensor).temp = stol(readfile(found_sensors.at(cpu_sensor).path, "0")) / 1000; + current_cpu.temp.at(0).push_back(found_sensors.at(cpu_sensor).temp); + current_cpu.temp_max = found_sensors.at(cpu_sensor).crit; + if (current_cpu.temp.at(0).size() > 20) current_cpu.temp.at(0).pop_front(); + + if (Config::getB("show_coretemp") and not cpu_temp_only) { + for (vector done; const auto& sensor : core_sensors) { + if (v_contains(done, sensor)) continue; + found_sensors.at(sensor).temp = stol(readfile(found_sensors.at(sensor).path, "0")) / 1000; + done.push_back(sensor); + } + for (const auto& [core, temp] : core_mapping) { + if (cmp_less(core + 1, current_cpu.temp.size()) and cmp_less(temp, core_sensors.size())) { + current_cpu.temp.at(core + 1).push_back(found_sensors.at(core_sensors.at(temp)).temp); + if (current_cpu.temp.at(core + 1).size() > 20) current_cpu.temp.at(core + 1).pop_front(); + } + } + } + } + + static string normalize_frequency(double hz) { + string str; + if (hz > 999999) { + str = fmt::format("{:.1f}", hz / 1'000'000); + str.resize(3); + if (str.back() == '.') str.pop_back(); + str += " THz"; + } + else if (hz > 999) { + str = fmt::format("{:.1f}", hz / 1'000); + str.resize(3); + if (str.back() == '.') str.pop_back(); + str += " GHz"; + } + else { + str = fmt::format("{:.0f} MHz", hz); + } + return str; + } + + string get_cpuHz() { + static int failed{}; + + if (failed > 4) + return ""s; + + string cpuhz; + + const auto &freq_mode = Config::getS("freq_mode"); + + try { + double hz = 0.0; + // Read frequencies from all CPU cores + vector frequencies; + for (auto it = Cpu::core_freq.begin(); it != Cpu::core_freq.end(); ) { + if (it->empty()) { + it = Cpu::core_freq.erase(it); + continue; + } + + double core_hz = stod(readfile(*it, "0.0")) / 1000; + if (core_hz <= 0.0 and ++failed >= 2) { + it = Cpu::core_freq.erase(it); + } else { + frequencies.push_back(core_hz); + if (freq_mode == "first") break; + ++it; + } + } + + if (not frequencies.empty()) { + if (freq_mode == "first") { + hz = frequencies.front(); + } + if (freq_mode == "average") { + hz = std::accumulate(frequencies.begin(), frequencies.end(), 0.0) / static_cast(frequencies.size()); + } + else if (freq_mode == "highest") { + hz = *std::max_element(frequencies.begin(), frequencies.end()); + } + else if (freq_mode == "lowest") { + hz = *std::min_element(frequencies.begin(), frequencies.end()); + } + else if (freq_mode == "range") { + auto [min_hz,max_hz] = std::minmax_element(frequencies.begin(), frequencies.end()); + + // Format as range + string min_str, max_str; + min_str = normalize_frequency(*min_hz); + max_str = normalize_frequency(*max_hz); + + return min_str + " - " + max_str; + } + } + //? If freq from /sys failed or is missing try to use /proc/cpuinfo + if (hz <= 0.0) { + ifstream cpufreq(Shared::procPath / "cpuinfo"); + if (cpufreq.good()) { + while (cpufreq.ignore(SSmax, '\n')) { + // peek is caps sensitive so it was skipping 'CPU MHz'. This aims to fix it. + if (cpufreq.peek() == 'c' || cpufreq.peek() == 'C') { + cpufreq.ignore(SSmax, ' '); + if (cpufreq.peek() == 'M') { + cpufreq.ignore(SSmax, ':'); + cpufreq.ignore(1); + cpufreq >> hz; + break; + } + } + } + } + } + + if (hz <= 1 or hz >= 999999999) + throw std::runtime_error("Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo."); + + cpuhz = normalize_frequency(hz); + + } + catch (const std::exception& e) { + if (++failed < 5) + return ""s; + else { + Logger::warning("get_cpuHZ() : {}", e.what()); + return ""s; + } + } + + return cpuhz; + } + + auto get_core_mapping() -> std::unordered_map { + std::unordered_map core_map; + if (cpu_temp_only) return core_map; + + const int num_sensors = core_sensors.size(); + + //? Try to get core mapping from /proc/cpuinfo + ifstream cpuinfo(Shared::procPath / "cpuinfo"); + if (cpuinfo.good()) { + int cpu{}; + int core{}; + int max_core{}; + std::unordered_map cpu_to_core; + for (string instr; cpuinfo >> instr;) { + if (instr == "processor") { + cpuinfo.ignore(SSmax, ':'); + cpuinfo >> cpu; + } + else if (instr.starts_with("core")) { + cpuinfo.ignore(SSmax, ':'); + cpuinfo >> core; + cpu_to_core[cpu] = core; + max_core = std::max(max_core, core); + } + cpuinfo.ignore(SSmax, '\n'); + } + if (not cpu_to_core.empty()) + //? Divide core ID space evenly across sensors (handles AMD multi-CCD, e.g. 5950x: IDs 0-7 -> Tccd1, 8-15 -> Tccd2) + for (const auto& [cpu_id, core_id] : cpu_to_core) { + core_map[cpu_id] = core_id * num_sensors / (max_core + 1); + } + } + + //? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc. + if (cmp_less(core_map.size(), Shared::coreCount)) { + if (Shared::coreCount % 2 == 0 and (long)core_map.size() == Shared::coreCount / 2) { + //? SMT siblings mirror their first half of cores. + for (int i = 0; i < Shared::coreCount / 2; i++) { + core_map[Shared::coreCount / 2 + i] = core_map.count(i) ? core_map.at(i) : (i % num_sensors); + } + } + else { + core_map.clear(); + for (int i = 0; i < Shared::coreCount; i++) { + core_map[i] = (i * num_sensors) / Shared::coreCount; + } + } + } + + //? Apply user set custom mapping if any + const auto& custom_map = Config::getS("cpu_core_map"); + if (not custom_map.empty()) { + try { + for (const auto& split : ssplit(custom_map)) { + const auto vals = ssplit(split, ':'); + if (vals.size() != 2) continue; + int change_id = std::stoi(vals.at(0)); + int new_id = std::stoi(vals.at(1)); + if (not core_map.contains(change_id) or cmp_greater(new_id, num_sensors)) continue; + core_map.at(change_id) = new_id; + } + } + catch (...) {} + } + + return core_map; + } + + struct battery { + fs::path base_dir, energy_now, charge_now, energy_full, charge_full, power_now, current_now, voltage_now, status, online; + string device_type; + bool use_energy_or_charge = true; + bool use_power = true; + }; + + auto get_battery() -> tuple { + if (not has_battery) return {0, 0, 0, ""}; + static string auto_sel; + static std::unordered_map batteries; + + //? Get paths to needed files and check for valid values on first run + if (batteries.empty() and has_battery) { + try { + if (fs::exists("/sys/class/power_supply")) { + for (const auto& d : fs::directory_iterator("/sys/class/power_supply")) { + //? Only consider online power supplies of type Battery or UPS + //? see kernel docs for details on the file structure and contents + //? https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-power + battery new_bat; + fs::path bat_dir; + try { + if (not d.is_directory() + or not fs::exists(d.path() / "type") + or not fs::exists(d.path() / "present") + or stoi(readfile(d.path() / "present")) != 1) + continue; + string dev_type = readfile(d.path() / "type"); + if (is_in(dev_type, "Battery", "UPS")) { + bat_dir = d.path(); + new_bat.base_dir = d.path(); + new_bat.device_type = dev_type; + } + } catch (...) { + //? skip power supplies not conforming to the kernel standard + continue; + } + + if (fs::exists(bat_dir / "energy_now")) new_bat.energy_now = bat_dir / "energy_now"; + else if (fs::exists(bat_dir / "charge_now")) new_bat.charge_now = bat_dir / "charge_now"; + else new_bat.use_energy_or_charge = false; + + if (fs::exists(bat_dir / "energy_full")) new_bat.energy_full = bat_dir / "energy_full"; + else if (fs::exists(bat_dir / "charge_full")) new_bat.charge_full = bat_dir / "charge_full"; + else new_bat.use_energy_or_charge = false; + + if (not new_bat.use_energy_or_charge and not fs::exists(bat_dir / "capacity")) { + continue; + } + + if (fs::exists(bat_dir / "power_now")) { + new_bat.power_now = bat_dir / "power_now"; + } + else if ((fs::exists(bat_dir / "current_now")) and (fs::exists(bat_dir / "voltage_now"))) { + new_bat.current_now = bat_dir / "current_now"; + new_bat.voltage_now = bat_dir / "voltage_now"; + } + else { + new_bat.use_power = false; + } + + if (fs::exists(bat_dir / "AC0/online")) new_bat.online = bat_dir / "AC0/online"; + else if (fs::exists(bat_dir / "AC/online")) new_bat.online = bat_dir / "AC/online"; + + batteries[bat_dir.filename()] = new_bat; + Config::available_batteries.push_back(bat_dir.filename()); + } + } + } + catch (...) { + batteries.clear(); + } + if (batteries.empty()) { + has_battery = false; + return {0, 0, 0, ""}; + } + } + + auto& battery_sel = Config::getS("selected_battery"); + + if (auto_sel.empty()) { + for (auto& [name, bat] : batteries) { + if (bat.device_type == "Battery") { + auto_sel = name; + break; + } + } + if (auto_sel.empty()) auto_sel = batteries.begin()->first; + } + + auto& b = (battery_sel != "Auto" and batteries.contains(battery_sel) ? batteries.at(battery_sel) : batteries.at(auto_sel)); + + int percent = -1; + long seconds = -1; + float watts = -1; + + //? Try to get battery percentage + if (percent < 0) { + try { + percent = stoi(readfile(b.base_dir / "capacity", "-1")); + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + if (b.use_energy_or_charge and percent < 0) { + try { + percent = round(100.0 * stod(readfile(b.energy_now, "-1")) / stod(readfile(b.energy_full, "1"))); + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + if (b.use_energy_or_charge and percent < 0) { + try { + percent = round(100.0 * stod(readfile(b.charge_now, "-1")) / stod(readfile(b.charge_full, "1"))); + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + if (percent < 0) { + has_battery = false; + return {0, 0, 0, ""}; + } + + //? Get charging/discharging status + string status = str_to_lower(readfile(b.base_dir / "status", "unknown")); + if (status == "unknown" and not b.online.empty()) { + const auto online = readfile(b.online, "0"); + if (online == "1" and percent < 100) status = "charging"; + else if (online == "1") status = "full"; + else status = "discharging"; + } + + //? Get seconds to empty + if (not is_in(status, "charging", "full")) { + if (b.use_energy_or_charge ) { + if (not b.power_now.empty()) { + try { + seconds = abs(round(stod(readfile(b.energy_now, "0")) / stod(readfile(b.power_now, "1")) * 3600)); + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + else if (not b.current_now.empty()) { + try { + seconds = abs(round(stod(readfile(b.charge_now, "0")) / stod(readfile(b.current_now, "1")) * 3600)); + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + } + + if (seconds < 0 and fs::exists(b.base_dir / "time_to_empty")) { + try { + seconds = stoll(readfile(b.base_dir / "time_to_empty", "0")) * 60; + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + } + //? Or get seconds to full + else if(is_in(status, "charging")) { + if (b.use_energy_or_charge ) { + if (not b.power_now.empty()) { + try { + seconds = (round(stod(readfile(b.energy_full , "0")) - round(stod(readfile(b.energy_now, "0")))) + / abs(stod(readfile(b.power_now, "1"))) * 3600); + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + else if (not b.current_now.empty()) { + try { + seconds = (round(stod(readfile(b.charge_full , "0")) - stod(readfile(b.charge_now, "0"))) + / std::abs(stod(readfile(b.current_now, "1"))) * 3600); + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + } + } + + //? Get power draw + if (b.use_power) { + if (not b.power_now.empty()) { + try { + watts = stof(readfile(b.power_now, "-1")) / 1000000.0F; + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + else if (not b.voltage_now.empty() and not b.current_now.empty()) { + try { + watts = stof(readfile(b.current_now, "-1")) / 1000000.0F * stof(readfile(b.voltage_now, "1")) / 1000000.0F; + } + catch (const std::invalid_argument&) { } + catch (const std::out_of_range&) { } + } + + } + + return {percent, watts, seconds, status}; + } + + long long get_cpuConsumptionUJoules() + { + long long consumption = -1; + const auto rapl_power_usage_path = "/sys/class/powercap/intel-rapl:0/energy_uj"; + std::ifstream file(rapl_power_usage_path); + if(file.good()) + { + file >> consumption; + } + return consumption; + } + + float get_cpuConsumptionWatts() + { + static long long previous_usage = 0; + static long long previous_timestamp = 0; + + if (previous_usage == 0) + { + previous_usage = get_cpuConsumptionUJoules(); + previous_timestamp = get_monotonicTimeUSec(); + supports_watts = (previous_usage > 0); + return 0; + } + + if (!supports_watts) + { + return -1; + } + + auto current_timestamp = get_monotonicTimeUSec(); + auto current_usage = get_cpuConsumptionUJoules(); + + auto watts = (float)(current_usage - previous_usage) / (float)(current_timestamp - previous_timestamp); + + previous_timestamp = current_timestamp; + previous_usage = current_usage; + + return watts; + } + + static constexpr auto to_int(std::string_view view) { + std::uint32_t value {}; + std::from_chars(view.data(), view.data() + view.size(), value); + return value; + } + + static constexpr auto detect_active_cpus() { + auto stream = std::ifstream { "/sys/fs/cgroup/cpuset.cpus.effective" }; + auto buf = std::string { std::istreambuf_iterator { stream }, {} }; + + if (buf.empty()) { + return std::views::iota(0, Shared::coreCount) | std::ranges::to>(); + } + + return buf | std::views::split(',') | std::views::transform([](auto&& range) -> auto { + auto view = std::string_view { range }; + auto dash = view.find('-'); + + if (dash == std::string_view::npos) { + // Single CPU, return iota of single element + auto value = to_int(view); + return std::views::iota(value, value + 1); + } + + auto start = to_int(view.substr(0, dash)); + auto end = to_int(view.substr(dash + 1)); + return std::views::iota(start, end + 1); + }) | + std::views::join | std::ranges::to>(); + } + + auto collect(bool no_update) -> cpu_info& { + if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) return current_cpu; + auto& cpu = current_cpu; + + if (Config::getB("show_cpu_freq")) + cpuHz = get_cpuHz(); + + if (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) { + Logger::error("failed to get load averages"); + } + + ifstream cread; + + try { + //? Get cpu total times for all cores from /proc/stat + string cpu_name; + cread.open(Shared::procPath / "stat"); + int i = 0; + int target = Shared::coreCount; + for (; i <= target or (cread.good() and cread.peek() == 'c'); i++) { + //? Make sure to add zero value for missing core values if at end of file + if ((not cread.good() or cread.peek() != 'c') and i <= target) { + if (i == 0) throw std::runtime_error("Failed to parse /proc/stat"); + else { + //? Fix container sizes if new cores are detected + while (cmp_less(cpu.core_percent.size(), i)) { + core_old_totals.push_back(0); + core_old_idles.push_back(0); + cpu.core_percent.emplace_back(); + } + cpu.core_percent.at(i-1).push_back(0); + } + } + else { + if (i == 0) cread.ignore(SSmax, ' '); + else { + cread >> cpu_name; + int cpuNum = std::stoi(cpu_name.substr(3)); + if (cpuNum >= target - 1) target = cpuNum + (cread.peek() == 'c' ? 2 : 1); + + //? Add zero value for core if core number is missing from /proc/stat + while (i - 1 < cpuNum) { + //? Fix container sizes if new cores are detected + while (cmp_less(cpu.core_percent.size(), i)) { + core_old_totals.push_back(0); + core_old_idles.push_back(0); + cpu.core_percent.emplace_back(); + } + cpu.core_percent[i-1].push_back(0); + if (cpu.core_percent.at(i-1).size() > 40) cpu.core_percent.at(i-1).pop_front(); + i++; + } + } + + //? Expected on kernel 2.6.3> : 0=user, 1=nice, 2=system, 3=idle, 4=iowait, 5=irq, 6=softirq, 7=steal, 8=guest, 9=guest_nice + vector times; + long long total_sum = 0; + + for (uint64_t val; cread >> val; total_sum += val) { + times.push_back(val); + } + cread.clear(); + if (times.size() < 4) throw std::runtime_error("Malformed /proc/stat"); + + //? Subtract fields 8-9 and any future unknown fields + const long long totals = max(0ll, total_sum - (times.size() > 8 ? std::accumulate(times.begin() + 8, times.end(), 0ll) : 0)); + + //? Add iowait field if present + const long long idles = max(0ll, times.at(3) + (times.size() > 4 ? times.at(4) : 0)); + + //? Calculate values for totals from first line of stat + if (i == 0) { + const long long calc_totals = max(1ll, totals - cpu_old.at("totals")); + const long long calc_idles = max(0ll, idles - cpu_old.at("idles")); + cpu_old.at("totals") = totals; + cpu_old.at("idles") = idles; + + //? Total usage of cpu + cpu.cpu_percent.at("total").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll)); + + //? Reduce size if there are more values than needed for graph + while (cmp_greater(cpu.cpu_percent.at("total").size(), width * 2)) cpu.cpu_percent.at("total").pop_front(); + + //? Populate cpu.cpu_percent with all fields from stat + for (int ii = 0; const auto& val : times) { + cpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll)); + cpu_old.at(time_names.at(ii)) = val; + + //? Reduce size if there are more values than needed for graph + while (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front(); + + if (++ii == 10) break; + } + continue; + } + //? Calculate cpu total for each core + else { + //? Fix container sizes if new cores are detected + while (cmp_less(cpu.core_percent.size(), i)) { + core_old_totals.push_back(0); + core_old_idles.push_back(0); + cpu.core_percent.emplace_back(); + } + const long long calc_totals = max(1ll, totals - core_old_totals.at(i-1)); + const long long calc_idles = max(0ll, idles - core_old_idles.at(i-1)); + core_old_totals.at(i-1) = totals; + core_old_idles.at(i-1) = idles; + + cpu.core_percent.at(i-1).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll)); + } + } + + //? Reduce size if there are more values than needed for graph + if (cpu.core_percent.at(i-1).size() > 40) cpu.core_percent.at(i-1).pop_front(); + } + + //? Notify main thread to redraw screen if we found more cores than previously detected + if (cmp_greater(cpu.core_percent.size(), Shared::coreCount)) { + Logger::debug("Changing CPU max corecount from {} to {}.", Shared::coreCount, cpu.core_percent.size()); + Runner::coreNum_reset = true; + Shared::coreCount = cpu.core_percent.size(); + while (cmp_less(current_cpu.temp.size(), cpu.core_percent.size() + 1)) current_cpu.temp.push_back({0}); + } + + } + catch (const std::exception& e) { + Logger::debug("Cpu::collect() : {}", e.what()); + if (cread.bad()) throw std::runtime_error("Failed to read /proc/stat"); + else throw std::runtime_error(fmt::format("Cpu::collect() : {}", e.what())); + } + + if (Config::getB("check_temp") and got_sensors) + update_sensors(); + + if (Config::getB("show_battery") and has_battery) + current_bat = get_battery(); + + if (Config::getB("show_cpu_watts") and supports_watts) + current_cpu.usage_watts = get_cpuConsumptionWatts(); + + cpu.active_cpus = std::make_optional(detect_active_cpus()); + + return cpu; + } +} + +#ifdef GPU_SUPPORT +namespace Gpu { + //? NVIDIA + namespace Nvml { + bool init() { + if (initialized) return false; + + //? Dynamic loading & linking + //? Try possible library names for libnvidia-ml.so + const array libNvAlts = { + "libnvidia-ml.so", + "libnvidia-ml.so.1", + }; + + for (const auto& l : libNvAlts) { + nvml_dl_handle = dlopen(l, RTLD_LAZY); + if (nvml_dl_handle != nullptr) { + break; + } + } + if (!nvml_dl_handle) { + Logger::info("Failed to load libnvidia-ml.so, NVIDIA GPUs will not be detected: {}", dlerror()); + return false; + } + + auto load_nvml_sym = [&](const char sym_name[]) { + auto sym = dlsym(nvml_dl_handle, sym_name); + auto err = dlerror(); + if (err != nullptr) { + Logger::error("NVML: Couldn't find function {}: {}", sym_name, err); + return (void*)nullptr; + } else return sym; + }; + + #define LOAD_SYM(NAME) if ((NAME = (decltype(NAME))load_nvml_sym(#NAME)) == nullptr) return false + + LOAD_SYM(nvmlErrorString); + LOAD_SYM(nvmlInit); + LOAD_SYM(nvmlShutdown); + LOAD_SYM(nvmlDeviceGetCount); + LOAD_SYM(nvmlDeviceGetHandleByIndex); + LOAD_SYM(nvmlDeviceGetName); + LOAD_SYM(nvmlDeviceGetPowerManagementLimit); + LOAD_SYM(nvmlDeviceGetTemperatureThreshold); + LOAD_SYM(nvmlDeviceGetUtilizationRates); + LOAD_SYM(nvmlDeviceGetClockInfo); + LOAD_SYM(nvmlDeviceGetPowerUsage); + LOAD_SYM(nvmlDeviceGetPowerState); + LOAD_SYM(nvmlDeviceGetTemperature); + LOAD_SYM(nvmlDeviceGetMemoryInfo); + LOAD_SYM(nvmlDeviceGetPcieThroughput); + LOAD_SYM(nvmlDeviceGetEncoderUtilization); + LOAD_SYM(nvmlDeviceGetDecoderUtilization); + + #undef LOAD_SYM + + //? Function calls + nvmlReturn_t result = nvmlInit(); + if (result != NVML_SUCCESS) { + Logger::debug("Failed to initialize NVML, NVIDIA GPUs will not be detected: {}", nvmlErrorString(result)); + return false; + } + + //? Device count + result = nvmlDeviceGetCount(&device_count); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get device count: {}", nvmlErrorString(result)); + return false; + } + + if (device_count > 0) { + devices.resize(device_count); + gpus.resize(device_count); + gpu_names.resize(device_count); + + initialized = true; + + //? Check supported functions & get maximums + Nvml::collect<1>(gpus.data()); + + return true; + } else {initialized = true; shutdown(); return false;} + } + + bool shutdown() { + if (!initialized) return false; + nvmlReturn_t result = nvmlShutdown(); + if (NVML_SUCCESS == result) { + initialized = false; + dlclose(nvml_dl_handle); + } else Logger::warning("Failed to shutdown NVML: {}", nvmlErrorString(result)); + + return !initialized; + } + + template // collect<1> is called in Nvml::init(), and populates gpus.supported_functions + bool collect(gpu_info* gpus_slice) { // raw pointer to vector data, size == device_count + if (!initialized) return false; + + nvmlReturn_t result; + join_thread pcie_tx_thread; + join_thread pcie_rx_thread; + // DebugTimer nvTotalTimer("Nvidia Total"); + for (unsigned int i = 0; i < device_count; ++i) { + if constexpr(is_init) { + //? Device Handle + result = nvmlDeviceGetHandleByIndex(i, devices.data() + i); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get device handle: {}", nvmlErrorString(result)); + gpus[i].supported_functions = {false, false, false, false, false, false, false, false, false, false}; + continue; + } + + //? Device name + char name[NVML_DEVICE_NAME_BUFFER_SIZE]; + result = nvmlDeviceGetName(devices[i], name, NVML_DEVICE_NAME_BUFFER_SIZE); + if (result != NVML_SUCCESS) + Logger::warning("NVML: Failed to get device name: {}", nvmlErrorString(result)); + else { + gpu_names[i] = string(name); + for (const auto& brand : {"NVIDIA", "Nvidia", "(R)", "(TM)"}) { + gpu_names[i] = s_replace(gpu_names[i], brand, ""); + } + gpu_names[i] = trim(gpu_names[i]); + } + + //? Power usage + unsigned int max_power; + result = nvmlDeviceGetPowerManagementLimit(devices[i], &max_power); + if (result != NVML_SUCCESS) + Logger::warning("NVML: Failed to get maximum GPU power draw, defaulting to 225W: {}", nvmlErrorString(result)); + else { + gpus[i].pwr_max_usage = max_power; // RSMI reports power in microWatts + gpu_pwr_total_max += max_power; + } + + //? Get temp_max + unsigned int temp_max; + result = nvmlDeviceGetTemperatureThreshold(devices[i], NVML_TEMPERATURE_THRESHOLD_SHUTDOWN, &temp_max); + if (result != NVML_SUCCESS) + Logger::warning("NVML: Failed to get maximum GPU temperature, defaulting to 110°C: {}", nvmlErrorString(result)); + else gpus[i].temp_max = (long long)temp_max; + } + + //? PCIe link speeds, the data collection takes >=20ms each call so they run on separate threads + if (gpus_slice[i].supported_functions.pcie_txrx and (Config::getB("nvml_measure_pcie_speeds") or is_init)) { + pcie_tx_thread = join_thread([gpus_slice, i]() { + unsigned int tx; + nvmlReturn_t result = nvmlDeviceGetPcieThroughput(devices[i], NVML_PCIE_UTIL_TX_BYTES, &tx); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get PCIe TX throughput: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.pcie_txrx = false; + } else gpus_slice[i].pcie_tx = (long long)tx; + }); + + pcie_rx_thread = join_thread([gpus_slice, i]() { + unsigned int rx; + nvmlReturn_t result = nvmlDeviceGetPcieThroughput(devices[i], NVML_PCIE_UTIL_RX_BYTES, &rx); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get PCIe RX throughput: {}", nvmlErrorString(result)); + } else gpus_slice[i].pcie_rx = (long long)rx; + }); + } else { + gpus_slice[i].pcie_tx = -1; + gpus_slice[i].pcie_rx = -1; + } + + // DebugTimer nvTimer("Nv utilization"); + //? GPU & memory utilization + if (gpus_slice[i].supported_functions.gpu_utilization) { + nvmlUtilization_t utilization; + result = nvmlDeviceGetUtilizationRates(devices[i], &utilization); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get GPU utilization: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_utilization = false; + if constexpr(is_init) gpus_slice[i].supported_functions.mem_utilization = false; + } else { + gpus_slice[i].gpu_percent.at("gpu-totals").push_back((long long)utilization.gpu); + gpus_slice[i].mem_utilization_percent.push_back((long long)utilization.memory); + } + } + + // nvTimer.stop_rename_reset("Nv clock"); + //? Clock speeds + if (gpus_slice[i].supported_functions.gpu_clock) { + unsigned int gpu_clock; + result = nvmlDeviceGetClockInfo(devices[i], NVML_CLOCK_GRAPHICS, &gpu_clock); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get GPU clock speed: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false; + } else gpus_slice[i].gpu_clock_speed = (long long)gpu_clock; + } + + if (gpus_slice[i].supported_functions.mem_clock) { + unsigned int mem_clock; + result = nvmlDeviceGetClockInfo(devices[i], NVML_CLOCK_MEM, &mem_clock); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get VRAM clock speed: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false; + } else gpus_slice[i].mem_clock_speed = (long long)mem_clock; + } + + // nvTimer.stop_rename_reset("Nv power"); + //? Power usage & state + if (gpus_slice[i].supported_functions.pwr_usage) { + unsigned int power; + result = nvmlDeviceGetPowerUsage(devices[i], &power); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get GPU power usage: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.pwr_usage = false; + } else { + gpus_slice[i].pwr_usage = (long long)power; + if (gpus_slice[i].pwr_usage > gpus_slice[i].pwr_max_usage) + gpus_slice[i].pwr_max_usage = gpus_slice[i].pwr_usage; + gpus_slice[i].gpu_percent.at("gpu-pwr-totals").push_back(clamp((long long)round((double)gpus_slice[i].pwr_usage * 100.0 / (double)gpus_slice[i].pwr_max_usage), 0ll, 100ll)); + } + } + + if (gpus_slice[i].supported_functions.pwr_state) { + nvmlPstates_t pState; + result = nvmlDeviceGetPowerState(devices[i], &pState); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get GPU power state: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.pwr_state = false; + } else gpus_slice[i].pwr_state = static_cast(pState); + } + + // nvTimer.stop_rename_reset("Nv temp"); + //? GPU temperature + if (gpus_slice[i].supported_functions.temp_info) { + if (Config::getB("check_temp")) { + unsigned int temp; + nvmlReturn_t result = nvmlDeviceGetTemperature(devices[i], NVML_TEMPERATURE_GPU, &temp); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get GPU temperature: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.temp_info = false; + } else gpus_slice[i].temp.push_back((long long)temp); + } + } + + // nvTimer.stop_rename_reset("Nv mem"); + //? Memory info + if (gpus_slice[i].supported_functions.mem_total) { + nvmlMemory_t memory; + result = nvmlDeviceGetMemoryInfo(devices[i], &memory); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get VRAM info: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_total = false; + if constexpr(is_init) gpus_slice[i].supported_functions.mem_used = false; + } else { + gpus_slice[i].mem_total = memory.total; + gpus_slice[i].mem_used = memory.used; + //gpu.mem_free = memory.free; + + auto used_percent = (long long)round((double)memory.used * 100.0 / (double)memory.total); + gpus_slice[i].gpu_percent.at("gpu-vram-totals").push_back(used_percent); + } + } + + // nvTimer.stop_rename_reset("Nv enc"); + //? Encoder info + if (gpus_slice[i].supported_functions.encoder_utilization) { + unsigned int utilization; + unsigned int samplingPeriodUs; + result = nvmlDeviceGetEncoderUtilization(devices[i], &utilization, &samplingPeriodUs); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get encoder utilization: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.encoder_utilization = false; + } else gpus_slice[i].encoder_utilization = (long long)utilization; + } + + // nvTimer.stop_rename_reset("Nv dec"); + //? Decoder info + if (gpus_slice[i].supported_functions.decoder_utilization) { + unsigned int utilization; + unsigned int samplingPeriodUs; + result = nvmlDeviceGetDecoderUtilization(devices[i], &utilization, &samplingPeriodUs); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get decoder utilization: {}", nvmlErrorString(result)); + if constexpr(is_init) gpus_slice[i].supported_functions.decoder_utilization = false; + } else gpus_slice[i].decoder_utilization = (long long)utilization; + } + + //? TODO: Processes using GPU + /*unsigned int proc_info_len; + nvmlProcessInfo_t* proc_info = 0; + result = nvmlDeviceGetComputeRunningProcesses_v3(device, &proc_info_len, proc_info); + if (result != NVML_SUCCESS) { + Logger::warning("NVML: Failed to get compute processes: {}", nvmlErrorString(result)); + } else { + for (unsigned int i = 0; i < proc_info_len; ++i) + gpus_slice[i].graphics_processes.push_back({proc_info[i].pid, proc_info[i].usedGpuMemory}); + }*/ + + // nvTimer.stop_rename_reset("Nv pcie thread join"); + //? Join PCIE TX/RX threads + if constexpr(is_init) { // there doesn't seem to be a better way to do this, but this should be fine considering it's just 2 lines + pcie_tx_thread.join(); + pcie_rx_thread.join(); + } else if (gpus_slice[i].supported_functions.pcie_txrx and Config::getB("nvml_measure_pcie_speeds")) { + pcie_tx_thread.join(); + pcie_rx_thread.join(); + } + } + + return true; + } + } + + //? AMD + namespace Rsmi { + bool init() { + if (initialized) return false; + + //? Dynamic loading & linking + #if !defined(RSMI_STATIC) + + //? Try possible library paths and names for librocm_smi64.so + const array libRocAlts = { + "/opt/rocm/lib/librocm_smi64.so", + "librocm_smi64.so", + "librocm_smi64.so.5", // fedora + "librocm_smi64.so.1.0", // debian + "librocm_smi64.so.6", + "librocm_smi64.so.7" // rocm 7 support / Ubuntu 26.04 + }; + + for (const auto& l : libRocAlts) { + rsmi_dl_handle = dlopen(l, RTLD_LAZY); + if (rsmi_dl_handle != nullptr) { + break; + } + } + + if (!rsmi_dl_handle) { + Logger::info("Failed to load librocm_smi64.so, AMD GPUs will not be detected: {}", dlerror()); + return false; + } + + auto load_rsmi_sym = [&](const char sym_name[]) { + auto sym = dlsym(rsmi_dl_handle, sym_name); + auto err = dlerror(); + if (err != nullptr) { + Logger::error("ROCm SMI: Couldn't find function {}: {}", sym_name, err); + return (void*)nullptr; + } else return sym; + }; + + #define LOAD_SYM(NAME) if ((NAME = (decltype(NAME))load_rsmi_sym(#NAME)) == nullptr) return false + + LOAD_SYM(rsmi_init); + LOAD_SYM(rsmi_shut_down); + LOAD_SYM(rsmi_version_get); + LOAD_SYM(rsmi_num_monitor_devices); + LOAD_SYM(rsmi_dev_name_get); + LOAD_SYM(rsmi_dev_power_cap_get); + LOAD_SYM(rsmi_dev_temp_metric_get); + LOAD_SYM(rsmi_dev_busy_percent_get); + LOAD_SYM(rsmi_dev_memory_busy_percent_get); + LOAD_SYM(rsmi_dev_power_ave_get); + LOAD_SYM(rsmi_dev_memory_total_get); + LOAD_SYM(rsmi_dev_memory_usage_get); + LOAD_SYM(rsmi_dev_pci_throughput_get); + + #undef LOAD_SYM + #endif + + //? Function calls + rsmi_status_t result = rsmi_init(0); + if (result != RSMI_STATUS_SUCCESS) { + Logger::debug("Failed to initialize ROCm SMI, AMD GPUs will not be detected"); + return false; + } + + #if !defined(RSMI_STATIC) + //? Check version + rsmi_version_t version; + result = rsmi_version_get(&version); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get version"); + return false; + } + + // Two distinct real-world libraries report version.major == 1: + // - ROCm 7.2 ships the v6 ABI (see upstream PR #1566). + // - Debian/Ubuntu's librocm-smi64 is built from 5.x sources but + // rocm_smi64Config.h reports version 1.0.0, so the ABI is v5. + // Probe a 6.x-only symbol to disambiguate instead of guessing. + uint32_t effective_major = version.major; + if (version.major == 1) { + bool has_v6_symbol = (dlsym(rsmi_dl_handle, "rsmi_dev_activity_metric_get") != nullptr); + (void)dlerror(); // clear error state from the probe + effective_major = has_v6_symbol ? 6 : 5; + Logger::warning("ROCm SMI: library reports version 1.x; assuming {}.x ABI based on symbol probe", + has_v6_symbol ? "6" : "5"); + } + + if (effective_major == 5) { + if ((rsmi_dev_gpu_clk_freq_get_v5 = (decltype(rsmi_dev_gpu_clk_freq_get_v5))load_rsmi_sym("rsmi_dev_gpu_clk_freq_get")) == nullptr) + return false; + // In the release tarballs of rocm 6.0.0 and 6.0.2 the version queried with rsmi_version_get is 7.0.0.0 + } else if (effective_major == 6 || effective_major == 7) { + if ((rsmi_dev_gpu_clk_freq_get_v6 = (decltype(rsmi_dev_gpu_clk_freq_get_v6))load_rsmi_sym("rsmi_dev_gpu_clk_freq_get")) == nullptr) + return false; + } else { + Logger::warning("ROCm SMI: Dynamic loading only supported for version 5 and 6"); + return false; + } + version_major = effective_major; + #endif + + //? Device count + result = rsmi_num_monitor_devices(&device_count); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to fetch number of devices"); + return false; + } + + if (device_count > 0) { + gpus.resize(gpus.size() + device_count); + gpu_names.resize(gpus.size() + device_count); + + initialized = true; + + //? Check supported functions & get maximums + Rsmi::collect<1>(gpus.data() + Nvml::device_count); + + return true; + } else {initialized = true; shutdown(); return false;} + } + + bool shutdown() { + if (!initialized) return false; + if (rsmi_shut_down() == RSMI_STATUS_SUCCESS) { + initialized = false; + #if !defined(RSMI_STATIC) + dlclose(rsmi_dl_handle); + #endif + } else Logger::warning("Failed to shutdown ROCm SMI"); + + return true; + } + + template + bool collect(gpu_info* gpus_slice) { // raw pointer to vector data, size == device_count, offset by Nvml::device_count elements + if (!initialized) return false; + rsmi_status_t result; + + for (uint32_t i = 0; i < device_count; ++i) { + if constexpr(is_init) { + //? Device name + char name[RSMI_DEVICE_NAME_BUFFER_SIZE]; + result = rsmi_dev_name_get(i, name, RSMI_DEVICE_NAME_BUFFER_SIZE); + if (result != RSMI_STATUS_SUCCESS) + Logger::warning("ROCm SMI: Failed to get device name"); + else gpu_names[Nvml::device_count + i] = string(name); + + //? Power usage + uint64_t max_power; + result = rsmi_dev_power_cap_get(i, 0, &max_power); + if (result != RSMI_STATUS_SUCCESS) + Logger::warning("ROCm SMI: Failed to get maximum GPU power draw, defaulting to 225W"); + else { + gpus_slice[i].pwr_max_usage = (long long)(max_power/1000); // RSMI reports power in microWatts + gpu_pwr_total_max += gpus_slice[i].pwr_max_usage; + } + + //? Get temp_max + int64_t temp_max; + result = rsmi_dev_temp_metric_get(i, RSMI_TEMP_TYPE_EDGE, RSMI_TEMP_MAX, &temp_max); + if (result != RSMI_STATUS_SUCCESS) + Logger::warning("ROCm SMI: Failed to get maximum GPU temperature, defaulting to 110°C"); + else gpus_slice[i].temp_max = (long long)temp_max; + + //? Disable encoder and decoder utilisation on AMD + gpus_slice[i].supported_functions.encoder_utilization = false; + gpus_slice[i].supported_functions.decoder_utilization = false; + } + + //? GPU utilization + if (gpus_slice[i].supported_functions.gpu_utilization) { + uint32_t utilization; + result = rsmi_dev_busy_percent_get(i, &utilization); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get GPU utilization"); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_utilization = false; + } else gpus_slice[i].gpu_percent.at("gpu-totals").push_back((long long)utilization); + } + + //? Memory utilization + if (gpus_slice[i].supported_functions.mem_utilization) { + uint32_t utilization; + result = rsmi_dev_memory_busy_percent_get(i, &utilization); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get VRAM utilization"); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_utilization = false; + } else gpus_slice[i].mem_utilization_percent.push_back((long long)utilization); + } + #if !defined(RSMI_STATIC) + //? Clock speeds + // Some AMD devices (e.g. integrated GPUs with the Debian 5.7.0 rocm_smi package) return + // RSMI_STATUS_SUCCESS from rsmi_dev_gpu_clk_freq_get but leave frequencies.current + // uninitialized, which crashes when used as an array index. Bound-check before indexing. + if (gpus_slice[i].supported_functions.gpu_clock) { + if (version_major == 5) { + rsmi_frequencies_t_v5 frequencies{}; + result = rsmi_dev_gpu_clk_freq_get_v5(i, RSMI_CLK_TYPE_SYS, &frequencies); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get GPU clock speed: "); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false; + } else if (frequencies.num_supported == 0 || frequencies.current >= frequencies.num_supported + || frequencies.num_supported > RSMI_MAX_NUM_FREQUENCIES_V5) { + Logger::warning("ROCm SMI: GPU clock speed unsupported on this device"); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false; + } else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz + } + else if (version_major == 6 || version_major == 7) { + rsmi_frequencies_t_v6 frequencies{}; + result = rsmi_dev_gpu_clk_freq_get_v6(i, RSMI_CLK_TYPE_SYS, &frequencies); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get GPU clock speed: "); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false; + } else if (frequencies.num_supported == 0 || frequencies.current >= frequencies.num_supported + || frequencies.num_supported > RSMI_MAX_NUM_FREQUENCIES_V6) { + Logger::warning("ROCm SMI: GPU clock speed unsupported on this device"); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false; + } else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz + } + } + + if (gpus_slice[i].supported_functions.mem_clock) { + if (version_major == 5) { + rsmi_frequencies_t_v5 frequencies{}; + result = rsmi_dev_gpu_clk_freq_get_v5(i, RSMI_CLK_TYPE_MEM, &frequencies); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get VRAM clock speed: "); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false; + } else if (frequencies.num_supported == 0 || frequencies.current >= frequencies.num_supported + || frequencies.num_supported > RSMI_MAX_NUM_FREQUENCIES_V5) { + Logger::warning("ROCm SMI: VRAM clock speed unsupported on this device"); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false; + } else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz + } + else if (version_major == 6 || version_major == 7) { + rsmi_frequencies_t_v6 frequencies{}; + result = rsmi_dev_gpu_clk_freq_get_v6(i, RSMI_CLK_TYPE_MEM, &frequencies); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get VRAM clock speed: "); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false; + } else if (frequencies.num_supported == 0 || frequencies.current >= frequencies.num_supported + || frequencies.num_supported > RSMI_MAX_NUM_FREQUENCIES_V6) { + Logger::warning("ROCm SMI: VRAM clock speed unsupported on this device"); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false; + } else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz + } + } + #else + //? Clock speeds + // Same defensive pattern as the dynamic path above: bound-check the reported + // frequencies before indexing, in case the driver returns SUCCESS without + // populating the struct. + if (gpus_slice[i].supported_functions.gpu_clock) { + rsmi_frequencies_t frequencies{}; + result = rsmi_dev_gpu_clk_freq_get(i, RSMI_CLK_TYPE_SYS, &frequencies); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get GPU clock speed: "); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false; + } else if (frequencies.num_supported == 0 || frequencies.current >= frequencies.num_supported + || frequencies.num_supported > RSMI_MAX_NUM_FREQUENCIES) { + Logger::warning("ROCm SMI: GPU clock speed unsupported on this device"); + if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false; + } else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz + } + + if (gpus_slice[i].supported_functions.mem_clock) { + rsmi_frequencies_t frequencies{}; + result = rsmi_dev_gpu_clk_freq_get(i, RSMI_CLK_TYPE_MEM, &frequencies); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get VRAM clock speed: "); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false; + } else if (frequencies.num_supported == 0 || frequencies.current >= frequencies.num_supported + || frequencies.num_supported > RSMI_MAX_NUM_FREQUENCIES) { + Logger::warning("ROCm SMI: VRAM clock speed unsupported on this device"); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false; + } else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz + } + #endif + //? Power usage & state + if (gpus_slice[i].supported_functions.pwr_usage) { + uint64_t power; + result = rsmi_dev_power_ave_get(i, 0, &power); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get GPU power usage"); + if constexpr(is_init) gpus_slice[i].supported_functions.pwr_usage = false; + } else { + gpus_slice[i].pwr_usage = (long long)power / 1000; + if (gpus_slice[i].pwr_usage > gpus_slice[i].pwr_max_usage) + gpus_slice[i].pwr_max_usage = gpus_slice[i].pwr_usage; + gpus_slice[i].gpu_percent.at("gpu-pwr-totals").push_back(clamp((long long)round((double)gpus_slice[i].pwr_usage * 100.0 / (double)gpus_slice[i].pwr_max_usage), 0ll, 100ll)); + } + + if constexpr(is_init) gpus_slice[i].supported_functions.pwr_state = false; + } + + //? GPU temperature + if (gpus_slice[i].supported_functions.temp_info) { + if (Config::getB("check_temp") or is_init) { + int64_t temp; + result = rsmi_dev_temp_metric_get(i, RSMI_TEMP_TYPE_EDGE, RSMI_TEMP_CURRENT, &temp); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get GPU temperature"); + if constexpr(is_init) gpus_slice[i].supported_functions.temp_info = false; + } else gpus_slice[i].temp.push_back((long long)temp/1000); + } + } + + //? Memory info + if (gpus_slice[i].supported_functions.mem_total) { + uint64_t total; + result = rsmi_dev_memory_total_get(i, RSMI_MEM_TYPE_VRAM, &total); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get total VRAM"); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_total = false; + } else gpus_slice[i].mem_total = total; + } + + if (gpus_slice[i].supported_functions.mem_used) { + uint64_t used; + result = rsmi_dev_memory_usage_get(i, RSMI_MEM_TYPE_VRAM, &used); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get VRAM usage"); + if constexpr(is_init) gpus_slice[i].supported_functions.mem_used = false; + } else { + gpus_slice[i].mem_used = used; + if (gpus_slice[i].supported_functions.mem_total) + gpus_slice[i].gpu_percent.at("gpu-vram-totals").push_back((long long)round((double)used * 100.0 / (double)gpus_slice[i].mem_total)); + } + } + + //? PCIe link speeds + if ((gpus_slice[i].supported_functions.pcie_txrx and Config::getB("rsmi_measure_pcie_speeds")) or is_init) { + uint64_t tx, rx; + result = rsmi_dev_pci_throughput_get(i, &tx, &rx, nullptr); + if (result != RSMI_STATUS_SUCCESS) { + Logger::warning("ROCm SMI: Failed to get PCIe throughput"); + if constexpr(is_init) gpus_slice[i].supported_functions.pcie_txrx = false; + } else { + gpus_slice[i].pcie_tx = (long long)tx; + gpus_slice[i].pcie_rx = (long long)rx; + } + } else { + gpus_slice[i].pcie_tx = -1; + gpus_slice[i].pcie_rx = -1; + } + } + + return true; + } + } + + namespace Intel { + bool init() { + if (initialized) return false; + + char *gpu_path = find_intel_gpu_dir(); + if (!gpu_path) { + Logger::debug("Failed to find Intel GPU sysfs path, Intel GPUs will not be detected"); + return false; + } + + char *gpu_device_id = get_intel_device_id(gpu_path); + if (!gpu_device_id) { + Logger::debug("Failed to find Intel GPU device ID, Intel GPUs will not be detected"); + return false; + } + + char *gpu_device_name = get_intel_device_name(gpu_device_id); + if (!gpu_device_name) { + Logger::warning("Failed to find Intel GPU device name in internal database"); + } + + free(gpu_device_id); + + engines = discover_engines(device); + if (!engines) { + Logger::debug("Failed to find Intel GPU engines, Intel GPUs will not be detected"); + free(gpu_device_name); + return false; + } + + int ret = pmu_init(engines); + if (ret) { + Logger::warning("Intel GPU: Failed to initialize PMU"); + free(gpu_device_name); + free_engines(engines); + engines = nullptr; + return false; + } + + pmu_sample(engines); + + device_count = 1; + + gpus.resize(gpus.size() + device_count); + gpu_names.resize(gpus.size() + device_count); + + if (gpu_device_name) { + gpu_names[Nvml::device_count + Rsmi::device_count + Asysfs::device_count] = string(gpu_device_name); + } else { + gpu_names[Nvml::device_count + Rsmi::device_count + Asysfs::device_count] = "Intel GPU"; + } + + free(gpu_device_name); + + initialized = true; + Intel::collect<1>(gpus.data() + Nvml::device_count + Rsmi::device_count + Asysfs::device_count); + + return true; + } + + bool shutdown() { + if (!initialized) return false; + if (engines) { + free_engines(engines); + engines = nullptr; + } + initialized = false; + return true; + } + + template bool collect(gpu_info* gpus_slice) { + if (!initialized) return false; + + if constexpr(is_init) { + gpus_slice->supported_functions = { + .gpu_utilization = true, + .mem_utilization = false, + .gpu_clock = true, + .mem_clock = false, + .pwr_usage = true, + .pwr_state = false, + .temp_info = false, + .mem_total = false, + .mem_used = false, + .pcie_txrx = false, + .encoder_utilization = false, + .decoder_utilization = false + }; + + gpus_slice->pwr_max_usage = 10'000; //? 10W + } + + pmu_sample(engines); + double t = (double)(engines->ts.cur - engines->ts.prev) / 1e9; + + double max_util = 0; + for (unsigned int i = 0; i < engines->num_engines; i++) { + struct engine *engine = &(&engines->engine)[i]; + double util = pmu_calc(&engine->busy.val, 1e9, t, 100); + if (util > max_util) { + max_util = util; + } + } + gpus_slice->gpu_percent.at("gpu-totals").push_back((long long)round(max_util)); + + double pwr = pmu_calc(&engines->r_gpu.val, 1, t, engines->r_gpu.scale); // in Watts + gpus_slice->pwr_usage = (long long)round(pwr * 1000); + if (gpus_slice->pwr_usage > gpus_slice->pwr_max_usage) + gpus_slice->pwr_max_usage = gpus_slice->pwr_usage; + + gpus_slice->gpu_percent.at("gpu-pwr-totals").push_back(clamp((long long)round((double)gpus_slice->pwr_usage * 100.0 / (double)gpus_slice->pwr_max_usage), 0ll, 100ll)); + + double freq = pmu_calc(&engines->freq_act.val, 1, t, 1); // in MHz + gpus_slice->gpu_clock_speed = (unsigned int)round(freq); + + return true; + } + } + + namespace Asysfs { + //? Read a sysfs node containing a single integer; return fallback on missing/parse error. + static long long read_ll(const std::filesystem::path& path, long long fallback = 0) { + try { + return std::stoll(readfile(path, std::to_string(fallback))); + } catch (const std::exception&) { + return fallback; + } + } + + //? Match /sys/class/drm/cardN (no '-', all digits after "card"). Skips card1-DP-1, renderD*, etc. + static bool is_card_node(const string& fname) { + if (not fname.starts_with("card") or fname.size() <= 4) return false; + return std::ranges::all_of(fname.begin() + 4, fname.end(), + [](char c) { return c >= '0' and c <= '9'; }); + } + + //? Pick the first hwmon* subdirectory under /hwmon, or empty path if none. + static std::filesystem::path find_hwmon(const std::filesystem::path& device) { + const auto hwmon_dir = device / "hwmon"; + std::error_code ec; + if (not std::filesystem::is_directory(hwmon_dir, ec)) return {}; + for (const auto& h : std::filesystem::directory_iterator(hwmon_dir, ec)) { + if (h.is_directory()) return h.path(); + } + return {}; + } + + bool init() { + if (initialized) return false; + //? Self-skip when rocm-smi already enumerated AMD devices — avoids double-counting on + //? systems where both backends would succeed. + if (Rsmi::device_count > 0) return false; + devices.clear(); + + const std::filesystem::path drm_root("/sys/class/drm"); + std::error_code ec; + if (not std::filesystem::is_directory(drm_root, ec)) { + Logger::debug("amdgpu sysfs: /sys/class/drm not present"); + return false; + } + + for (const auto& entry : std::filesystem::directory_iterator(drm_root, ec)) { + if (not is_card_node(entry.path().filename().string())) continue; + + const auto device_link = entry.path() / "device"; + if (not std::filesystem::exists(device_link)) continue; + + //? Vendor must be exactly 0x1002 (AMD). The sysfs node ends with a newline, + //? so trim before comparing. + string vendor = readfile(device_link / "vendor", ""); + while (not vendor.empty() and (vendor.back() == '\n' or vendor.back() == ' ')) vendor.pop_back(); + if (vendor != "0x1002") continue; + + //? Driver must be amdgpu (rules out radeon-driver-only legacy GPUs which use a + //? different sysfs layout). + const auto driver_link = std::filesystem::read_symlink(device_link / "driver", ec); + if (ec or driver_link.filename().string() != "amdgpu") continue; + + device_paths d{}; + d.device = device_link; + try { + //? "device" file holds e.g. "0x150e\n" — base 0 lets stoul autodetect the 0x prefix. + d.pci_device_id = (uint32_t)std::stoul(readfile(device_link / "device", "0"), nullptr, 0); + } catch (const std::exception&) { + d.pci_device_id = 0; + } + d.hwmon = find_hwmon(device_link); + + d.has_busy = std::filesystem::exists(device_link / "gpu_busy_percent"); + d.has_vram = std::filesystem::exists(device_link / "mem_info_vram_total"); + + if (not d.hwmon.empty()) { + d.has_temp = std::filesystem::exists(d.hwmon / "temp1_input"); + d.has_freq = std::filesystem::exists(d.hwmon / "freq1_input"); + //? Prefer power1_average (filtered, EMA) over power1_input (instantaneous). + const auto avg = d.hwmon / "power1_average"; + const auto inst = d.hwmon / "power1_input"; + if (std::filesystem::exists(avg)) d.power = avg; + else if (std::filesystem::exists(inst)) d.power = inst; + } + + //? Skip cards with no readable signals — virtual GPUs, fresh-bound devices, + //? or driver states where nothing useful is exposed yet. Otherwise btop would + //? render an empty GPU entry every tick. + if (not (d.has_busy or d.has_vram or d.has_temp or d.has_freq or not d.power.empty())) { + Logger::debug("amdgpu sysfs: skipping {} — no readable metrics", device_link.string()); + continue; + } + + devices.push_back(std::move(d)); + } + + device_count = (uint32_t)devices.size(); + if (device_count == 0) { + Logger::debug("amdgpu sysfs: no AMD cards found in /sys/class/drm"); + return false; + } + + gpus.resize(gpus.size() + device_count); + gpu_names.resize(Nvml::device_count + Rsmi::device_count + device_count); + for (uint32_t i = 0; i < device_count; ++i) { + gpu_names[Nvml::device_count + Rsmi::device_count + i] = + fmt::format("AMD GPU (1002:{:04x})", devices[i].pci_device_id); + } + + initialized = true; + Logger::info("Using amdgpu sysfs for {} AMD GPU(s)", device_count); + Asysfs::collect<1>(gpus.data() + Nvml::device_count + Rsmi::device_count); + return true; + } + + bool shutdown() { + if (not initialized) return false; + devices.clear(); + device_count = 0; + initialized = false; + return true; + } + + template bool collect(gpu_info* gpus_slice) { + if (not initialized) return false; + + for (uint32_t i = 0; i < device_count; ++i) { + gpu_info& gpu = gpus_slice[i]; + const device_paths& d = devices[i]; + + if constexpr (is_init) { + gpu.supported_functions = { + .gpu_utilization = d.has_busy, + .mem_utilization = false, + .gpu_clock = d.has_freq, + .mem_clock = false, //? only DPM table is exposed via pp_dpm_mclk, not the current frequency + .pwr_usage = not d.power.empty(), + .pwr_state = false, + .temp_info = d.has_temp, + .mem_total = d.has_vram, + .mem_used = d.has_vram, + .pcie_txrx = false, + .encoder_utilization = false, + .decoder_utilization = false, + }; + //? Start at zero and let the observed peak set the scale, like Intel does (line 1958-ish). + gpu.pwr_max_usage = 0; + } + + if (d.has_busy) { + gpu.gpu_percent.at("gpu-totals").push_back( + std::clamp(read_ll(d.device / "gpu_busy_percent"), 0LL, 100LL)); + } + + if (d.has_temp) { + gpu.temp.push_back(read_ll(d.hwmon / "temp1_input") / 1000); //? millidegrees → degrees + } + + if (not d.power.empty()) { + gpu.pwr_usage = read_ll(d.power) / 1000; //? microwatts → milliwatts + gpu.pwr_max_usage = std::max(gpu.pwr_max_usage, gpu.pwr_usage); + if (gpu.pwr_max_usage > 0) { + gpu.gpu_percent.at("gpu-pwr-totals").push_back( + std::clamp((long long)std::round((double)gpu.pwr_usage * 100.0 / (double)gpu.pwr_max_usage), 0LL, 100LL)); + } + } + + if (d.has_freq) { + gpu.gpu_clock_speed = (unsigned int)(read_ll(d.hwmon / "freq1_input") / 1'000'000); //? Hz → MHz + } + + if (d.has_vram) { + gpu.mem_total = read_ll(d.device / "mem_info_vram_total"); + gpu.mem_used = read_ll(d.device / "mem_info_vram_used"); + if (gpu.mem_total > 0) { + gpu.gpu_percent.at("gpu-vram-totals").push_back( + std::clamp((long long)std::round((double)gpu.mem_used * 100.0 / (double)gpu.mem_total), 0LL, 100LL)); + } + } + } + return true; + } + + //? Explicit template instantiations referenced from Shared::init and Gpu::collect. + template bool collect<0>(gpu_info*); + template bool collect<1>(gpu_info*); + } + + //? Collect data from GPU-specific libraries + auto collect(bool no_update) -> vector& { + if (Runner::stopping or (no_update and not gpus.empty())) return gpus; + + // DebugTimer gpu_timer("GPU Total"); + + //* Collect data + Nvml::collect<0>(gpus.data()); // raw pointer to vector data, size == Nvml::device_count + Rsmi::collect<0>(gpus.data() + Nvml::device_count); // size = Rsmi::device_count + Asysfs::collect<0>(gpus.data() + Nvml::device_count + Rsmi::device_count); // size = Asysfs::device_count + Intel::collect<0>(gpus.data() + Nvml::device_count + Rsmi::device_count + Asysfs::device_count); // size = Intel::device_count + + //* Calculate average usage + long long avg = 0; + long long mem_usage_total = 0; + long long mem_total = 0; + long long pwr_total = 0; + for (auto& gpu : gpus) { + if (gpu.supported_functions.gpu_utilization) + avg += gpu.gpu_percent.at("gpu-totals").back(); + if (gpu.supported_functions.mem_used) + mem_usage_total += gpu.mem_used; + if (gpu.supported_functions.mem_total) + mem_total += gpu.mem_total; + if (gpu.supported_functions.pwr_usage) + pwr_total += gpu.pwr_usage; + + //* Trim vectors if there are more values than needed for graphs + if (width != 0) { + //? GPU & memory utilization + while (cmp_greater(gpu.gpu_percent.at("gpu-totals").size(), width * 2)) gpu.gpu_percent.at("gpu-totals").pop_front(); + while (cmp_greater(gpu.mem_utilization_percent.size(), width)) gpu.mem_utilization_percent.pop_front(); + //? Power usage + while (cmp_greater(gpu.gpu_percent.at("gpu-pwr-totals").size(), width)) gpu.gpu_percent.at("gpu-pwr-totals").pop_front(); + //? Temperature + while (cmp_greater(gpu.temp.size(), 18)) gpu.temp.pop_front(); + //? Memory usage + while (cmp_greater(gpu.gpu_percent.at("gpu-vram-totals").size(), width/2)) gpu.gpu_percent.at("gpu-vram-totals").pop_front(); + } + } + + shared_gpu_percent.at("gpu-average").push_back(avg / gpus.size()); + if (mem_total != 0) + shared_gpu_percent.at("gpu-vram-total").push_back(static_cast(round(mem_usage_total * 100.0 / mem_total))); + if (gpu_pwr_total_max != 0) + shared_gpu_percent.at("gpu-pwr-total").push_back(clamp(static_cast(round(pwr_total * 100.0 / gpu_pwr_total_max)), 0ll, 100ll)); + + if (width != 0) { + while (cmp_greater(shared_gpu_percent.at("gpu-average").size(), width * 2)) shared_gpu_percent.at("gpu-average").pop_front(); + while (cmp_greater(shared_gpu_percent.at("gpu-pwr-total").size(), width * 2)) shared_gpu_percent.at("gpu-pwr-total").pop_front(); + while (cmp_greater(shared_gpu_percent.at("gpu-vram-total").size(), width * 2)) shared_gpu_percent.at("gpu-vram-total").pop_front(); + } + + count = gpus.size(); + + return gpus; + } +} +#endif + +/// Convert ascii escapes like \040 into chars. +static auto convert_ascii_escapes(const std::string& input) -> std::string { + std::string out; + out.reserve(input.size()); + + for (std::size_t i = 0; i < input.size(); ++i) { + if (input[i] == '\\' && + // Peek the next three characters. + i + 3 < input.size() && + std::isdigit(input[i + 1]) && + std::isdigit(input[i + 2]) && + std::isdigit(input[i + 3])) { + + // Convert octal chars to decimal int. + // '0' - '0' -> 0, '4' - '0' -> 4, '0' - '0' -> 0. + // 0 * 64 (0) + // + 4 * 8 (32) + // + 0 + // = 32 (ascii space) + int value = ((input[i + 1] - '0') * 64) + ((input[i + 2] - '0') * 8) + (input[i + 3] - '0'); + out.push_back(static_cast(value)); + // Consume the three digits. + i += 3; + } else { + out.push_back(input[i]); + } + } + return out; +} + +namespace Mem { + bool has_swap{}; + vector fstab; + fs::file_time_type fstab_time; + int disk_ios{}; + vector last_found; + + //?* Find the filepath to the specified ZFS object's stat file + fs::path get_zfs_stat_file(const string& device_name, size_t dataset_name_start, bool zfs_hide_datasets); + + //?* Collect total ZFS pool io stats + bool zfs_collect_pool_total_stats(struct disk_info &disk); + + mem_info current_mem {}; + + uint64_t get_totalMem() { + ifstream meminfo(Shared::procPath / "meminfo"); + int64_t totalMem = 0; + if (meminfo.good()) { + meminfo.ignore(SSmax, ':'); + meminfo >> totalMem; + totalMem <<= 10; + } + if (not meminfo.good() or totalMem == 0) + throw std::runtime_error("Could not get total memory size from /proc/meminfo"); + + return totalMem; + } + + auto collect(bool no_update) -> mem_info& { + if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) return current_mem; + auto show_swap = Config::getB("show_swap"); + auto swap_disk = Config::getB("swap_disk"); + auto show_disks = Config::getB("show_disks"); + auto zfs_arc_cached = Config::getB("zfs_arc_cached"); + auto totalMem = get_totalMem(); + auto& mem = current_mem; + + mem.stats.at("swap_total") = 0; + + //? Read ZFS ARC info from /proc/spl/kstat/zfs/arcstats + uint64_t arc_size = 0, arc_min_size = 0; + if (zfs_arc_cached) { + ifstream arcstats(Shared::procPath / "spl/kstat/zfs/arcstats"); + if (arcstats.good()) { + for (string label; arcstats >> label;) { + if (label == "c_min") { + arcstats >> arc_min_size >> arc_min_size; // double read skips type column + } + else if (label == "size") { + arcstats >> arc_size >> arc_size; + break; + } + } + } + arcstats.close(); + } + + //? Read memory info from /proc/meminfo + ifstream meminfo(Shared::procPath / "meminfo"); + if (meminfo.good()) { + bool got_avail = false; + for (string label; meminfo.peek() != 'D' and meminfo >> label;) { + if (label == "MemFree:") { + meminfo >> mem.stats.at("free"); + mem.stats.at("free") <<= 10; + } + else if (label == "MemAvailable:") { + meminfo >> mem.stats.at("available"); + mem.stats.at("available") <<= 10; + got_avail = true; + } + else if (label == "Cached:") { + meminfo >> mem.stats.at("cached"); + mem.stats.at("cached") <<= 10; + if (not show_swap and not swap_disk) break; + } + else if (label == "SwapTotal:") { + meminfo >> mem.stats.at("swap_total"); + mem.stats.at("swap_total") <<= 10; + } + else if (label == "SwapFree:") { + meminfo >> mem.stats.at("swap_free"); + mem.stats.at("swap_free") <<= 10; + break; + } + meminfo.ignore(SSmax, '\n'); + } + if (not got_avail) mem.stats.at("available") = mem.stats.at("free") + mem.stats.at("cached"); + if (zfs_arc_cached) { + mem.stats.at("cached") += arc_size; + // The ARC will not shrink below arc_min_size, so that memory is not available + if (arc_size > arc_min_size) + mem.stats.at("available") += arc_size - arc_min_size; + } + mem.stats.at("used") = totalMem - (mem.stats.at("available") <= totalMem ? mem.stats.at("available") : mem.stats.at("free")); + + if (mem.stats.at("swap_total") > 0) mem.stats.at("swap_used") = mem.stats.at("swap_total") - mem.stats.at("swap_free"); + } + else + throw std::runtime_error("Failed to read /proc/meminfo"); + + meminfo.close(); + + //? Calculate percentages + for (const auto& name : mem_names) { + mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / totalMem)); + while (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front(); + } + + if (show_swap and mem.stats.at("swap_total") > 0) { + for (const auto& name : swap_names) { + mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at("swap_total"))); + while (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front(); + } + has_swap = true; + } + else + has_swap = false; + + //? Get disks stats + if (show_disks) { + static vector ignore_list; + double uptime = system_uptime(); + auto free_priv = Config::getB("disk_free_priv"); + try { + auto& disks_filter = Config::getS("disks_filter"); + bool filter_exclude = false; + auto use_fstab = Config::getB("use_fstab"); + auto only_physical = Config::getB("only_physical"); + auto zfs_hide_datasets = Config::getB("zfs_hide_datasets"); + auto& disks = mem.disks; + static std::unordered_map>> disks_stats_promises; + ifstream diskread; + + vector filter; + if (not disks_filter.empty()) { + filter = ssplit(disks_filter); + if (filter.at(0).starts_with("exclude=")) { + filter_exclude = true; + filter.at(0) = filter.at(0).substr(8); + } + } + + //? Get list of "real" filesystems from /proc/filesystems + vector fstypes; + if (only_physical and not use_fstab) { + fstypes = {"zfs", "wslfs", "drvfs"}; + diskread.open(Shared::procPath / "filesystems"); + if (diskread.good()) { + for (string fstype; diskread >> fstype;) { + if (not is_in(fstype, "nodev", "squashfs", "nullfs")) + fstypes.push_back(fstype); + diskread.ignore(SSmax, '\n'); + } + } + else + throw std::runtime_error("Failed to read /proc/filesystems"); + diskread.close(); + } + + //? Get disk list to use from fstab if enabled + if (use_fstab and fs::last_write_time("/etc/fstab") != fstab_time) { + fstab.clear(); + fstab_time = fs::last_write_time("/etc/fstab"); + diskread.open("/etc/fstab"); + if (diskread.good()) { + for (string instr; diskread >> instr;) { + if (not instr.starts_with('#')) { + diskread >> instr; + #ifdef SNAPPED + if (instr == "/") fstab.push_back("/mnt"); + else if (not is_in(instr, "none", "swap")) fstab.push_back(instr); + #else + if (not is_in(instr, "none", "swap")) fstab.push_back(instr); + #endif + } + diskread.ignore(SSmax, '\n'); + } + } + else + throw std::runtime_error("Failed to read /etc/fstab"); + diskread.close(); + } + + //? Get mounts from /etc/mtab or /proc/self/mounts + diskread.open((fs::exists("/etc/mtab") ? fs::path("/etc/mtab") : Shared::procPath / "self/mounts")); + if (diskread.good()) { + vector found; + found.reserve(last_found.size()); + string dev, mountpoint, fstype; + while (not diskread.eof()) { + std::error_code ec; + diskread >> dev >> mountpoint >> fstype; + diskread.ignore(SSmax, '\n'); + + // A mountpoint can ascii escape codes, which will not work with `statvfs`. + mountpoint = convert_ascii_escapes(mountpoint); + + if (v_contains(ignore_list, mountpoint) or v_contains(found, mountpoint)) continue; + + //? Match filter if not empty + if (not filter.empty()) { + bool match = v_contains(filter, mountpoint); + if ((filter_exclude and match) or (not filter_exclude and not match)) + continue; + } + + //? Skip ZFS datasets if zfs_hide_datasets option is enabled + size_t zfs_dataset_name_start = 0; + if (fstype == "zfs" && (zfs_dataset_name_start = dev.find('/')) != std::string::npos && zfs_hide_datasets) continue; + + if ((not use_fstab and not only_physical) + or (use_fstab and v_contains(fstab, mountpoint)) + or (not use_fstab and only_physical and v_contains(fstypes, fstype))) { + found.push_back(mountpoint); + if (not v_contains(last_found, mountpoint)) redraw = true; + + //? Save mountpoint, name, fstype, dev path and path to /sys/block stat file + if (not disks.contains(mountpoint)) { + disks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename(), fstype}; + if (disks.at(mountpoint).dev.empty()) disks.at(mountpoint).dev = dev; + #ifdef SNAPPED + if (mountpoint == "/mnt") disks.at(mountpoint).name = "root"; + #endif + if (disks.at(mountpoint).name.empty()) disks.at(mountpoint).name = (mountpoint == "/" ? "root" : mountpoint); + string devname = disks.at(mountpoint).dev.filename(); + int c = 0; + while (devname.size() >= 2) { + const auto stat = fmt::format("/sys/block/{}/stat", devname); + if (fs::exists(stat, ec) and access(stat.c_str(), R_OK) == 0) { + const auto mount_stat = fmt::format("/sys/block/{}/{}/stat", devname, disks.at(mountpoint).dev.filename()); + if (c > 0 and fs::exists(mount_stat, ec)) + disks.at(mountpoint).stat = std::move(mount_stat); + else + disks.at(mountpoint).stat = std::move(stat); + break; + //? Set ZFS stat filepath + } else if (fstype == "zfs") { + disks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets); + if (disks.at(mountpoint).stat.empty()) { + Logger::debug("Failed to get ZFS stat file for device {}", dev); + } + break; + } + devname.resize(devname.size() - 1); + c++; + } + } + + //? If zfs_hide_datasets option was switched, refresh stat filepath + if (fstype == "zfs" && ((zfs_hide_datasets && !is_directory(disks.at(mountpoint).stat)) + || (!zfs_hide_datasets && is_directory(disks.at(mountpoint).stat)))) { + disks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets); + if (disks.at(mountpoint).stat.empty()) { + Logger::debug("Failed to get ZFS stat file for device {}", dev); + } + } + } + } + + //? Remove disks no longer mounted or filtered out + if (swap_disk and has_swap) found.push_back("swap"); + for (auto it = disks.begin(); it != disks.end();) { + if (not v_contains(found, it->first)) + it = disks.erase(it); + else + it++; + } + if (found.size() != last_found.size()) redraw = true; + last_found = std::move(found); + } + else + throw std::runtime_error("Failed to get mounts from /etc/mtab and /proc/self/mounts"); + diskread.close(); + + //? Get disk/partition stats + for (auto it = disks.begin(); it != disks.end(); ) { + auto &[mountpoint, disk] = *it; + if (v_contains(ignore_list, mountpoint) or disk.name == "swap") { + it = disks.erase(it); + continue; + } + if(auto promises_it = disks_stats_promises.find(mountpoint); promises_it != disks_stats_promises.end()){ + auto& promise = promises_it->second; + if(promise.valid() && + promise.wait_for(0s) == std::future_status::timeout) { + ++it; + continue; + } + auto promise_res = promises_it->second.get(); + if(promise_res.second != -1){ + ignore_list.push_back(mountpoint); + Logger::warning("Failed to get disk/partition stats for mount \"{}\" with statvfs error code: {}. Ignoring...", mountpoint, promise_res.second); + it = disks.erase(it); + continue; + } + auto &updated_stats = promise_res.first; + disk.total = updated_stats.total; + disk.free = updated_stats.free; + disk.used = updated_stats.used; + disk.used_percent = updated_stats.used_percent; + disk.free_percent = updated_stats.free_percent; + } + disks_stats_promises[mountpoint] = async(std::launch::async, [mountpoint, free_priv]() -> pair { + struct statvfs vfs; + disk_info disk; + if (statvfs(mountpoint.c_str(), &vfs) < 0) { + return pair{disk, errno}; + } + disk.total = vfs.f_blocks * vfs.f_frsize; + disk.free = (free_priv ? vfs.f_bfree : vfs.f_bavail) * vfs.f_frsize; + disk.used = disk.total - disk.free; + if (disk.total != 0) { + disk.used_percent = round((double)disk.used * 100 / disk.total); + disk.free_percent = 100 - disk.used_percent; + } else { + disk.used_percent = 0; + disk.free_percent = 0; + } + return pair{disk, -1}; + }); + ++it; + } + + //? Setup disks order in UI and add swap if enabled + mem.disks_order.clear(); + #ifdef SNAPPED + if (disks.contains("/mnt")) mem.disks_order.push_back("/mnt"); + #else + if (disks.contains("/")) mem.disks_order.push_back("/"); + #endif + if (swap_disk and has_swap) { + mem.disks_order.push_back("swap"); + if (not disks.contains("swap")) disks["swap"] = {"", "swap", "swap"}; + disks.at("swap").total = mem.stats.at("swap_total"); + disks.at("swap").used = mem.stats.at("swap_used"); + disks.at("swap").free = mem.stats.at("swap_free"); + disks.at("swap").used_percent = mem.percent.at("swap_used").back(); + disks.at("swap").free_percent = mem.percent.at("swap_free").back(); + } + for (const auto& name : last_found) + #ifdef SNAPPED + if (not is_in(name, "/mnt", "swap")) mem.disks_order.push_back(name); + #else + if (not is_in(name, "/", "swap")) mem.disks_order.push_back(name); + #endif + + //? Get disks IO + int64_t sectors_read, sectors_write, io_ticks, io_ticks_temp; + disk_ios = 0; + for (auto& [ignored, disk] : disks) { + if (disk.stat.empty() or access(disk.stat.c_str(), R_OK) != 0) continue; + if (disk.fstype == "zfs" && zfs_hide_datasets && zfs_collect_pool_total_stats(disk)) { + disk_ios++; + continue; + } + diskread.open(disk.stat); + if (diskread.good()) { + disk_ios++; + //? ZFS Pool Support + if (disk.fstype == "zfs") { + // skip first three lines + for (int i = 0; i < 3; i++) diskread.ignore(numeric_limits::max(), '\n'); + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> io_ticks; + + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> sectors_write; // nbytes written + if (disk.io_write.empty()) + disk.io_write.push_back(0); + else + disk.io_write.push_back(max((int64_t)0, (sectors_write - disk.old_io.at(1)))); + disk.old_io.at(1) = sectors_write; + while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front(); + + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> io_ticks_temp; + io_ticks += io_ticks_temp; + + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> sectors_read; // nbytes read + if (disk.io_read.empty()) + disk.io_read.push_back(0); + else + disk.io_read.push_back(max((int64_t)0, (sectors_read - disk.old_io.at(0)))); + disk.old_io.at(0) = sectors_read; + while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front(); + + if (disk.io_activity.empty()) + disk.io_activity.push_back(0); + else + disk.io_activity.push_back(max((int64_t)0, (io_ticks - disk.old_io.at(2)))); + disk.old_io.at(2) = io_ticks; + while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front(); + } else { + for (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); } + diskread >> sectors_read; + if (disk.io_read.empty()) + disk.io_read.push_back(0); + else + disk.io_read.push_back(max((int64_t)0, (sectors_read - disk.old_io.at(0)) * 512)); + disk.old_io.at(0) = sectors_read; + while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front(); + + for (int i = 0; i < 3; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); } + diskread >> sectors_write; + if (disk.io_write.empty()) + disk.io_write.push_back(0); + else + disk.io_write.push_back(max((int64_t)0, (sectors_write - disk.old_io.at(1)) * 512)); + disk.old_io.at(1) = sectors_write; + while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front(); + + for (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); } + diskread >> io_ticks; + if (uptime == old_uptime || disk.io_activity.empty()) + disk.io_activity.push_back(0); + else + disk.io_activity.push_back(clamp((long)round((double)(io_ticks - disk.old_io.at(2)) / (uptime - old_uptime) / 10), 0l, 100l)); + disk.old_io.at(2) = io_ticks; + while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front(); + } + } else { + Logger::debug("Error in Mem::collect() : when opening {}", disk.stat); + } + diskread.close(); + } + old_uptime = uptime; + } + catch (const std::exception& e) { + Logger::warning("Error in Mem::collect() : {}", e.what()); + } + } + + return mem; + } + + fs::path get_zfs_stat_file(const string& device_name, size_t dataset_name_start, bool zfs_hide_datasets) { + fs::path zfs_pool_stat_path; + if (zfs_hide_datasets) { + zfs_pool_stat_path = Shared::procPath / "spl/kstat/zfs" / device_name; + if (access(zfs_pool_stat_path.c_str(), R_OK) == 0) { + return zfs_pool_stat_path; + } else { + Logger::debug("Can't access folder: {}", zfs_pool_stat_path); + return ""; + } + } + + ifstream filestream; + string filename; + string name_compare; + + if (dataset_name_start != std::string::npos) { // device is a dataset + zfs_pool_stat_path = Shared::procPath / "spl/kstat/zfs" / device_name.substr(0, dataset_name_start); + } else { // device is a pool + zfs_pool_stat_path = Shared::procPath / "spl/kstat/zfs" / device_name; + } + + // looking through all files that start with 'objset' to find the one containing `device_name` object stats + try { + for (const auto& file: fs::directory_iterator(zfs_pool_stat_path)) { + filename = file.path().filename(); + if (filename.starts_with("objset")) { + filestream.open(file.path()); + if (filestream.good()) { + // skip first two lines + for (int i = 0; i < 2; i++) filestream.ignore(numeric_limits::max(), '\n'); + // skip characters until '7' is reached, indicating data type 7, next value will be object name + filestream.ignore(numeric_limits::max(), '7'); + filestream >> name_compare; + if (name_compare == device_name) { + filestream.close(); + if (access(file.path().c_str(), R_OK) == 0) { + return file.path(); + } else { + Logger::debug("Can't access file: {}", file.path()); + return ""; + } + } + } + filestream.close(); + } + } + } + catch (fs::filesystem_error& e) {} + + Logger::debug("Could not read directory: {}", zfs_pool_stat_path); + return ""; + } + + bool zfs_collect_pool_total_stats(struct disk_info &disk) { + ifstream diskread; + + int64_t bytes_read; + int64_t bytes_write; + int64_t io_ticks; + int64_t bytes_read_total{}; + int64_t bytes_write_total{}; + int64_t io_ticks_total{}; + int64_t objects_read{}; + + // looking through all files that start with 'objset' + for (const auto& file: fs::directory_iterator(disk.stat)) { + if ((file.path().filename()).string().starts_with("objset")) { + diskread.open(file.path()); + if (diskread.good()) { + try { + // skip first three lines + for (int i = 0; i < 3; i++) diskread.ignore(numeric_limits::max(), '\n'); + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> io_ticks; + io_ticks_total += io_ticks; + + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> bytes_write; + bytes_write_total += bytes_write; + + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> io_ticks; + io_ticks_total += io_ticks; + + // skip characters until '4' is reached, indicating data type 4, next value will be out target + diskread.ignore(numeric_limits::max(), '4'); + diskread >> bytes_read; + bytes_read_total += bytes_read; + } catch (const std::exception& e) { + continue; + } + + // increment read objects counter if no errors were encountered + objects_read++; + } else { + Logger::debug("Could not read file: {}", file.path()); + } + diskread.close(); + } + } + + // if for some reason no objects were read + if (objects_read == 0) return false; + + if (disk.io_write.empty()) + disk.io_write.push_back(0); + else + disk.io_write.push_back(max((int64_t)0, (bytes_write_total - disk.old_io.at(1)))); + disk.old_io.at(1) = bytes_write_total; + while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front(); + + if (disk.io_read.empty()) + disk.io_read.push_back(0); + else + disk.io_read.push_back(max((int64_t)0, (bytes_read_total - disk.old_io.at(0)))); + disk.old_io.at(0) = bytes_read_total; + while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front(); + + if (disk.io_activity.empty()) + disk.io_activity.push_back(0); + else + disk.io_activity.push_back(max((int64_t)0, (io_ticks_total - disk.old_io.at(2)))); + disk.old_io.at(2) = io_ticks_total; + while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front(); + + return true; + } + +} + +namespace Net { + std::unordered_map current_net; + net_info empty_net = {}; + vector interfaces; + string selected_iface; + int errors{}; + std::unordered_map graph_max = { {"download", {}}, {"upload", {}} }; + std::unordered_map> max_count = { {"download", {}}, {"upload", {}} }; + bool rescale{true}; + uint64_t timestamp{}; + + auto collect(bool no_update) -> net_info& { + if (Runner::stopping) return empty_net; + auto& net = current_net; + auto& config_iface = Config::getS("net_iface"); + auto net_sync = Config::getB("net_sync"); + auto net_auto = Config::getB("net_auto"); + auto new_timestamp = time_ms(); + + if (not no_update and errors < 3) { + //? Get interface list using getifaddrs() wrapper + IfAddrsPtr if_addrs {}; + if (if_addrs.get_status() != 0) { + errors++; + Logger::error("Net::collect() -> getifaddrs() failed with id {}", if_addrs.get_status()); + redraw = true; + return empty_net; + } + int family = 0; + static_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance. + enum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert + char ip[IPBUFFER_MAXSIZE]; + interfaces.clear(); + string ipv4, ipv6; + + //? Iteration over all items in getifaddrs() list + for (auto* ifa = if_addrs.get(); ifa != nullptr; ifa = ifa->ifa_next) { + if (ifa->ifa_addr == nullptr) continue; + family = ifa->ifa_addr->sa_family; + const auto& iface = ifa->ifa_name; + + //? Update available interfaces vector and get status of interface + if (not v_contains(interfaces, iface)) { + interfaces.push_back(iface); + net[iface].connected = (ifa->ifa_flags & IFF_RUNNING); + + // An interface can have more than one IP of the same family associated with it, + // but we pick only the first one to show in the NET box. + // Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable! + net[iface].ipv4.clear(); + net[iface].ipv6.clear(); + } + + + //? Get IPv4 address + if (family == AF_INET) { + if (net[iface].ipv4.empty()) { + if (nullptr != inet_ntop(family, &(reinterpret_cast(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) { + net[iface].ipv4 = ip; + } else { + int errsv = errno; + Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}", iface, strerror(errsv)); + } + } + } + //? Get IPv6 address + else if (family == AF_INET6) { + if (net[iface].ipv6.empty()) { + if (nullptr != inet_ntop(family, &(reinterpret_cast(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) { + net[iface].ipv6 = ip; + } else { + int errsv = errno; + Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}", iface, strerror(errsv)); + } + } + } //else, ignoring family==AF_PACKET (see man 3 getifaddrs) which is the first one in the `for` loop. + } + + //? Get total received and transmitted bytes + device address if no ip was found + for (const auto& iface : interfaces) { + auto& netif = net.at(iface); + if (netif.ipv4.empty() and netif.ipv6.empty()) + netif.ipv4 = readfile("/sys/class/net/" + iface + "/address"); + + for (const string dir : {"download", "upload"}) { + const fs::path sys_file = "/sys/class/net/" + iface + "/statistics/" + (dir == "download" ? "rx_bytes" : "tx_bytes"); + auto& saved_stat = netif.stat.at(dir); + auto& bandwidth = netif.bandwidth.at(dir); + + uint64_t val{}; + try { val = stoull(readfile(sys_file, "0")); } + catch (const std::invalid_argument&) {} + catch (const std::out_of_range&) {} + + //? Update speed, total and top values + if (val < saved_stat.last) { + saved_stat.rollover += saved_stat.last; + saved_stat.last = 0; + } + if (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits::max())) { + saved_stat.rollover = 0; + saved_stat.last = 0; + } + saved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000)); + if (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed; + if (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0; + saved_stat.total = (val + saved_stat.rollover) - saved_stat.offset; + saved_stat.last = val; + + //? Add values to graph + bandwidth.push_back(saved_stat.speed); + while (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front(); + + //? Set counters for auto scaling + if (net_auto and selected_iface == iface) { + if (net_sync and saved_stat.speed < netif.stat.at(dir == "download" ? "upload" : "download").speed) continue; + if (saved_stat.speed > graph_max[dir]) { + ++max_count[dir][0]; + if (max_count[dir][1] > 0) --max_count[dir][1]; + } + else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) { + ++max_count[dir][1]; + if (max_count[dir][0] > 0) --max_count[dir][0]; + } + + } + } + } + + //? Clean up net map if needed + if (net.size() > interfaces.size()) { + for (auto it = net.begin(); it != net.end();) { + if (not v_contains(interfaces, it->first)) + it = net.erase(it); + else + it++; + } + } + + timestamp = new_timestamp; + } + + //? Return empty net_info struct if no interfaces was found + if (net.empty()) + return empty_net; + + //? Find an interface to display if selected isn't set or valid + if (selected_iface.empty() or not v_contains(interfaces, selected_iface)) { + max_count["download"][0] = max_count["download"][1] = max_count["upload"][0] = max_count["upload"][1] = 0; + redraw = true; + if (net_auto) rescale = true; + if (not config_iface.empty() and v_contains(interfaces, config_iface)) selected_iface = config_iface; + else { + //? Sort interfaces by total upload + download bytes + auto sorted_interfaces = interfaces; + rng::sort(sorted_interfaces, [&](const auto& a, const auto& b){ + return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total, + net.at(b).stat["download"].total + net.at(b).stat["upload"].total); + }); + selected_iface.clear(); + //? Try to set to a connected interface + for (const auto& iface : sorted_interfaces) { + if (net.at(iface).connected) { + selected_iface = iface; + break; + } + } + //? If no interface is connected set to first available + if (selected_iface.empty() and not sorted_interfaces.empty()) selected_iface = sorted_interfaces.at(0); + else if (sorted_interfaces.empty()) return empty_net; + + } + } + + //? Calculate max scale for graphs if needed + if (net_auto) { + bool sync = false; + for (const auto& dir: {"download", "upload"}) { + for (const auto& sel : {0, 1}) { + if (rescale or max_count[dir][sel] >= 5) { + const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5 + ? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5 + : net[selected_iface].stat[dir].speed); + graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10); + max_count[dir][0] = max_count[dir][1] = 0; + redraw = true; + if (net_sync) sync = true; + break; + } + } + //? Sync download/upload graphs if enabled + if (sync) { + const auto other = (string(dir) == "upload" ? "download" : "upload"); + graph_max[other] = graph_max[dir]; + max_count[other][0] = max_count[other][1] = 0; + break; + } + } + } + + rescale = false; + return net.at(selected_iface); + } +} + +namespace Proc { + + vector current_procs; + std::unordered_map uid_user; + string current_sort; + string current_filter; + bool current_rev{}; + bool is_tree_mode; + + fs::file_time_type passwd_time; + + uint64_t cputimes; + int collapse = -1, expand = -1, toggle_children = -1, collapse_all = -1; + uint64_t old_cputimes{}; + atomic numpids{}; + int filter_found{}; + + detail_container detailed; + constexpr size_t KTHREADD = 2; + static std::unordered_set kernels_procs = {KTHREADD}; + static std::unordered_set dead_procs; + + //* Get detailed info for selected process + static void _collect_details(const size_t pid, const uint64_t uptime, vector& procs) { + fs::path pid_path = Shared::procPath / std::to_string(pid); + + if (pid != detailed.last_pid) { + detailed = {}; + detailed.last_pid = pid; + detailed.skip_smaps = not Config::getB("proc_info_smaps"); + } + + //? Copy proc_info for process from proc vector + auto p_info = rng::find(procs, pid, &proc_info::pid); + detailed.entry = *p_info; + + //? Update cpu percent deque for process cpu graph + if (not Config::getB("proc_per_core")) detailed.entry.cpu_p *= Shared::coreCount; + detailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll)); + while (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front(); + + //? Process runtime + if (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(uptime - (detailed.entry.cpu_s / Shared::clkTck)); + else detailed.elapsed = sec_to_dhms(detailed.entry.death_time); + if (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3); + + //? Get parent process name + if (detailed.parent.empty()) { + auto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid); + if (p_entry != procs.end()) detailed.parent = p_entry->name; + } + + //? Expand process status from single char to explanative string + detailed.status = (proc_states.contains(detailed.entry.state)) ? proc_states.at(detailed.entry.state) : "Unknown"; + + ifstream d_read; + string short_str; + + //? Try to get RSS mem from proc/[pid]/smaps + detailed.memory.clear(); + if (not detailed.skip_smaps and fs::exists(pid_path / "smaps")) { + d_read.open(pid_path / "smaps"); + uint64_t rss = 0; + try { + while (d_read.good()) { + d_read.ignore(SSmax, 'R'); + if (d_read.peek() == 's') { + d_read.ignore(SSmax, ':'); + getline(d_read, short_str, 'k'); + rss += stoull(short_str); + } + } + if (rss == detailed.entry.mem >> 10) + detailed.skip_smaps = true; + else { + detailed.mem_bytes.push_back(rss << 10); + detailed.memory = floating_humanizer(rss, false, 1); + } + } + catch (const std::invalid_argument&) {} + catch (const std::out_of_range&) {} + d_read.close(); + } + if (detailed.memory.empty()) { + detailed.mem_bytes.push_back(detailed.entry.mem); + detailed.memory = floating_humanizer(detailed.entry.mem); + } + if (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) { + detailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem()); + redraw = true; + } + + while (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front(); + + //? Get bytes read and written from proc/[pid]/io + if (fs::exists(pid_path / "io")) { + d_read.open(pid_path / "io"); + try { + string name; + while (d_read.good()) { + getline(d_read, name, ':'); + if (name.ends_with("read_bytes")) { + getline(d_read, short_str); + detailed.io_read = floating_humanizer(stoull(short_str)); + } + else if (name.ends_with("write_bytes")) { + getline(d_read, short_str); + detailed.io_write = floating_humanizer(stoull(short_str)); + break; + } + else + d_read.ignore(SSmax, '\n'); + } + } + catch (const std::invalid_argument&) {} + catch (const std::out_of_range&) {} + d_read.close(); + } + } + + //* Collects and sorts process information from /proc + auto collect(bool no_update) -> vector& { + if (Runner::stopping) return current_procs; + const auto& sorting = Config::getS("proc_sorting"); + auto reverse = Config::getB("proc_reversed"); + const auto& filter = Config::getS("proc_filter"); + auto per_core = Config::getB("proc_per_core"); + auto should_filter_kernel = Config::getB("proc_filter_kernel"); + auto tree = Config::getB("proc_tree"); + auto show_detailed = Config::getB("show_detailed"); + const auto pause_proc_list = Config::getB("pause_proc_list"); + const size_t detailed_pid = Config::getI("detailed_pid"); + bool should_filter = current_filter != filter; + if (should_filter) current_filter = filter; + bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter); + bool tree_mode_change = tree != is_tree_mode; + if (sorted_change) { + current_sort = sorting; + current_rev = reverse; + } + if (tree_mode_change) is_tree_mode = tree; + ifstream pread; + string long_string; + string short_str; + + static vector found; + + const double uptime = system_uptime(); + + const int cmult = (per_core) ? Shared::coreCount : 1; + bool got_detailed = false; + + static size_t proc_clear_count{}; + + //* Use pids from last update if only changing filter, sorting or tree options + if (no_update and not current_procs.empty()) { + if (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, round(uptime), current_procs); + } + //* ---------------------------------------------Collection start---------------------------------------------- + else { + should_filter = true; + found.clear(); + + //? First make sure kernel proc cache is cleared. + if (should_filter_kernel and ++proc_clear_count >= 256) { + //? Clearing the cache is used in the event of a pid wrap around. + //? In that event processes that acquire old kernel pids would also be filtered out so we need to manually clean the cache every now and then. + kernels_procs.clear(); + kernels_procs.emplace(KTHREADD); + proc_clear_count = 0; + } + + auto totalMem = Mem::get_totalMem(); + int totalMem_len = to_string(totalMem >> 10).size(); + + //? Update uid_user map if /etc/passwd changed since last run + if (not Shared::passwd_path.empty() and fs::last_write_time(Shared::passwd_path) != passwd_time) { + string r_uid, r_user; + passwd_time = fs::last_write_time(Shared::passwd_path); + uid_user.clear(); + pread.open(Shared::passwd_path); + if (pread.good()) { + while (pread.good()) { + getline(pread, r_user, ':'); + pread.ignore(SSmax, ':'); + getline(pread, r_uid, ':'); + if (uid_user.contains(r_uid)) break; + uid_user[r_uid] = r_user; + pread.ignore(SSmax, '\n'); + } + } + else { + Shared::passwd_path.clear(); + } + pread.close(); + } + + //? Get cpu total times from /proc/stat up to the guest field + cputimes = 0; + pread.open(Shared::procPath / "stat"); + if (pread.good()) { + pread.ignore(SSmax, ' '); + int i = 0; + for (uint64_t times; i < 8 and pread >> times; cputimes += times, i++); + } + else throw std::runtime_error("Failure to read /proc/stat"); + pread.close(); + + //? Iterate over all pids in /proc + for (const auto& d: fs::directory_iterator(Shared::procPath)) { + if (Runner::stopping) + return current_procs; + + if (pread.is_open()) pread.close(); + + const string pid_str = d.path().filename(); + if (not isdigit(pid_str[0])) continue; + + const size_t pid = stoul(pid_str); + + if (should_filter_kernel and kernels_procs.contains(pid)) { + continue; + } + + found.push_back(pid); + + //? Check if pid already exists in current_procs + auto find_old = rng::find(current_procs, pid, &proc_info::pid); + bool no_cache{}; + //? Only add new processes if not paused + if (find_old == current_procs.end()) { + if (not pause_proc_list) { + current_procs.push_back({pid}); + find_old = current_procs.end() - 1; + no_cache = true; + } + else continue; + } + else if (dead_procs.contains(pid)) continue; + + auto& new_proc = *find_old; + + //? Get program name, command and username + if (no_cache) { + pread.open(d.path() / "comm"); + if (not pread.good()) continue; + getline(pread, new_proc.name); + pread.close(); + //? Check for whitespace characters in name and set offset to get correct fields from stat file + new_proc.name_offset = rng::count(new_proc.name, ' '); + + pread.open(d.path() / "cmdline"); + if (not pread.good()) continue; + long_string.clear(); + while(getline(pread, long_string, '\0')) { + new_proc.cmd += long_string + ' '; + if (new_proc.cmd.size() > 1000) { + new_proc.cmd.resize(1000); + break; + } + } + pread.close(); + if (not new_proc.cmd.empty()) new_proc.cmd.pop_back(); + + pread.open(d.path() / "status"); + if (not pread.good()) continue; + string uid; + string line; + while (pread.good()) { + getline(pread, line, ':'); + if (line == "Uid") { + pread.ignore(); + getline(pread, uid, '\t'); + break; + } else { + pread.ignore(SSmax, '\n'); + } + } + pread.close(); + if (uid_user.contains(uid)) { + new_proc.user = uid_user.at(uid); + } + else { + #if !(defined(STATIC_BUILD) && defined(__GLIBC__)) + try { + struct passwd* udet; + udet = getpwuid(stoi(uid)); + if (udet != nullptr and udet->pw_name != nullptr) { + new_proc.user = string(udet->pw_name); + } + else { + new_proc.user = uid; + } + } + catch (...) { new_proc.user = uid; } + #else + new_proc.user = uid; + #endif + } + } + + //? Parse /proc/[pid]/stat + pread.open(d.path() / "stat"); + if (not pread.good()) continue; + + const auto& offset = new_proc.name_offset; + short_str.clear(); + int x = 0, next_x = 3; + uint64_t cpu_t = 0; + try { + for (;;) { + while (pread.good() and ++x < next_x + offset) pread.ignore(SSmax, ' '); + if (not pread.good()) break; + else getline(pread, short_str, ' '); + + switch (x-offset) { + case 3: //? Process state + new_proc.state = short_str.at(0); + if (new_proc.ppid != 0) next_x = 14; + continue; + case 4: //? Parent pid + new_proc.ppid = stoull(short_str); + next_x = 14; + continue; + case 14: //? Process utime + cpu_t = stoull(short_str); + continue; + case 15: //? Process stime + cpu_t += stoull(short_str); + next_x = 19; + continue; + case 19: //? Nice value + new_proc.p_nice = stoll(short_str); + continue; + case 20: //? Number of threads + new_proc.threads = stoull(short_str); + if (new_proc.cpu_s == 0) { + next_x = 22; + new_proc.cpu_t = cpu_t; + } + else + next_x = 24; + continue; + case 22: //? Get cpu seconds if missing + new_proc.cpu_s = stoull(short_str); + next_x = 24; + continue; + case 24: //? RSS memory (can be inaccurate, but parsing smaps increases total cpu usage by ~20x) + if (cmp_greater(short_str.size(), totalMem_len)) + new_proc.mem = totalMem; + else + new_proc.mem = stoull(short_str) * Shared::pageSize; + } + break; + } + + } + catch (const std::invalid_argument&) { continue; } + catch (const std::out_of_range&) { continue; } + + pread.close(); + + if (should_filter_kernel and new_proc.ppid == KTHREADD) { + kernels_procs.emplace(new_proc.pid); + found.pop_back(); + } + + if (x-offset < 24) continue; + + //? Get RSS memory from /proc/[pid]/statm if value from /proc/[pid]/stat looks wrong + if (new_proc.mem >= totalMem) { + pread.open(d.path() / "statm"); + if (not pread.good()) continue; + pread.ignore(SSmax, ' '); + pread >> new_proc.mem; + new_proc.mem *= Shared::pageSize; + pread.close(); + } + + //? Process cpu usage since last update + new_proc.cpu_p = clamp(round(cmult * 1000 * (cpu_t - new_proc.cpu_t) / max((uint64_t)1, cputimes - old_cputimes)) / 10.0, 0.0, 100.0 * Shared::coreCount); + + //? Process cumulative cpu usage since process start + new_proc.cpu_c = (double)cpu_t / max(1.0, (uptime * Shared::clkTck) - new_proc.cpu_s); + + //? Update cached value with latest cpu times + new_proc.cpu_t = cpu_t; + + if (show_detailed and not got_detailed and new_proc.pid == detailed_pid) { + got_detailed = true; + } + } + + //? Clear dead processes from current_procs and remove kernel processes if enabled and not paused + if (not pause_proc_list) { + auto eraser = rng::remove_if(current_procs, [&](const auto& element){ return not v_contains(found, element.pid); }); + current_procs.erase(eraser.begin(), eraser.end()); + if (!dead_procs.empty()) dead_procs.clear(); + } + //? Set correct state of dead processes if paused + else { + const bool keep_dead_proc_usage = Config::getB("keep_dead_proc_usage"); + for (auto& r : current_procs) { + if (rng::find(found, r.pid) == found.end()) { + if (r.state != 'X') r.death_time = round(uptime) - (r.cpu_s / Shared::clkTck); + r.state = 'X'; + dead_procs.emplace(r.pid); + //? Reset cpu usage for dead processes if paused and option is set + if (!keep_dead_proc_usage) { + r.cpu_p = 0.0; + r.mem = 0; + } + } + } + } + + //? Update the details info box for process if active + if (show_detailed and got_detailed) { + _collect_details(detailed_pid, round(uptime), current_procs); + } + else if (show_detailed and not got_detailed and detailed.status != "Dead") { + detailed.status = "Dead"; + redraw = true; + } + + old_cputimes = cputimes; + } + //* ---------------------------------------------Collection done----------------------------------------------- + + //* Match filter if defined + if (should_filter) { + filter_found = 0; + for (auto& p : current_procs) { + if (not tree and not filter.empty()) { + if (!matches_filter(p, filter)) { + p.filtered = true; + filter_found++; + } else { + p.filtered = false; + } + } else { + p.filtered = false; + } + } + } + + //* Sort processes + if ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) { + proc_sorter(current_procs, sorting, reverse, tree); + } + + //* Generate tree view if enabled + if (tree and (not no_update or should_filter or sorted_change)) { + bool locate_selection = false; + + if (toggle_children != -1) { + auto collapser = rng::find(current_procs, toggle_children, &proc_info::pid); + if (collapser != current_procs.end()){ + for (auto& p : current_procs) { + if (p.ppid == collapser->pid) { + auto child = rng::find(current_procs, p.pid, &proc_info::pid); + if (child != current_procs.end()){ + child->collapsed = not child->collapsed; + } + } + } + if (Config::ints.at("proc_selected") > 0) locate_selection = true; + } + toggle_children = -1; + } + + if (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) { + auto collapser = rng::find(current_procs, find_pid, &proc_info::pid); + if (collapser != current_procs.end()) { + if (collapse == expand) { + collapser->collapsed = not collapser->collapsed; + } + else if (collapse > -1) { + collapser->collapsed = true; + } + else if (expand > -1) { + collapser->collapsed = false; + } + if (Config::ints.at("proc_selected") > 0) locate_selection = true; + } + collapse = expand = -1; + } + + if (collapse_all != -1) { + toggle_tree_collapse(current_procs); + collapse_all = -1; + if (Config::ints.at("proc_selected") > 0) locate_selection = true; + } + + if (should_filter or not filter.empty()) filter_found = 0; + + vector tree_procs; + tree_procs.reserve(current_procs.size()); + + if (!pause_proc_list) { + for (auto& p : current_procs) { + if (not v_contains(found, p.ppid)) p.ppid = 0; + } + } + + //? Stable sort to retain selected sorting among processes with the same parent + rng::stable_sort(current_procs, rng::less{}, & proc_info::ppid); + + //? Auto-collapse processes with many children when entering tree mode + _auto_collapse_oversized(current_procs, tree_mode_change); + + //? Start recursive iteration over processes with the lowest shared parent pids + for (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) { + _tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter); + } + + //? Recursive sort over tree structure to account for collapsed processes in the tree + int index = 0; + tree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size()); + + //? Recursive construction of ASCII tree prefixes. + for (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) { + _collect_prefixes(*t, t == tree_procs.end() - 1); + } + + //? Final sort based on tree index + rng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index); + + //? Move current selection/view to the selected process when collapsing/expanding in the tree + if (locate_selection) { + int loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index; + if (Config::ints.at("proc_start") >= loc or Config::ints.at("proc_start") <= loc - Proc::select_max) + Config::ints.at("proc_start") = max(0, loc - 1); + Config::ints.at("proc_selected") = loc - Config::ints.at("proc_start") + 1; + } + } + + numpids = (int)current_procs.size() - filter_found; + + return current_procs; + } +} + +namespace Tools { + double system_uptime() { + string upstr; + ifstream pread(Shared::procPath / "uptime"); + if (pread.good()) { + try { + getline(pread, upstr, ' '); + pread.close(); + return stod(upstr); + } + catch (const std::invalid_argument&) {} + catch (const std::out_of_range&) {} + } + throw std::runtime_error(fmt::format("Failed to get uptime from {}", Shared::procPath / "uptime")); + } +} diff --git a/vendor/btop/src/osx/btop_collect.cpp b/vendor/btop/src/osx/btop_collect.cpp new file mode 100644 index 000000000..d89406962 --- /dev/null +++ b/vendor/btop/src/osx/btop_collect.cpp @@ -0,0 +1,2067 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#ifdef __APPLE__ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// BUGS +// If both and are being included, must be +// included before . +// from: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getifaddrs.3.html +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // for inet_ntop +#include +#include +#include + +#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504 +#include "sensors.hpp" +#endif +#include "smc.hpp" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "../btop_config.hpp" +#include "../btop_log.hpp" +#include "../btop_shared.hpp" +#include "../btop_tools.hpp" + +#if defined(GPU_SUPPORT) && defined(__APPLE__) && defined(__arm64__) +#include +#include + +//? IOReport C function declarations for Apple Silicon GPU metrics +extern "C" { + typedef struct IOReportSubscription* IOReportSubscriptionRef; + + CFDictionaryRef IOReportCopyChannelsInGroup(CFStringRef group, CFStringRef subgroup, + uint64_t a, uint64_t b, uint64_t c); + void IOReportMergeChannels(CFDictionaryRef a, CFDictionaryRef b, CFTypeRef cfnull); + IOReportSubscriptionRef IOReportCreateSubscription(void* a, CFMutableDictionaryRef b, + CFMutableDictionaryRef* c, uint64_t d, CFTypeRef cfnull); + CFDictionaryRef IOReportCreateSamples(IOReportSubscriptionRef sub, + CFMutableDictionaryRef chan, CFTypeRef cfnull); + CFDictionaryRef IOReportCreateSamplesDelta(CFDictionaryRef a, CFDictionaryRef b, CFTypeRef cfnull); + CFStringRef IOReportChannelGetGroup(CFDictionaryRef item); + CFStringRef IOReportChannelGetSubGroup(CFDictionaryRef item); + CFStringRef IOReportChannelGetChannelName(CFDictionaryRef item); + int64_t IOReportSimpleGetIntegerValue(CFDictionaryRef item, int32_t idx); + CFStringRef IOReportChannelGetUnitLabel(CFDictionaryRef item); + int32_t IOReportStateGetCount(CFDictionaryRef item); + CFStringRef IOReportStateGetNameForIndex(CFDictionaryRef item, int32_t idx); + int64_t IOReportStateGetResidency(CFDictionaryRef item, int32_t idx); + + //? IOHIDEvent declarations for GPU temperature + typedef struct __IOHIDEvent* IOHIDEventRef; + typedef struct __IOHIDServiceClient* IOHIDServiceClientRef; + typedef struct __IOHIDEventSystemClient* IOHIDEventSystemClientRef; + #ifdef __LP64__ + typedef double IOHIDFloat; + #else + typedef float IOHIDFloat; + #endif + IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator); + int IOHIDEventSystemClientSetMatching(IOHIDEventSystemClientRef client, CFDictionaryRef match); + CFArrayRef IOHIDEventSystemClientCopyServices(IOHIDEventSystemClientRef client); + IOHIDEventRef IOHIDServiceClientCopyEvent(IOHIDServiceClientRef sc, int64_t type, int32_t a, int64_t b); + CFStringRef IOHIDServiceClientCopyProperty(IOHIDServiceClientRef service, CFStringRef property); + IOHIDFloat IOHIDEventGetFloatValue(IOHIDEventRef event, int32_t field); +} +#endif // GPU_SUPPORT + +#if __MAC_OS_X_VERSION_MIN_REQUIRED < 120000 +#define kIOMainPortDefault kIOMasterPortDefault +#endif + +using std::clamp, std::string_literals::operator""s, std::cmp_equal, std::cmp_less, std::cmp_greater; +using std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min; +namespace fs = std::filesystem; +namespace rng = std::ranges; +using namespace Tools; + +//? RAII wrapper for CoreFoundation types — releases via CFRelease() on destruction +template +struct CFRef { + T ref; + CFRef() : ref(nullptr) {} + CFRef(T ref) : ref(ref) {} + ~CFRef() { if (ref) CFRelease((CFTypeRef)ref); } + CFRef(const CFRef&) = delete; + CFRef& operator=(const CFRef&) = delete; + CFRef(CFRef&& other) noexcept : ref(other.ref) { other.ref = nullptr; } + CFRef& operator=(CFRef&& other) noexcept { + if (this != &other) { reset(); ref = other.ref; other.ref = nullptr; } + return *this; + } + operator T() const { return ref; } + T get() const { return ref; } + T* ptr() { return &ref; } + void reset(T new_ref = nullptr) { + if (ref) CFRelease((CFTypeRef)ref); + ref = new_ref; + } + T release() { T r = ref; ref = nullptr; return r; } +}; + +//? RAII wrapper for IOKit object types — releases via IOObjectRelease() on destruction +struct IORef { + io_object_t ref; + IORef() : ref(0) {} + IORef(io_object_t ref) : ref(ref) {} + ~IORef() { if (ref) IOObjectRelease(ref); } + IORef(const IORef&) = delete; + IORef& operator=(const IORef&) = delete; + operator io_object_t() const { return ref; } + io_object_t get() const { return ref; } + io_object_t* ptr() { return &ref; } +}; + +//? --------------------------------------------------- FUNCTIONS ----------------------------------------------------- + +namespace Cpu { + vector core_old_totals; + vector core_old_idles; + vector available_fields = {"Auto", "total"}; + vector available_sensors = {"Auto"}; + cpu_info current_cpu; + bool got_sensors = false, cpu_temp_only = false, supports_watts = false; + int core_offset = 0; + + //* Populate found_sensors map + bool get_sensors(); + + //* Get current cpu clock speed + string get_cpuHz(); + + //* Search /proc/cpuinfo for a cpu name + string get_cpuName(); + + struct Sensor { + fs::path path; + string label; + int64_t temp = 0; + int64_t high = 0; + int64_t crit = 0; + }; + + string cpu_sensor; + vector core_sensors; + std::unordered_map core_mapping; +} // namespace Cpu + +namespace Mem { + double old_uptime; +} + +#if defined(GPU_SUPPORT) +namespace Gpu { + vector gpus; + + //? Stub shutdown for backends not available on macOS + namespace Nvml { bool shutdown() { return false; } } + namespace Rsmi { bool shutdown() { return false; } } + namespace Asysfs { bool shutdown() { return false; } } + + //? Apple Silicon GPU data collection via IOReport + namespace AppleSilicon { + bool initialized = false; + unsigned int device_count = 0; + + //? Forward declaration + template + bool collect(gpu_info* gpus_slice); + + //? IOReport subscription state + IOReportSubscriptionRef ior_sub = nullptr; + CFMutableDictionaryRef ior_chan = nullptr; + CFDictionaryRef prev_sample = nullptr; + uint64_t prev_sample_time = 0; + + //? GPU frequency table from DVFS + vector gpu_freqs; + + static string cfstring_to_string(CFStringRef cfstr) { + if (not cfstr) return ""; + char buf[256]; + if (CFStringGetCString(cfstr, buf, sizeof(buf), kCFStringEncodingUTF8)) + return string(buf); + return ""; + } + + static string get_chip_name() { + char buf[256]; + size_t size = sizeof(buf); + if (sysctlbyname("machdep.cpu.brand_string", buf, &size, nullptr, 0) == 0) + return string(buf); + return "Apple Silicon GPU"; + } + + static uint64_t get_mach_time_ms() { + static mach_timebase_info_data_t timebase = {0, 0}; + if (timebase.denom == 0) mach_timebase_info(&timebase); + return (mach_absolute_time() * timebase.numer / timebase.denom) / 1000000; + } + + //? Read GPU DVFS frequency table from IORegistry pmgr node + static void get_gpu_freqs_from_pmgr() { + io_iterator_t iter_raw; + //? matchDict ownership is consumed by IOServiceGetMatchingServices + CFMutableDictionaryRef matchDict = IOServiceMatching("AppleARMIODevice"); + if (IOServiceGetMatchingServices(kIOMainPortDefault, matchDict, &iter_raw) != kIOReturnSuccess) + return; + IORef iter(iter_raw); + + io_object_t entry_raw; + while ((entry_raw = IOIteratorNext(iter)) != 0) { + IORef entry(entry_raw); + char name[128]; + if (IORegistryEntryGetName(entry, name) == kIOReturnSuccess and string(name) == "pmgr") { + CFMutableDictionaryRef props_raw = nullptr; + if (IORegistryEntryCreateCFProperties(entry, &props_raw, kCFAllocatorDefault, 0) == kIOReturnSuccess and props_raw) { + CFRef props(props_raw); + CFDataRef dvfs_data = (CFDataRef)CFDictionaryGetValue(props, CFSTR("voltage-states9")); + if (dvfs_data) { + auto len = CFDataGetLength(dvfs_data); + auto ptr = CFDataGetBytePtr(dvfs_data); + //? Pairs of (freq, voltage), 4 bytes each + for (CFIndex i = 0; i + 7 < len; i += 8) { + uint32_t freq = 0; + memcpy(&freq, ptr + i, 4); + if (freq > 0) gpu_freqs.push_back(freq / (1000 * 1000)); // Hz -> MHz + } + } + } + } + } + } + + bool init() { + if (initialized) return false; + + //? Get GPU frequency table + get_gpu_freqs_from_pmgr(); + + //? Set up IOReport channels for GPU Stats and Energy Model + CFRef gpu_stats_group(CFStringCreateWithCString(kCFAllocatorDefault, "GPU Stats", kCFStringEncodingUTF8)); + CFRef gpu_perf_subgroup(CFStringCreateWithCString(kCFAllocatorDefault, "GPU Performance States", kCFStringEncodingUTF8)); + CFRef energy_group(CFStringCreateWithCString(kCFAllocatorDefault, "Energy Model", kCFStringEncodingUTF8)); + + CFRef gpu_chan(IOReportCopyChannelsInGroup(gpu_stats_group, gpu_perf_subgroup, 0, 0, 0)); + CFRef energy_chan(IOReportCopyChannelsInGroup(energy_group, nullptr, 0, 0, 0)); + + if (not gpu_chan.get() and not energy_chan.get()) { + Logger::info("Apple Silicon GPU: No IOReport channels found, GPU monitoring unavailable"); + return false; + } + + //? Merge channels into a single subscription + if (gpu_chan.get() and energy_chan.get()) { + IOReportMergeChannels(gpu_chan, energy_chan, nullptr); + } + CFDictionaryRef base_chan = gpu_chan.get() ? gpu_chan.get() : energy_chan.get(); + + auto size = CFDictionaryGetCount(base_chan); + ior_chan = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, size, base_chan); + + //? Create IOReport subscription + CFMutableDictionaryRef sub_dict = nullptr; + ior_sub = IOReportCreateSubscription(nullptr, ior_chan, &sub_dict, 0, nullptr); + if (not ior_sub) { + Logger::warning("Apple Silicon GPU: Failed to create IOReport subscription"); + CFRelease(ior_chan); + ior_chan = nullptr; + return false; + } + + device_count = 1; //? Apple Silicon has one integrated GPU + gpus.resize(gpus.size() + device_count); + gpu_names.resize(gpu_names.size() + device_count); + + initialized = true; + + //? Take initial sample for delta computation + prev_sample = IOReportCreateSamples(ior_sub, ior_chan, nullptr); + prev_sample_time = get_mach_time_ms(); + + //? Run init collect to populate names and supported functions + collect<1>(gpus.data()); + + return true; + } + + bool shutdown() { + if (not initialized) return false; + if (prev_sample) { CFRelease(prev_sample); prev_sample = nullptr; } + if (ior_chan) { CFRelease(ior_chan); ior_chan = nullptr; } + if (ior_sub) { CFRelease((CFTypeRef)ior_sub); ior_sub = nullptr; } + initialized = false; + return true; + } + + //? Read GPU temperature via IOHIDEventSystem thermal sensors + static long long get_gpu_temp_iohid() { + #if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504 + constexpr int kHIDPage_AppleVendor = 0xff00; + constexpr int kHIDUsage_TemperatureSensor = 5; + constexpr int64_t kIOHIDEventTypeTemperature = 15; + + CFStringRef keys[2] = { CFSTR("PrimaryUsagePage"), CFSTR("PrimaryUsage") }; + int page = kHIDPage_AppleVendor, usage = kHIDUsage_TemperatureSensor; + CFRef num0(CFNumberCreate(nullptr, kCFNumberSInt32Type, &page)); + CFRef num1(CFNumberCreate(nullptr, kCFNumberSInt32Type, &usage)); + const void* values[] = { num0.get(), num1.get() }; + CFRef match(CFDictionaryCreate(nullptr, + (const void**)keys, values, 2, + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); + + CFRef system(IOHIDEventSystemClientCreate(kCFAllocatorDefault)); + if (not system.get()) return -1; + IOHIDEventSystemClientSetMatching(system, match); + CFRef services(IOHIDEventSystemClientCopyServices(system)); + + if (not services.get()) return -1; + + double gpu_temp_sum = 0; + int gpu_temp_count = 0; + long count = CFArrayGetCount(services); + for (long i = 0; i < count; i++) { + auto sc = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(services, i); + if (not sc) continue; + CFRef name(IOHIDServiceClientCopyProperty(sc, CFSTR("Product"))); + if (not name.get()) continue; + char buf[200]; + CFStringGetCString(name, buf, 200, kCFStringEncodingASCII); + string n(buf); + //? Legacy Apple Silicon uses "GPU MTR Temp Sensor*" names. + //? On newer Apple Silicon we can see PMU TP*g sensors for GPU temperatures. + bool is_gpu_sensor = n.find("GPU") != string::npos; + if (not is_gpu_sensor and n.rfind("PMU TP", 0) == 0 and not n.empty() and n.back() == 'g') { + is_gpu_sensor = true; + } + if (is_gpu_sensor) { + CFRef event(IOHIDServiceClientCopyEvent(sc, kIOHIDEventTypeTemperature, 0, 0)); + if (event.get()) { + double temp = IOHIDEventGetFloatValue(event, kIOHIDEventTypeTemperature << 16); + if (temp > 0 and temp < 150) { + gpu_temp_sum += temp; + gpu_temp_count++; + } + } + } + } + + if (gpu_temp_count > 0) + return static_cast(round(gpu_temp_sum / gpu_temp_count)); + #endif + return -1; + } + + template + bool collect(gpu_info* gpus_slice) { + if (not initialized) return false; + + if constexpr (is_init) { + //? Device name + string chip = get_chip_name(); + gpu_names[0] = chip + " GPU"; + + //? Power max (typical Apple Silicon GPU TDP ~15-20W) + gpus_slice[0].pwr_max_usage = 20000; // 20W in mW + gpu_pwr_total_max += gpus_slice[0].pwr_max_usage; + + //? Temperature max + gpus_slice[0].temp_max = 110; + + //? Memory total (unified memory architecture — GPU shares system RAM) + int64_t memsize = 0; + size_t size = sizeof(memsize); + if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) == 0) + gpus_slice[0].mem_total = memsize; + + //? Supported functions + gpus_slice[0].supported_functions = { + .gpu_utilization = true, + .mem_utilization = true, + .gpu_clock = not gpu_freqs.empty(), + .mem_clock = false, + .pwr_usage = true, + .pwr_state = false, + .temp_info = true, + .mem_total = true, + .mem_used = true, + .pcie_txrx = false, + .encoder_utilization = false, + .decoder_utilization = false + }; + } + + //? Take new IOReport sample and compute delta + CFDictionaryRef cur_sample = IOReportCreateSamples(ior_sub, ior_chan, nullptr); + if (not cur_sample) return false; + + uint64_t cur_time = get_mach_time_ms(); + uint64_t dt = cur_time - prev_sample_time; + if (dt == 0) dt = 1; + + CFRef delta; + if (prev_sample) { + delta.reset(IOReportCreateSamplesDelta(prev_sample, cur_sample, nullptr)); + CFRelease(prev_sample); + } + prev_sample = cur_sample; + prev_sample_time = cur_time; + + if (not delta.get()) return false; + + //? Parse delta samples + CFArrayRef channels = (CFArrayRef)CFDictionaryGetValue(delta, CFSTR("IOReportChannels")); + if (not channels) return false; + + long long gpu_utilization = 0; + bool got_gpu_util = false; + double gpu_power_watts = 0; + bool got_gpu_power = false; + + long chan_count = CFArrayGetCount(channels); + for (long i = 0; i < chan_count; i++) { + CFDictionaryRef item = (CFDictionaryRef)CFArrayGetValueAtIndex(channels, i); + if (not item) continue; + + string group = cfstring_to_string(IOReportChannelGetGroup(item)); + string subgroup = cfstring_to_string(IOReportChannelGetSubGroup(item)); + string channel = cfstring_to_string(IOReportChannelGetChannelName(item)); + + //? GPU utilization from residency states + if (group == "GPU Stats" and subgroup == "GPU Performance States" and channel == "GPUPH") { + int32_t state_count = IOReportStateGetCount(item); + if (state_count <= 0) continue; + + int64_t total_residency = 0; + int64_t active_residency = 0; + double weighted_freq = 0; + + //? Find offset past IDLE/OFF/DOWN states + int offset = 0; + for (int32_t s = 0; s < state_count; s++) { + string name = cfstring_to_string(IOReportStateGetNameForIndex(item, s)); + if (name == "IDLE" or name == "OFF" or name == "DOWN") + offset = s + 1; + total_residency += IOReportStateGetResidency(item, s); + } + + int freq_count = static_cast(gpu_freqs.size()); + for (int32_t s = offset; s < state_count; s++) { + int64_t res = IOReportStateGetResidency(item, s); + active_residency += res; + int freq_idx = s - offset; + if (freq_idx < freq_count and active_residency > 0) + weighted_freq += static_cast(res) * gpu_freqs[freq_idx]; + } + + if (total_residency > 0) { + double usage_ratio = static_cast(active_residency) / static_cast(total_residency); + gpu_utilization = clamp(static_cast(round(usage_ratio * 100.0)), 0ll, 100ll); + got_gpu_util = true; + + //? Calculate average frequency + if (active_residency > 0 and not gpu_freqs.empty()) { + double avg_freq = weighted_freq / static_cast(active_residency); + gpus_slice[0].gpu_clock_speed = static_cast(round(avg_freq)); + } + } + } + + //? GPU power from Energy Model + if (group == "Energy Model" and channel == "GPU Energy") { + string unit = cfstring_to_string(IOReportChannelGetUnitLabel(item)); + int64_t val = IOReportSimpleGetIntegerValue(item, 0); + double energy = static_cast(val); + double divisor = static_cast(dt) / 1000.0; // dt is in ms + + if (unit.find("nJ") != string::npos) energy /= 1e9; + else if (unit.find("uJ") != string::npos or unit.find("\xc2\xb5J") != string::npos) energy /= 1e6; + else if (unit.find("mJ") != string::npos) energy /= 1e3; + //? energy is now in Joules + + if (divisor > 0) { + gpu_power_watts = energy / divisor; + got_gpu_power = true; + } + } + } + + //? Store GPU utilization + if (got_gpu_util) { + gpus_slice[0].gpu_percent.at("gpu-totals").push_back(gpu_utilization); + gpus_slice[0].mem_utilization_percent.push_back(gpu_utilization); + } + + //? Store power usage (convert W to mW) + if (got_gpu_power) { + gpus_slice[0].pwr_usage = static_cast(round(gpu_power_watts * 1000.0)); + if (gpus_slice[0].pwr_usage > gpus_slice[0].pwr_max_usage) + gpus_slice[0].pwr_max_usage = gpus_slice[0].pwr_usage; + gpus_slice[0].gpu_percent.at("gpu-pwr-totals").push_back( + clamp(static_cast(round(static_cast(gpus_slice[0].pwr_usage) * 100.0 / static_cast(gpus_slice[0].pwr_max_usage))), 0ll, 100ll)); + } + + //? GPU temperature + if (gpus_slice[0].supported_functions.temp_info and Config::getB("check_temp")) { + long long temp = get_gpu_temp_iohid(); + if (temp > 0) + gpus_slice[0].temp.push_back(temp); + } + + //? Memory usage (unified memory — report system memory usage) + if (gpus_slice[0].supported_functions.mem_total) { + vm_size_t page_size; + mach_port_t mach_port = mach_host_self(); + vm_statistics64_data_t vm_stats; + mach_msg_type_number_t count = sizeof(vm_stats) / sizeof(natural_t); + host_page_size(mach_port, &page_size); + + if (host_statistics64(mach_port, HOST_VM_INFO64, (host_info64_t)&vm_stats, &count) == KERN_SUCCESS) { + long long used = (static_cast(vm_stats.active_count) + + static_cast(vm_stats.inactive_count) + + static_cast(vm_stats.wire_count) + + static_cast(vm_stats.speculative_count) + + static_cast(vm_stats.compressor_page_count) + - static_cast(vm_stats.purgeable_count) + - static_cast(vm_stats.external_page_count)) * static_cast(page_size); + if (used < 0) used = 0; + gpus_slice[0].mem_used = used; + if (gpus_slice[0].mem_total > 0) { + auto used_pct = static_cast(round(static_cast(used) * 100.0 / static_cast(gpus_slice[0].mem_total))); + gpus_slice[0].gpu_percent.at("gpu-vram-totals").push_back(clamp(used_pct, 0ll, 100ll)); + } + } + } + + return true; + } + + //? Explicit template instantiations + template bool collect(gpu_info*); + template bool collect(gpu_info*); + } // namespace AppleSilicon + + //? Collect data from Apple Silicon GPU + auto collect(bool no_update) -> vector& { + if (Runner::stopping or (no_update and not gpus.empty())) return gpus; + + AppleSilicon::collect<0>(gpus.data()); + + //* Calculate averages + long long avg = 0; + long long mem_usage_total = 0; + long long mem_total = 0; + long long pwr_total = 0; + for (auto& gpu : gpus) { + if (gpu.supported_functions.gpu_utilization and not gpu.gpu_percent.at("gpu-totals").empty()) + avg += gpu.gpu_percent.at("gpu-totals").back(); + if (gpu.supported_functions.mem_used) + mem_usage_total += gpu.mem_used; + if (gpu.supported_functions.mem_total) + mem_total += gpu.mem_total; + if (gpu.supported_functions.pwr_usage) + pwr_total += gpu.pwr_usage; + + //* Trim vectors if there are more values than needed for graphs + if (width != 0) { + while (cmp_greater(gpu.gpu_percent.at("gpu-totals").size(), width * 2)) gpu.gpu_percent.at("gpu-totals").pop_front(); + while (cmp_greater(gpu.mem_utilization_percent.size(), width)) gpu.mem_utilization_percent.pop_front(); + while (cmp_greater(gpu.gpu_percent.at("gpu-pwr-totals").size(), width)) gpu.gpu_percent.at("gpu-pwr-totals").pop_front(); + while (cmp_greater(gpu.temp.size(), 18)) gpu.temp.pop_front(); + while (cmp_greater(gpu.gpu_percent.at("gpu-vram-totals").size(), width/2)) gpu.gpu_percent.at("gpu-vram-totals").pop_front(); + } + } + + if (not gpus.empty()) { + shared_gpu_percent.at("gpu-average").push_back(avg / static_cast(gpus.size())); + if (mem_total != 0) + shared_gpu_percent.at("gpu-vram-total").push_back(mem_usage_total * 100 / mem_total); + if (gpu_pwr_total_max != 0) + shared_gpu_percent.at("gpu-pwr-total").push_back(pwr_total * 100 / gpu_pwr_total_max); + } + + if (width != 0) { + while (cmp_greater(shared_gpu_percent.at("gpu-average").size(), width * 2)) shared_gpu_percent.at("gpu-average").pop_front(); + while (cmp_greater(shared_gpu_percent.at("gpu-vram-total").size(), width)) shared_gpu_percent.at("gpu-vram-total").pop_front(); + while (cmp_greater(shared_gpu_percent.at("gpu-pwr-total").size(), width)) shared_gpu_percent.at("gpu-pwr-total").pop_front(); + } + + return gpus; + } +} // namespace Gpu +#endif // GPU_SUPPORT + + class MachProcessorInfo { + public: + processor_info_array_t info_array; + mach_msg_type_number_t info_count; + MachProcessorInfo() {} + virtual ~MachProcessorInfo() {vm_deallocate(mach_task_self(), (vm_address_t)info_array, (vm_size_t)sizeof(processor_info_array_t) * info_count);} + }; + +namespace Shared { + + fs::path passwd_path; + uint64_t totalMem; + long pageSize, coreCount, clkTck, physicalCoreCount, arg_max; + double machTck; + int totalMem_len; + + void init() { + //? Shared global variables init + + coreCount = sysconf(_SC_NPROCESSORS_ONLN); // this returns all logical cores (threads) + if (coreCount < 1) { + coreCount = 1; + Logger::warning("Could not determine number of cores, defaulting to 1."); + } + + size_t physicalCoreCountSize = sizeof(physicalCoreCount); + if (sysctlbyname("hw.physicalcpu", &physicalCoreCount, &physicalCoreCountSize, nullptr, 0) < 0) { + Logger::error("Could not get physical core count"); + } + + pageSize = sysconf(_SC_PAGE_SIZE); + if (pageSize <= 0) { + pageSize = 4096; + Logger::warning("Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect."); + } + + mach_timebase_info_data_t convf; + if (mach_timebase_info(&convf) == KERN_SUCCESS) { + machTck = convf.numer / convf.denom; + } else { + Logger::warning("Could not get mach clock tick conversion factor. Defaulting to 100, processes cpu usage might be incorrect."); + machTck = 100; + } + + clkTck = sysconf(_SC_CLK_TCK); + if (clkTck <= 0) { + clkTck = 100; + Logger::warning("Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect."); + } + + int64_t memsize = 0; + size_t size = sizeof(memsize); + if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) < 0) { + Logger::warning("Could not get memory size"); + } + totalMem = memsize; + + //* Get maximum length of process arguments + arg_max = sysconf(_SC_ARG_MAX); + + //? Init for namespace Cpu + Cpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {}); + Cpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {}); + Cpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0); + Cpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0); + Cpu::collect(); + for (auto &[field, vec] : Cpu::current_cpu.cpu_percent) { + if (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field); + } + Cpu::cpuName = Cpu::get_cpuName(); + Cpu::got_sensors = Cpu::get_sensors(); + Cpu::core_mapping = Cpu::get_core_mapping(); + + //? Init for namespace Gpu + #ifdef GPU_SUPPORT + auto shown_gpus = Config::getS("shown_gpus"); + if (shown_gpus.contains("apple")) { + Gpu::AppleSilicon::init(); + } + + if (not Gpu::gpu_names.empty()) { + for (auto const& [key, _] : Gpu::gpus[0].gpu_percent) + Cpu::available_fields.push_back(key); + for (auto const& [key, _] : Gpu::shared_gpu_percent) + Cpu::available_fields.push_back(key); + + using namespace Gpu; + count = gpus.size(); + gpu_b_height_offsets.resize(gpus.size()); + for (size_t i = 0; i < gpu_b_height_offsets.size(); ++i) + gpu_b_height_offsets[i] = gpus[i].supported_functions.gpu_utilization + + gpus[i].supported_functions.pwr_usage + + (gpus[i].supported_functions.encoder_utilization or gpus[i].supported_functions.decoder_utilization) + + (gpus[i].supported_functions.mem_total or gpus[i].supported_functions.mem_used) + * (1 + 2*(gpus[i].supported_functions.mem_total and gpus[i].supported_functions.mem_used) + 2*gpus[i].supported_functions.mem_utilization); + } + #endif + + //? Init for namespace Mem + Mem::old_uptime = system_uptime(); + Mem::collect(); + } + +} // namespace Shared + +namespace Cpu { + string cpuName; + string cpuHz; + bool has_battery = true; + bool macM1 = false; + tuple current_bat; + + const array time_names = {"user", "nice", "system", "idle"}; + + std::unordered_map cpu_old = { + {"totals", 0}, + {"idles", 0}, + {"user", 0}, + {"nice", 0}, + {"system", 0}, + {"idle", 0} + }; + + string get_cpuName() { + string name; + char buffer[1024]; + size_t size = sizeof(buffer); + if (sysctlbyname("machdep.cpu.brand_string", &buffer, &size, nullptr, 0) < 0) { + Logger::error("Failed to get CPU name"); + return name; + } + return trim_name(string(buffer)); + } + + bool get_sensors() { + Logger::debug("get_sensors(): show_coretemp={} check_temp={}", Config::getB("show_coretemp"), Config::getB("check_temp")); + got_sensors = false; + if (Config::getB("show_coretemp") and Config::getB("check_temp")) { +#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504 + ThermalSensors sensors; + std::vector core_temps; + if (sensors.getSensors(core_temps) > 0) { + Logger::debug("M1 sensors found"); + got_sensors = true; + cpu_temp_only = core_temps.empty(); + macM1 = true; + } else { +#endif + // try SMC (intel) + Logger::debug("checking intel"); + try { + SMCConnection smcCon; + Logger::debug("SMC connection established"); + long long t = smcCon.getTemp(-1); // check if we have package T + if (t > -1) { + Logger::debug("intel sensors found"); + got_sensors = true; + t = smcCon.getTemp(0); + if (t == -1) { + // for some macs the core offset is 1 - check if we get a sane value with 1 + if (smcCon.getTemp(1) > -1) { + Logger::debug("intel sensors with offset 1"); + core_offset = 1; + } + } + } else { + Logger::debug("no intel sensors found"); + got_sensors = false; + } + } catch (std::runtime_error &e) { + Logger::debug("SMC not available: {}", e.what()); + // ignore, we don't have temp (common in VMs) + got_sensors = false; + } +#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504 + } +#endif + } + return got_sensors; + } + + struct SensorResult { + long long package_temp{}; + std::vector core_temps; + bool valid{false}; + }; + + static SensorResult collect_sensors() { + SensorResult result; + try { + if (macM1) { +#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504 + ThermalSensors sensors; + result.package_temp = sensors.getSensors(result.core_temps); + result.valid = true; +#endif + } else { + SMCConnection smcCon; + int threadsPerCore = Shared::coreCount / Shared::physicalCoreCount; + result.package_temp = smcCon.getTemp(-1); + for (int core = 0; core < Shared::coreCount; core++) { + result.core_temps.push_back(smcCon.getTemp((core / threadsPerCore) + core_offset)); + } + result.valid = true; + } + } catch (std::runtime_error &e) { + Logger::error("failed getting CPU temp: {}", e.what()); + } + return result; + } + + void update_sensors() { + static std::future sensor_future; + static SensorResult last_result{}; + + current_cpu.temp_max = 95; // we have no idea how to get the critical temp + + if (sensor_future.valid() and + sensor_future.wait_for(std::chrono::seconds(0)) != std::future_status::timeout) { + last_result = sensor_future.get(); + if (not last_result.valid) { + got_sensors = false; + } + } + + if (last_result.valid) { + current_cpu.temp.at(0).push_back(last_result.package_temp); + if (current_cpu.temp.at(0).size() > 20) + current_cpu.temp.at(0).pop_front(); + + if (macM1) { + cpu_temp_only = last_result.core_temps.empty(); + } + + bool show_coretemp = macM1 ? Config::getB("show_coretemp") : true; + if (show_coretemp and not last_result.core_temps.empty()) { + for (int core = 0; core < Shared::coreCount; core++) { + size_t sensor_index = static_cast(core) * last_result.core_temps.size() / Shared::coreCount; + long long temp = last_result.core_temps.at(sensor_index); + if (cmp_less(core + 1, current_cpu.temp.size())) { + current_cpu.temp.at(core + 1).push_back(temp); + if (current_cpu.temp.at(core + 1).size() > 20) + current_cpu.temp.at(core + 1).pop_front(); + } + } + } + } + + sensor_future = std::async(std::launch::async, collect_sensors); + } + + string get_cpuHz() { + unsigned int freq = 1; + size_t size = sizeof(freq); + + int mib[] = {CTL_HW, HW_CPU_FREQ}; + + if (sysctl(mib, 2, &freq, &size, nullptr, 0) < 0) { + // this fails on Apple Silicon macs. Apparently you're not allowed to know + return ""; + } + return std::to_string(freq / 1000.0 / 1000.0 / 1000.0).substr(0, 3); + } + + auto get_core_mapping() -> std::unordered_map { + std::unordered_map core_map; + if (cpu_temp_only) return core_map; + + natural_t cpu_count; + natural_t i; + MachProcessorInfo info {}; + kern_return_t error; + + error = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count); + if (error != KERN_SUCCESS) { + Logger::error("Failed getting CPU info"); + return core_map; + } + for (i = 0; i < cpu_count; i++) { + core_map[i] = i; + } + + //? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc. + if (cmp_less(core_map.size(), Shared::coreCount)) { + if (Shared::coreCount % 2 == 0 and (long) core_map.size() == Shared::coreCount / 2) { + for (int i = 0, n = 0; i < Shared::coreCount / 2; i++) { + if (std::cmp_greater_equal(n, core_sensors.size())) n = 0; + core_map[Shared::coreCount / 2 + i] = n++; + } + } else { + core_map.clear(); + for (int i = 0, n = 0; i < Shared::coreCount; i++) { + if (std::cmp_greater_equal(n, core_sensors.size())) n = 0; + core_map[i] = n++; + } + } + } + + //? Apply user set custom mapping if any + const auto &custom_map = Config::getS("cpu_core_map"); + if (not custom_map.empty()) { + try { + for (const auto &split : ssplit(custom_map)) { + const auto vals = ssplit(split, ':'); + if (vals.size() != 2) continue; + int change_id = std::stoi(vals.at(0)); + int new_id = std::stoi(vals.at(1)); + if (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue; + core_map.at(change_id) = new_id; + } + } catch (...) { + } + } + + return core_map; + } + + class IOPSInfo_Wrap { + CFTypeRef data; + public: + IOPSInfo_Wrap() { data = IOPSCopyPowerSourcesInfo(); } + CFTypeRef& operator()() { return data; } + ~IOPSInfo_Wrap() { CFRelease(data); } + }; + + class IOPSList_Wrap { + CFArrayRef data; + public: + IOPSList_Wrap(CFTypeRef cft_ref) { data = IOPSCopyPowerSourcesList(cft_ref); } + CFArrayRef& operator()() { return data; } + ~IOPSList_Wrap() { CFRelease(data); } + }; + + auto get_battery() -> tuple { + if (not has_battery) return {0, 0, 0, ""}; + + uint32_t percent = -1; + long seconds = -1; + string status = "discharging"; + IOPSInfo_Wrap ps_info{}; + if (ps_info()) { + IOPSList_Wrap one_ps_descriptor(ps_info()); + if (one_ps_descriptor()) { + if (CFArrayGetCount(one_ps_descriptor())) { + CFDictionaryRef one_ps = IOPSGetPowerSourceDescription(ps_info(), CFArrayGetValueAtIndex(one_ps_descriptor(), 0)); + has_battery = true; + CFNumberRef remaining = (CFNumberRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSTimeToEmptyKey)); + int32_t estimatedMinutesRemaining; + if (remaining) { + CFNumberGetValue(remaining, kCFNumberSInt32Type, &estimatedMinutesRemaining); + seconds = estimatedMinutesRemaining * 60; + } + CFNumberRef charge = (CFNumberRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSCurrentCapacityKey)); + if (charge) { + CFNumberGetValue(charge, kCFNumberSInt32Type, &percent); + } + CFBooleanRef charging = (CFBooleanRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSIsChargingKey)); + if (charging) { + bool isCharging = CFBooleanGetValue(charging); + if (isCharging) { + status = "charging"; + } + } + if (percent == 100) { + status = "full"; + } + } else { + has_battery = false; + } + } else { + has_battery = false; + } + } + return {percent, -1, seconds, status}; + } + + auto collect(bool no_update) -> cpu_info & { + if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) + return current_cpu; + auto &cpu = current_cpu; + + if (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) { + Logger::error("failed to get load averages"); + } + + natural_t cpu_count; + natural_t i; + kern_return_t error; + processor_cpu_load_info_data_t *cpu_load_info = nullptr; + + MachProcessorInfo info{}; + error = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count); + if (error != KERN_SUCCESS) { + Logger::error("Failed getting CPU load info"); + } + cpu_load_info = (processor_cpu_load_info_data_t *)info.info_array; + long long global_totals = 0; + long long global_idles = 0; + vector times_summed = {0, 0, 0, 0}; + for (i = 0; i < cpu_count; i++) { + vector times; + //? 0=user, 1=nice, 2=system, 3=idle + for (int x = 0; const unsigned int c_state : {CPU_STATE_USER, CPU_STATE_NICE, CPU_STATE_SYSTEM, CPU_STATE_IDLE}) { + auto val = cpu_load_info[i].cpu_ticks[c_state]; + times.push_back(val); + times_summed.at(x++) += val; + } + + try { + //? All values + const long long totals = std::accumulate(times.begin(), times.end(), 0ll); + + //? Idle time + const long long idles = times.at(3); + + global_totals += totals; + global_idles += idles; + + //? Calculate cpu total for each core + if (i > Shared::coreCount) break; + const long long calc_totals = max(0ll, totals - core_old_totals.at(i)); + const long long calc_idles = max(0ll, idles - core_old_idles.at(i)); + core_old_totals.at(i) = totals; + core_old_idles.at(i) = idles; + + cpu.core_percent.at(i).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll)); + + //? Reduce size if there are more values than needed for graph + if (cpu.core_percent.at(i).size() > 40) cpu.core_percent.at(i).pop_front(); + + } catch (const std::exception &e) { + Logger::error("Cpu::collect() : {}", e.what()); + throw std::runtime_error(fmt::format("collect() : {}", e.what())); + } + } + + const long long calc_totals = max(1ll, global_totals - cpu_old.at("totals")); + const long long calc_idles = max(1ll, global_idles - cpu_old.at("idles")); + + //? Populate cpu.cpu_percent with all fields from syscall + for (int ii = 0; const auto &val : times_summed) { + cpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll)); + cpu_old.at(time_names.at(ii)) = val; + + //? Reduce size if there are more values than needed for graph + while (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front(); + + ii++; + } + + cpu_old.at("totals") = global_totals; + cpu_old.at("idles") = global_idles; + + //? Total usage of cpu + cpu.cpu_percent.at("total").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll)); + + //? Reduce size if there are more values than needed for graph + while (cmp_greater(cpu.cpu_percent.at("total").size(), width * 2)) cpu.cpu_percent.at("total").pop_front(); + + if (Config::getB("show_cpu_freq")) { + auto hz = get_cpuHz(); + if (hz != "") { + cpuHz = hz; + } + } + + if (Config::getB("check_temp") and got_sensors) + update_sensors(); + + if (Config::getB("show_battery") and has_battery) + current_bat = get_battery(); + + return cpu; + } +} // namespace Cpu + +namespace Mem { + bool has_swap = false; + vector fstab; + fs::file_time_type fstab_time; + int disk_ios = 0; + vector last_found; + static std::mutex iokit_mutex; // Protect concurrent IOKit calls + static std::mutex interface_mutex; // Protect concurrent interface access during USB device changes + + mem_info current_mem{}; + + uint64_t get_totalMem() { + return Shared::totalMem; + } + + int64_t getCFNumber(CFDictionaryRef dict, const void *key) { + CFNumberRef ref = (CFNumberRef)CFDictionaryGetValue(dict, key); + if (ref) { + int64_t value; + CFNumberGetValue(ref, kCFNumberSInt64Type, &value); + return value; + } + return 0; + } + + string getCFString(io_registry_entry_t volumeRef, CFStringRef key) { + CFStringRef bsdNameRef = (CFStringRef)IORegistryEntryCreateCFProperty(volumeRef, key, kCFAllocatorDefault, 0); + if (bsdNameRef) { + char buf[200]; + CFStringGetCString(bsdNameRef, buf, 200, kCFStringEncodingASCII); + CFRelease(bsdNameRef); + return string(buf); + } + return ""; + } + + bool isWhole(io_registry_entry_t volumeRef) { + CFBooleanRef isWhole = (CFBooleanRef)IORegistryEntryCreateCFProperty(volumeRef, CFSTR("Whole"), kCFAllocatorDefault, 0); + Boolean val = CFBooleanGetValue(isWhole); + CFRelease(isWhole); + return bool(val); + } + + class IOObject { + public: + IOObject(string name, io_object_t& obj) : name(name), object(obj) {} + virtual ~IOObject() { IOObjectRelease(object); } + private: + string name; + io_object_t &object; + }; + + void collect_disk(std::unordered_map &disks, std::unordered_map &mapping) { + // Lock mutex to prevent concurrent IOKit access + std::lock_guard lock(iokit_mutex); + + io_registry_entry_t drive; + io_iterator_t drive_list; + + /* Get the list of all drive objects. */ + if (IOServiceGetMatchingServices(kIOMainPortDefault, + IOServiceMatching("IOMediaBSDClient"), &drive_list)) { + Logger::error("Error in IOServiceGetMatchingServices()"); + return; + } + auto d = IOObject("drive list", drive_list); // dummy var so it gets destroyed + while ((drive = IOIteratorNext(drive_list)) != 0) { + auto dr = IOObject("drive", drive); + io_registry_entry_t volumeRef; + IORegistryEntryGetParentEntry(drive, kIOServicePlane, &volumeRef); + if (volumeRef) { + if (!isWhole(volumeRef)) { + string bsdName = getCFString(volumeRef, CFSTR("BSD Name")); + string device = getCFString(volumeRef, CFSTR("VolGroupMntFromName")); + if (!mapping.contains(device)) { + device = "/dev/" + bsdName; // try again with BSD name - not all volumes seem to have VolGroupMntFromName property + } + if (device != "") { + if (mapping.contains(device)) { + string mountpoint = mapping.at(device); + if (disks.contains(mountpoint)) { + auto& disk = disks.at(mountpoint); + CFDictionaryRef properties = nullptr; + if (IORegistryEntryCreateCFProperties(volumeRef, (CFMutableDictionaryRef *)&properties, kCFAllocatorDefault, 0) == KERN_SUCCESS and properties != nullptr) { + CFDictionaryRef statistics = (CFDictionaryRef)CFDictionaryGetValue(properties, CFSTR("Statistics")); + if (statistics) { + disk_ios++; + int64_t readBytes = getCFNumber(statistics, CFSTR("Bytes read from block device")); + if (disk.io_read.empty()) + disk.io_read.push_back(0); + else + disk.io_read.push_back(max((int64_t)0, (readBytes - disk.old_io.at(0)))); + disk.old_io.at(0) = readBytes; + while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front(); + + int64_t writeBytes = getCFNumber(statistics, CFSTR("Bytes written to block device")); + if (disk.io_write.empty()) + disk.io_write.push_back(0); + else + disk.io_write.push_back(max((int64_t)0, (writeBytes - disk.old_io.at(1)))); + disk.old_io.at(1) = writeBytes; + while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front(); + + // IOKit does not give us IO times, (use IO read + IO write with 1 MiB being 100% to get some activity indication) + if (disk.io_activity.empty()) + disk.io_activity.push_back(0); + else + disk.io_activity.push_back(clamp((long)round((double)(disk.io_write.back() + disk.io_read.back()) / (1 << 20)), 0l, 100l)); + while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front(); + } + CFRelease(properties); + } + } + } + } + } + } + } + } + + auto collect(bool no_update) -> mem_info & { + if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) + return current_mem; + + auto show_swap = Config::getB("show_swap"); + auto show_disks = Config::getB("show_disks"); + auto swap_disk = Config::getB("swap_disk"); + auto &mem = current_mem; + static bool snapped = (getenv("BTOP_SNAPPED") != nullptr); + + vm_statistics64 p; + mach_msg_type_number_t info_size = HOST_VM_INFO64_COUNT; + if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&p, &info_size) == 0) { + mem.stats.at("free") = p.free_count * Shared::pageSize; + mem.stats.at("cached") = p.external_page_count * Shared::pageSize; + mem.stats.at("used") = (p.active_count + p.wire_count) * Shared::pageSize; + mem.stats.at("available") = Shared::totalMem - mem.stats.at("used"); + } + + int mib[2] = {CTL_VM, VM_SWAPUSAGE}; + + struct xsw_usage swap; + size_t len = sizeof(struct xsw_usage); + if (sysctl(mib, 2, &swap, &len, nullptr, 0) == 0) { + mem.stats.at("swap_total") = swap.xsu_total; + mem.stats.at("swap_free") = swap.xsu_avail; + mem.stats.at("swap_used") = swap.xsu_used; + } + + if (show_swap and mem.stats.at("swap_total") > 0) { + for (const auto &name : swap_names) { + mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at("swap_total"))); + while (cmp_greater(mem.percent.at(name).size(), width * 2)) + mem.percent.at(name).pop_front(); + } + has_swap = true; + } else + has_swap = false; + //? Calculate percentages + for (const auto &name : mem_names) { + mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / Shared::totalMem)); + while (cmp_greater(mem.percent.at(name).size(), width * 2)) + mem.percent.at(name).pop_front(); + } + + if (show_disks) { + std::unordered_map mapping; // keep mapping from device -> mountpoint, since IOKit doesn't give us the mountpoint + double uptime = system_uptime(); + auto &disks_filter = Config::getS("disks_filter"); + bool filter_exclude = false; + // auto only_physical = Config::getB("only_physical"); + auto &disks = mem.disks; + vector filter; + if (not disks_filter.empty()) { + filter = ssplit(disks_filter); + if (filter.at(0).starts_with("exclude=")) { + filter_exclude = true; + filter.at(0) = filter.at(0).substr(8); + } + } + + struct statfs *stfs; + int count = getmntinfo(&stfs, MNT_NOWAIT); + vector found; + found.reserve(last_found.size()); + for (int i = 0; i < count; i++) { + std::error_code ec; + string mountpoint = stfs[i].f_mntonname; + string dev = stfs[i].f_mntfromname; + mapping[dev] = mountpoint; + + if (string(stfs[i].f_fstypename) == "autofs") { + continue; + } + + //? Match filter if not empty + if (not filter.empty()) { + bool match = v_contains(filter, mountpoint); + if ((filter_exclude and match) or (not filter_exclude and not match)) + continue; + } + + found.push_back(mountpoint); + if (not disks.contains(mountpoint)) { + disks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename()}; + + if (disks.at(mountpoint).dev.empty()) + disks.at(mountpoint).dev = dev; + + if (disks.at(mountpoint).name.empty()) + disks.at(mountpoint).name = (mountpoint == "/" ? "root" : mountpoint); + } + + + if (not v_contains(last_found, mountpoint)) + redraw = true; + + disks.at(mountpoint).free = stfs[i].f_bfree; + disks.at(mountpoint).total = stfs[i].f_iosize; + } + + //? Remove disks no longer mounted or filtered out + if (swap_disk and has_swap) found.push_back("swap"); + for (auto it = disks.begin(); it != disks.end();) { + if (not v_contains(found, it->first)) + it = disks.erase(it); + else + it++; + } + if (found.size() != last_found.size()) redraw = true; + last_found = std::move(found); + + //? Get disk/partition stats asynchronously to avoid blocking on unresponsive network mounts (e.g. SMB/NFS during backup) + static std::unordered_map>> disks_stats_promises; + for (auto it = disks.begin(); it != disks.end(); ) { + auto &[mountpoint, disk] = *it; + if (mountpoint == "swap") { + ++it; + continue; + } + if (auto promises_it = disks_stats_promises.find(mountpoint); promises_it != disks_stats_promises.end()) { + auto& promise = promises_it->second; + if (promise.valid() && promise.wait_for(std::chrono::seconds(0)) == std::future_status::timeout) { + ++it; + continue; + } + auto promise_res = promises_it->second.get(); + disks_stats_promises.erase(promises_it); + if (promise_res.second != -1) { + Logger::warning("Failed to get disk/partition stats with statvfs() for: {}", mountpoint); + ++it; + continue; + } + auto &updated_stats = promise_res.first; + disk.total = updated_stats.total; + disk.free = updated_stats.free; + disk.used = updated_stats.used; + disk.used_percent = updated_stats.used_percent; + disk.free_percent = updated_stats.free_percent; + } + disks_stats_promises[mountpoint] = std::async(std::launch::async, [mountpoint]() -> std::pair { + struct statvfs vfs; + disk_info disk; + if (statvfs(mountpoint.c_str(), &vfs) < 0) { + return {disk, errno}; + } + disk.total = vfs.f_blocks * vfs.f_frsize; + disk.free = vfs.f_bfree * vfs.f_frsize; + disk.used = disk.total - disk.free; + if (disk.total != 0) { + disk.used_percent = round((double)disk.used * 100 / disk.total); + disk.free_percent = 100 - disk.used_percent; + } else { + disk.used_percent = 0; + disk.free_percent = 0; + } + return {disk, -1}; + }); + ++it; + } + + //? Setup disks order in UI and add swap if enabled + mem.disks_order.clear(); + if (snapped and disks.contains("/mnt")) + mem.disks_order.push_back("/mnt"); + else if (disks.contains("/")) + mem.disks_order.push_back("/"); + if (swap_disk and has_swap) { + mem.disks_order.push_back("swap"); + if (not disks.contains("swap")) + disks["swap"] = {"", "swap"}; + disks.at("swap").total = mem.stats.at("swap_total"); + disks.at("swap").used = mem.stats.at("swap_used"); + disks.at("swap").free = mem.stats.at("swap_free"); + disks.at("swap").used_percent = mem.percent.at("swap_used").back(); + disks.at("swap").free_percent = mem.percent.at("swap_free").back(); + } + for (const auto &name : last_found) + if (not is_in(name, "/", "swap", "/dev")) + mem.disks_order.push_back(name); + + disk_ios = 0; + collect_disk(disks, mapping); + + old_uptime = uptime; + } + return mem; + } + +} // namespace Mem + +namespace Net { + std::unordered_map current_net; + net_info empty_net = {}; + vector interfaces; + string selected_iface; + int errors = 0; + std::unordered_map graph_max = {{"download", {}}, {"upload", {}}}; + std::unordered_map> max_count = {{"download", {}}, {"upload", {}}}; + bool rescale = true; + uint64_t timestamp = 0; + + //* RAII wrapper for getifaddrs + class getifaddr_wrapper { + struct ifaddrs *ifaddr; + + public: + int status; + getifaddr_wrapper() { status = getifaddrs(&ifaddr); } + ~getifaddr_wrapper() { freeifaddrs(ifaddr); } + auto operator()() -> struct ifaddrs * { return ifaddr; } + }; + + auto collect(bool no_update) -> net_info & { + // Lock mutex to prevent concurrent interface access during USB device changes + std::lock_guard lock(Mem::interface_mutex); + auto &net = current_net; + auto &config_iface = Config::getS("net_iface"); + auto net_sync = Config::getB("net_sync"); + auto net_auto = Config::getB("net_auto"); + auto new_timestamp = time_ms(); + + if (not no_update and errors < 3) { + //? Get interface list using getifaddrs() wrapper + getifaddr_wrapper if_wrap{}; + if (if_wrap.status != 0) { + errors++; + Logger::error("Net::collect() -> getifaddrs() failed with id {}", if_wrap.status); + redraw = true; + return empty_net; + } + int family = 0; + static_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance. + enum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert + char ip[IPBUFFER_MAXSIZE]; + interfaces.clear(); + string ipv4, ipv6; + + //? Iteration over all items in getifaddrs() list + for (auto *ifa = if_wrap(); ifa != nullptr; ifa = ifa->ifa_next) { + if (ifa->ifa_addr == nullptr) continue; + family = ifa->ifa_addr->sa_family; + const auto &iface = ifa->ifa_name; + //? Update available interfaces vector and get status of interface + if (not v_contains(interfaces, iface)) { + interfaces.push_back(iface); + net[iface].connected = (ifa->ifa_flags & IFF_RUNNING); + // An interface can have more than one IP of the same family associated with it, + // but we pick only the first one to show in the NET box. + // Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable! + net[iface].ipv4.clear(); + net[iface].ipv6.clear(); + } + //? Get IPv4 address + if (family == AF_INET) { + if (net[iface].ipv4.empty()) { + if (nullptr != inet_ntop(family, &(reinterpret_cast(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) { + net[iface].ipv4 = ip; + } else { + int errsv = errno; + Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}", iface, strerror(errsv)); + } + } + } + //? Get IPv6 address + else if (family == AF_INET6) { + if (net[iface].ipv6.empty()) { + if (nullptr != inet_ntop(family, &(reinterpret_cast(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) { + net[iface].ipv6 = ip; + } else { + int errsv = errno; + Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}", iface, strerror(errsv)); + } + } + } // else, ignoring family==AF_LINK (see man 3 getifaddrs) + } + + std::unordered_map> ifstats; + int mib[] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0}; + size_t len; + if (sysctl(mib, 6, nullptr, &len, nullptr, 0) < 0) { + Logger::error("failed getting network interfaces"); + } else { + std::unique_ptr buf(new char[len]); + if (sysctl(mib, 6, buf.get(), &len, nullptr, 0) < 0) { + Logger::error("failed getting network interfaces"); + } else { + char *lim = buf.get() + len; + char *next = nullptr; + for (next = buf.get(); next < lim;) { + struct if_msghdr *ifm = (struct if_msghdr *)next; + next += ifm->ifm_msglen; + if (ifm->ifm_type == RTM_IFINFO2) { + struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm; + struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1); + char iface[32]; + strncpy(iface, sdl->sdl_data, sdl->sdl_nlen); + iface[sdl->sdl_nlen] = 0; + ifstats[iface] = std::tuple(if2m->ifm_data.ifi_ibytes, if2m->ifm_data.ifi_obytes); + } + } + } + } + + //? Get total received and transmitted bytes + device address if no ip was found + for (const auto &iface : interfaces) { + for (const string dir : {"download", "upload"}) { + auto &saved_stat = net.at(iface).stat.at(dir); + auto &bandwidth = net.at(iface).bandwidth.at(dir); + uint64_t val = dir == "download" ? std::get<0>(ifstats[iface]) : std::get<1>(ifstats[iface]); + + //? Update speed, total and top values + if (val < saved_stat.last) { + saved_stat.rollover += saved_stat.last; + saved_stat.last = 0; + } + if (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits::max())) { + saved_stat.rollover = 0; + saved_stat.last = 0; + } + saved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000)); + if (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed; + if (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0; + saved_stat.total = (val + saved_stat.rollover) - saved_stat.offset; + saved_stat.last = val; + + //? Add values to graph + bandwidth.push_back(saved_stat.speed); + while (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front(); + + //? Set counters for auto scaling + if (net_auto and selected_iface == iface) { + if (saved_stat.speed > graph_max[dir]) { + ++max_count[dir][0]; + if (max_count[dir][1] > 0) --max_count[dir][1]; + } else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) { + ++max_count[dir][1]; + if (max_count[dir][0] > 0) --max_count[dir][0]; + } + } + } + } + + //? Clean up net map if needed + if (net.size() > interfaces.size()) { + for (auto it = net.begin(); it != net.end();) { + if (not v_contains(interfaces, it->first)) + it = net.erase(it); + else + it++; + } + } + + timestamp = new_timestamp; + } + //? Return empty net_info struct if no interfaces was found + if (net.empty()) + return empty_net; + + //? Find an interface to display if selected isn't set or valid + if (selected_iface.empty() or not v_contains(interfaces, selected_iface)) { + max_count["download"][0] = max_count["download"][1] = max_count["upload"][0] = max_count["upload"][1] = 0; + redraw = true; + if (net_auto) rescale = true; + if (not config_iface.empty() and v_contains(interfaces, config_iface)) + selected_iface = config_iface; + else { + //? Sort interfaces by total upload + download bytes + auto sorted_interfaces = interfaces; + rng::sort(sorted_interfaces, [&](const auto &a, const auto &b) { + return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total, + net.at(b).stat["download"].total + net.at(b).stat["upload"].total); + }); + selected_iface.clear(); + //? Try to set to a connected interface + for (const auto &iface : sorted_interfaces) { + if (net.at(iface).connected) selected_iface = iface; + break; + } + //? If no interface is connected set to first available + if (selected_iface.empty() and not sorted_interfaces.empty()) + selected_iface = sorted_interfaces.at(0); + else if (sorted_interfaces.empty()) + return empty_net; + } + } + + //? Calculate max scale for graphs if needed + if (net_auto) { + bool sync = false; + for (const auto &dir : {"download", "upload"}) { + for (const auto &sel : {0, 1}) { + if (rescale or max_count[dir][sel] >= 5) { + const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5 + ? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5 + : net[selected_iface].stat[dir].speed); + graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10); + max_count[dir][0] = max_count[dir][1] = 0; + redraw = true; + if (net_sync) sync = true; + break; + } + } + //? Sync download/upload graphs if enabled + if (sync) { + const auto other = (string(dir) == "upload" ? "download" : "upload"); + graph_max[other] = graph_max[dir]; + max_count[other][0] = max_count[other][1] = 0; + break; + } + } + } + + rescale = false; + return net.at(selected_iface); + } +} // namespace Net + +namespace Proc { + + vector current_procs; + std::unordered_map uid_user; + string current_sort; + string current_filter; + bool current_rev = false; + bool is_tree_mode; + + fs::file_time_type passwd_time; + + uint64_t cputimes; + int collapse = -1, expand = -1, toggle_children = -1, collapse_all = -1; + uint64_t old_cputimes = 0; + atomic numpids = 0; + int filter_found = 0; + + detail_container detailed; + static std::unordered_set dead_procs; + + string get_status(char s) { + if (s & SRUN) return "Running"; + if (s & SSLEEP) return "Sleeping"; + if (s & SIDL) return "Idle"; + if (s & SSTOP) return "Stopped"; + if (s & SZOMB) return "Zombie"; + return "Unknown"; + } + + //* Get detailed info for selected process + void _collect_details(const size_t pid, vector &procs) { + if (pid != detailed.last_pid) { + detailed = {}; + detailed.last_pid = pid; + detailed.skip_smaps = not Config::getB("proc_info_smaps"); + } + + //? Copy proc_info for process from proc vector + auto p_info = rng::find(procs, pid, &proc_info::pid); + detailed.entry = *p_info; + + //? Update cpu percent deque for process cpu graph + if (not Config::getB("proc_per_core")) detailed.entry.cpu_p *= Shared::coreCount; + detailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll)); + while (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front(); + + //? Process runtime : current time - start time (both in unix time - seconds since epoch) + struct timeval currentTime; + gettimeofday(¤tTime, nullptr); + //? Get elapsed time if process isn't dead + if (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(currentTime.tv_sec - (detailed.entry.cpu_s / 1'000'000)); + else detailed.elapsed = sec_to_dhms(detailed.entry.death_time); + if (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3); + + //? Get parent process name + if (detailed.parent.empty()) { + auto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid); + if (p_entry != procs.end()) detailed.parent = p_entry->name; + } + + //? Expand process status from single char to explanative string + detailed.status = get_status(detailed.entry.state); + + detailed.mem_bytes.push_back(detailed.entry.mem); + detailed.memory = floating_humanizer(detailed.entry.mem); + + if (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) { + detailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem()); + redraw = true; + } + + while (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front(); + + rusage_info_current rusage; + if (proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, (void **)&rusage) == 0) { + // this fails for processes we don't own - same as in Linux + detailed.io_read = floating_humanizer(rusage.ri_diskio_bytesread); + detailed.io_write = floating_humanizer(rusage.ri_diskio_byteswritten); + } + } + + //* Collects and sorts process information from /proc + auto collect(bool no_update) -> vector & { + const auto &sorting = Config::getS("proc_sorting"); + auto reverse = Config::getB("proc_reversed"); + const auto &filter = Config::getS("proc_filter"); + auto per_core = Config::getB("proc_per_core"); + auto tree = Config::getB("proc_tree"); + auto show_detailed = Config::getB("show_detailed"); + const auto pause_proc_list = Config::getB("pause_proc_list"); + const size_t detailed_pid = Config::getI("detailed_pid"); + bool should_filter = current_filter != filter; + if (should_filter) current_filter = filter; + bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter); + bool tree_mode_change = tree != is_tree_mode; + if (sorted_change) { + current_sort = sorting; + current_rev = reverse; + } + if (tree_mode_change) is_tree_mode = tree; + + const int cmult = (per_core) ? Shared::coreCount : 1; + bool got_detailed = false; + + static vector found; + + //* Use pids from last update if only changing filter, sorting or tree options + if (no_update and not current_procs.empty()) { + if (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, current_procs); + } else { + //* ---------------------------------------------Collection start---------------------------------------------- + + { //* Get CPU totals + natural_t cpu_count; + kern_return_t error; + processor_cpu_load_info_data_t *cpu_load_info = nullptr; + MachProcessorInfo info{}; + error = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count); + if (error != KERN_SUCCESS) { + Logger::error("Failed getting CPU load info"); + } + cpu_load_info = (processor_cpu_load_info_data_t *)info.info_array; + cputimes = 0; + for (natural_t i = 0; i < cpu_count; i++) { + cputimes += (cpu_load_info[i].cpu_ticks[CPU_STATE_USER] + + cpu_load_info[i].cpu_ticks[CPU_STATE_NICE] + + cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM] + + cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE]); + } + } + + should_filter = true; + int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0}; + found.clear(); + size_t size = 0; + const auto timeNow = time_micros(); + + if (sysctl(mib, 4, nullptr, &size, nullptr, 0) < 0 || size == 0) { + Logger::error("Unable to get size of kproc_infos"); + } + uint64_t cpu_t = 0; + + std::unique_ptr processes(new kinfo_proc[size / sizeof(kinfo_proc)]); + if (sysctl(mib, 4, processes.get(), &size, nullptr, 0) == 0) { + size_t count = size / sizeof(struct kinfo_proc); + for (size_t i = 0; i < count; i++) { //* iterate over all processes in kinfo_proc + struct kinfo_proc& kproc = processes.get()[i]; + const size_t pid = (size_t)kproc.kp_proc.p_pid; + if (pid < 1) continue; + found.push_back(pid); + + //? Check if pid already exists in current_procs + bool no_cache = false; + auto find_old = rng::find(current_procs, pid, &proc_info::pid); + //? Only add new processes if not paused + if (find_old == current_procs.end()) { + if (not pause_proc_list) { + current_procs.push_back({pid}); + find_old = current_procs.end() - 1; + no_cache = true; + } + else continue; + } + else if (dead_procs.contains(pid)) continue; + + auto &new_proc = *find_old; + + //? Get program name, command, username, parent pid, nice and status + if (no_cache) { + char fullname[PROC_PIDPATHINFO_MAXSIZE]; + int rc = proc_pidpath(pid, fullname, sizeof(fullname)); + string f_name = ""; + if (rc != 0) { + f_name = std::string(fullname); + size_t lastSlash = f_name.find_last_of('/'); + f_name = f_name.substr(lastSlash + 1); + } + new_proc.name = f_name; + //? Get process arguments if possible, fallback to process path in case of failure + if (Shared::arg_max > 0) { + std::unique_ptr proc_chars(new char[Shared::arg_max]); + int mib[] = {CTL_KERN, KERN_PROCARGS2, (int)pid}; + size_t argmax = Shared::arg_max; + if (sysctl(mib, 3, proc_chars.get(), &argmax, nullptr, 0) == 0) { + int argc = 0; + memcpy(&argc, &proc_chars.get()[0], sizeof(argc)); + std::string_view proc_args(proc_chars.get(), argmax); + if (size_t null_pos = proc_args.find('\0', sizeof(argc)); null_pos != string::npos) { + if (size_t start_pos = proc_args.find_first_not_of('\0', null_pos); start_pos != string::npos) { + while (argc-- > 0 and null_pos != string::npos and cmp_less(new_proc.cmd.size(), 1000)) { + null_pos = proc_args.find('\0', start_pos); + new_proc.cmd += (string)proc_args.substr(start_pos, null_pos - start_pos) + ' '; + start_pos = null_pos + 1; + } + } + } + if (not new_proc.cmd.empty()) new_proc.cmd.pop_back(); + } + } + if (new_proc.cmd.empty()) new_proc.cmd = f_name; + if (new_proc.cmd.size() > 1000) { + new_proc.cmd.resize(1000); + new_proc.cmd.shrink_to_fit(); + } + new_proc.ppid = kproc.kp_eproc.e_ppid; + new_proc.cpu_s = kproc.kp_proc.p_starttime.tv_sec * 1'000'000 + kproc.kp_proc.p_starttime.tv_usec; + struct passwd *pwd = getpwuid(kproc.kp_eproc.e_ucred.cr_uid); + if (pwd != nullptr) { + new_proc.user = pwd->pw_name; + } else { + new_proc.user = std::to_string(kproc.kp_eproc.e_ucred.cr_uid); + } + } + new_proc.p_nice = kproc.kp_proc.p_nice; + new_proc.state = kproc.kp_proc.p_stat; + + //? Get threads, mem and cpu usage + struct proc_taskinfo pti{}; + if (sizeof(pti) == proc_pidinfo(new_proc.pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti))) { + new_proc.threads = pti.pti_threadnum; + new_proc.mem = pti.pti_resident_size; + cpu_t = pti.pti_total_user + pti.pti_total_system; + + if (new_proc.cpu_t == 0) new_proc.cpu_t = cpu_t; + } else { + // Reset memory value if process info cannot be accessed (bad permissions or zombie processes) + new_proc.threads = 0; + new_proc.mem = 0; + cpu_t = new_proc.cpu_t; + } + + //? Process cpu usage since last update + new_proc.cpu_p = clamp(round(((cpu_t - new_proc.cpu_t) * Shared::machTck) / ((cputimes - old_cputimes) * Shared::clkTck)) * cmult / 1000.0, 0.0, 100.0 * Shared::coreCount); + + //? Process cumulative cpu usage since process start + new_proc.cpu_c = (double)(cpu_t * Shared::machTck) / (timeNow - new_proc.cpu_s); + + //? Update cached value with latest cpu times + new_proc.cpu_t = cpu_t; + + if (show_detailed and not got_detailed and new_proc.pid == detailed_pid) { + got_detailed = true; + } + } + + //? Clear dead processes from current_procs if not paused + if (not pause_proc_list) { + auto eraser = rng::remove_if(current_procs, [&](const auto& element) { return not v_contains(found, element.pid); }); + current_procs.erase(eraser.begin(), eraser.end()); + if (!dead_procs.empty()) dead_procs.clear(); + } + //? Set correct state of dead processes if paused + else { + const bool keep_dead_proc_usage = Config::getB("keep_dead_proc_usage"); + for (auto& r : current_procs) { + if (rng::find(found, r.pid) == found.end()) { + if (r.state != 'X') { + struct timeval currentTime; + gettimeofday(¤tTime, nullptr); + r.death_time = currentTime.tv_sec - (r.cpu_s / 1'000'000); + } + r.state = 'X'; + dead_procs.emplace(r.pid); + //? Reset cpu usage for dead processes if paused and option is set + if (!keep_dead_proc_usage) { + r.cpu_p = 0.0; + r.mem = 0; + } + } + } + } + + //? Update the details info box for process if active + if (show_detailed and got_detailed) { + _collect_details(detailed_pid, current_procs); + } else if (show_detailed and not got_detailed and detailed.status != "Dead") { + detailed.status = "Dead"; + redraw = true; + } + + old_cputimes = cputimes; + } + } + + //* ---------------------------------------------Collection done----------------------------------------------- + + //* Match filter if defined + if (should_filter) { + filter_found = 0; + for (auto &p : current_procs) { + if (not tree and not filter.empty()) { + if (!matches_filter(p, filter)) { + p.filtered = true; + filter_found++; + } else { + p.filtered = false; + } + } else { + p.filtered = false; + } + } + } + + //* Sort processes + if ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) { + proc_sorter(current_procs, sorting, reverse, tree); + } + + //* Generate tree view if enabled + if (tree and (not no_update or should_filter or sorted_change)) { + bool locate_selection = false; + + if (toggle_children != -1) { + auto collapser = rng::find(current_procs, toggle_children, &proc_info::pid); + if (collapser != current_procs.end()){ + for (auto& p : current_procs) { + if (p.ppid == collapser->pid) { + auto child = rng::find(current_procs, p.pid, &proc_info::pid); + if (child != current_procs.end()){ + child->collapsed = not child->collapsed; + } + } + } + if (Config::ints.at("proc_selected") > 0) locate_selection = true; + } + toggle_children = -1; + } + + if (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) { + auto collapser = rng::find(current_procs, find_pid, &proc_info::pid); + if (collapser != current_procs.end()) { + if (collapse == expand) { + collapser->collapsed = not collapser->collapsed; + } + else if (collapse > -1) { + collapser->collapsed = true; + } + else if (expand > -1) { + collapser->collapsed = false; + } + if (Config::ints.at("proc_selected") > 0) locate_selection = true; + } + collapse = expand = -1; + } + + if (collapse_all != -1) { + toggle_tree_collapse(current_procs); + collapse_all = -1; + if (Config::ints.at("proc_selected") > 0) locate_selection = true; + } + + if (should_filter or not filter.empty()) filter_found = 0; + + vector tree_procs; + tree_procs.reserve(current_procs.size()); + + if (!pause_proc_list) { + for (auto& p : current_procs) { + if (not v_contains(found, p.ppid)) p.ppid = 0; + } + } + + //? Stable sort to retain selected sorting among processes with the same parent + rng::stable_sort(current_procs, rng::less{}, & proc_info::ppid); + + //? Auto-collapse processes with many children when entering tree mode + _auto_collapse_oversized(current_procs, tree_mode_change); + + //? Start recursive iteration over processes with the lowest shared parent pids + for (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) { + _tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter); + } + + //? Recursive sort over tree structure to account for collapsed processes in the tree + int index = 0; + tree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size()); + + //? Recursive construction of ASCII tree prefixes. + for (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) { + _collect_prefixes(*t, t == tree_procs.end() - 1); + } + + //? Final sort based on tree index + rng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index); + + //? Move current selection/view to the selected process when collapsing/expanding in the tree + if (locate_selection) { + int loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index; + if (Config::ints.at("proc_start") >= loc or Config::ints.at("proc_start") <= loc - Proc::select_max) + Config::ints.at("proc_start") = max(0, loc - 1); + Config::ints.at("proc_selected") = loc - Config::ints.at("proc_start") + 1; + } + } + + numpids = (int)current_procs.size() - filter_found; + return current_procs; + } +} // namespace Proc + +namespace Tools { + double system_uptime() { + struct timeval ts, currTime; + std::size_t len = sizeof(ts); + int mib[2] = {CTL_KERN, KERN_BOOTTIME}; + if (sysctl(mib, 2, &ts, &len, nullptr, 0) != -1) { + gettimeofday(&currTime, nullptr); + return currTime.tv_sec - ts.tv_sec; + } + return 0.0; + } +} // namespace Tools diff --git a/vendor/btop/src/osx/sensors.cpp b/vendor/btop/src/osx/sensors.cpp new file mode 100644 index 000000000..62beeaa79 --- /dev/null +++ b/vendor/btop/src/osx/sensors.cpp @@ -0,0 +1,180 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include +#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504 +#include "sensors.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include + +extern "C" { +typedef struct __IOHIDEvent *IOHIDEventRef; +typedef struct __IOHIDServiceClient *IOHIDServiceClientRef; +#ifdef __LP64__ +typedef double IOHIDFloat; +#else +typedef float IOHIDFloat; +#endif + +#define IOHIDEventFieldBase(type) (type << 16) +#define kIOHIDEventTypeTemperature 15 + +IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator); +int IOHIDEventSystemClientSetMatching(IOHIDEventSystemClientRef client, CFDictionaryRef match); +int IOHIDEventSystemClientSetMatchingMultiple(IOHIDEventSystemClientRef client, CFArrayRef match); +IOHIDEventRef IOHIDServiceClientCopyEvent(IOHIDServiceClientRef, int64_t, int32_t, int64_t); +CFStringRef IOHIDServiceClientCopyProperty(IOHIDServiceClientRef service, CFStringRef property); +IOHIDFloat IOHIDEventGetFloatValue(IOHIDEventRef event, int32_t field); + +// create a dict ref, like for temperature sensor {"PrimaryUsagePage":0xff00, "PrimaryUsage":0x5} +CFDictionaryRef matching(int page, int usage) { + CFNumberRef nums[2]; + CFStringRef keys[2]; + + keys[0] = CFStringCreateWithCString(0, "PrimaryUsagePage", 0); + keys[1] = CFStringCreateWithCString(0, "PrimaryUsage", 0); + nums[0] = CFNumberCreate(0, kCFNumberSInt32Type, &page); + nums[1] = CFNumberCreate(0, kCFNumberSInt32Type, &usage); + + CFDictionaryRef dict = CFDictionaryCreate(0, (const void **)keys, (const void **)nums, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + CFRelease(keys[0]); + CFRelease(keys[1]); + return dict; +} + +double getValue(IOHIDServiceClientRef sc) { + IOHIDEventRef event = IOHIDServiceClientCopyEvent(sc, kIOHIDEventTypeTemperature, 0, 0); // here we use ...CopyEvent + IOHIDFloat temp = 0.0; + if (event != 0) { + temp = IOHIDEventGetFloatValue(event, IOHIDEventFieldBase(kIOHIDEventTypeTemperature)); + CFRelease(event); + } + return temp; +} + +} // extern C + +namespace { + int parse_sensor_index(const std::string& name, const std::string& prefix) { + if (name.rfind(prefix, 0) != 0) return -1; + size_t pos = prefix.size(); + if (pos >= name.size() or not std::isdigit(static_cast(name.at(pos)))) return -1; + int value = 0; + while (pos < name.size() and std::isdigit(static_cast(name.at(pos)))) { + value = (value * 10) + (name.at(pos) - '0'); + pos++; + } + return value; + } + + long long avg_to_long(const std::vector& temps) { + if (temps.empty()) return 0ll; + return round(std::accumulate(temps.begin(), temps.end(), 0ll) / temps.size()); + } +} + +long long Cpu::ThermalSensors::getSensors() { + std::vector unused_core_temps; + return getSensors(unused_core_temps); +} + +long long Cpu::ThermalSensors::getSensors(std::vector& core_temps) { + CFDictionaryRef thermalSensors = matching(0xff00, 5); // 65280_10 = FF00_16 + // thermalSensors's PrimaryUsagePage should be 0xff00 for M1 chip, instead of 0xff05 + // can be checked by ioreg -lfx + IOHIDEventSystemClientRef system = IOHIDEventSystemClientCreate(kCFAllocatorDefault); + IOHIDEventSystemClientSetMatching(system, thermalSensors); + CFArrayRef matchingsrvs = IOHIDEventSystemClientCopyServices(system); + std::vector acc_temps; + std::vector tdie_temps; + std::vector soc_temps; + std::unordered_map > acc_named_temps; + std::unordered_map > tdie_indexed_temps; + if (matchingsrvs) { + long count = CFArrayGetCount(matchingsrvs); + for (int i = 0; i < count; i++) { + IOHIDServiceClientRef sc = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(matchingsrvs, i); + if (sc) { + CFStringRef name = IOHIDServiceClientCopyProperty(sc, CFSTR("Product")); // here we use ...CopyProperty + if (name) { + char buf[200]; + CFStringGetCString(name, buf, 200, kCFStringEncodingASCII); + std::string n(buf); + // this is just a guess, nobody knows which sensors mean what + // on my system PMU tdie 3 and 9 are missing... + // there is also PMU tdev1-8 but it has negative values?? + // there is also eACC for efficiency package but it only has 2 entries + // and pACC for performance but it has 7 entries (2 - 9) WTF + double temp = getValue(sc); + if (temp > 0 and temp < 150) { + if (n.rfind("eACC", 0) == 0 or n.rfind("pACC", 0) == 0) { + acc_temps.push_back(temp); + acc_named_temps[n].push_back(temp); + } else if (n.rfind("PMU tdie", 0) == 0) { + tdie_temps.push_back(temp); + int index = parse_sensor_index(n, "PMU tdie"); + if (index >= 0) tdie_indexed_temps[index].push_back(temp); + } else if (n.rfind("SOC MTR Temp Sensor", 0) == 0) { + soc_temps.push_back(temp); + } + } + CFRelease(name); + } + } + } + CFRelease(matchingsrvs); + } + CFRelease(system); + CFRelease(thermalSensors); + core_temps.clear(); + if (not tdie_indexed_temps.empty()) { + std::vector indexes; + indexes.reserve(tdie_indexed_temps.size()); + for (const auto& indexed_temp : tdie_indexed_temps) { + indexes.push_back(indexed_temp.first); + } + std::sort(indexes.begin(), indexes.end()); + for (const auto& index : indexes) { + auto avg = avg_to_long(tdie_indexed_temps.at(index)); + if (avg > 0) core_temps.push_back(avg); + } + } else if (not acc_named_temps.empty()) { + std::vector names; + names.reserve(acc_named_temps.size()); + for (const auto& named_temp : acc_named_temps) { + names.push_back(named_temp.first); + } + std::sort(names.begin(), names.end()); + for (const auto& name : names) { + auto avg = avg_to_long(acc_named_temps.at(name)); + if (avg > 0) core_temps.push_back(avg); + } + } + + const auto &temps = not acc_temps.empty() ? acc_temps : (not tdie_temps.empty() ? tdie_temps : soc_temps); + return avg_to_long(temps); +} +#endif diff --git a/vendor/btop/src/osx/sensors.hpp b/vendor/btop/src/osx/sensors.hpp new file mode 100644 index 000000000..b7572aa03 --- /dev/null +++ b/vendor/btop/src/osx/sensors.hpp @@ -0,0 +1,31 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include + +#include +#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504 + +namespace Cpu { + class ThermalSensors { + public: + long long getSensors(); + long long getSensors(std::vector& core_temps); + }; +} // namespace Cpu +#endif diff --git a/vendor/btop/src/osx/smc.cpp b/vendor/btop/src/osx/smc.cpp new file mode 100644 index 000000000..cddf6debd --- /dev/null +++ b/vendor/btop/src/osx/smc.cpp @@ -0,0 +1,154 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#include "smc.hpp" + +static constexpr size_t MaxIndexCount = sizeof("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") - 1; +static constexpr const char *KeyIndexes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +static UInt32 _strtoul(char *str, int size, int base) { + UInt32 total = 0; + int i; + + for (i = 0; i < size; i++) { + if (base == 16) { + total += str[i] << (size - 1 - i) * 8; + } else { + total += (unsigned char)(str[i] << (size - 1 - i) * 8); + } + } + return total; +} + +static void _ultostr(char *str, UInt32 val) { + str[0] = '\0'; + snprintf(str, 5, "%c%c%c%c", + (unsigned int)val >> 24, + (unsigned int)val >> 16, + (unsigned int)val >> 8, + (unsigned int)val); +} + +namespace Cpu { + + SMCConnection::SMCConnection() { + CFMutableDictionaryRef matchingDictionary = IOServiceMatching("AppleSMC"); + result = IOServiceGetMatchingServices(0, matchingDictionary, &iterator); + if (result != kIOReturnSuccess) { + throw std::runtime_error("failed to get AppleSMC"); + } + + device = IOIteratorNext(iterator); + IOObjectRelease(iterator); + if (device == 0) { + throw std::runtime_error("failed to get SMC device"); + } + + result = IOServiceOpen(device, mach_task_self(), 0, &conn); + IOObjectRelease(device); + if (result != kIOReturnSuccess) { + throw std::runtime_error("failed to get SMC connection"); + } + } + SMCConnection::~SMCConnection() { + IOServiceClose(conn); + } + + long long SMCConnection::getSMCTemp(char *key) { + SMCVal_t val; + kern_return_t result; + result = SMCReadKey(key, &val); + if (result == kIOReturnSuccess) { + if (val.dataSize > 0) { + if (strcmp(val.dataType, DATATYPE_SP78) == 0) { + // convert sp78 value to temperature + int intValue = val.bytes[0] * 256 + (unsigned char)val.bytes[1]; + return static_cast(intValue / 256.0); + } + } + } + return -1; + } + + // core means physical core in SMC, while in core map it's cpu threads :-/ Only an issue on hackintosh? + // this means we can only get the T per physical core + // another issue with the SMC API is that the key is always 4 chars -> what with systems with more than 9 physical cores? + // no Mac models with more than 18 threads are released, so no problem so far + // according to VirtualSMC docs (hackintosh fake SMC) the enumeration follows with alphabetic chars - not implemented yet here (nor in VirtualSMC) + long long SMCConnection::getTemp(int core) { + char key[] = SMC_KEY_CPU_TEMP; + if (core >= 0) { + if ((size_t)core > MaxIndexCount) { + return -1; + } + snprintf(key, 5, "TC%1cc", KeyIndexes[core]); + } + long long result = getSMCTemp(key); + if (result == -1) { + // try again with C + snprintf(key, 5, "TC%1cC", KeyIndexes[core]); + result = getSMCTemp(key); + } + return result; + } + + kern_return_t SMCConnection::SMCReadKey(UInt32Char_t key, SMCVal_t *val) { + kern_return_t result; + SMCKeyData_t inputStructure; + SMCKeyData_t outputStructure; + + memset(&inputStructure, 0, sizeof(SMCKeyData_t)); + memset(&outputStructure, 0, sizeof(SMCKeyData_t)); + memset(val, 0, sizeof(SMCVal_t)); + + inputStructure.key = _strtoul(key, 4, 16); + inputStructure.data8 = SMC_CMD_READ_KEYINFO; + + result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure); + if (result != kIOReturnSuccess) + return result; + + val->dataSize = outputStructure.keyInfo.dataSize; + _ultostr(val->dataType, outputStructure.keyInfo.dataType); + inputStructure.keyInfo.dataSize = val->dataSize; + inputStructure.data8 = SMC_CMD_READ_BYTES; + + result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure); + if (result != kIOReturnSuccess) + return result; + + memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes)); + + return kIOReturnSuccess; + } + + kern_return_t SMCConnection::SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure) { + size_t structureInputSize; + size_t structureOutputSize; + + structureInputSize = sizeof(SMCKeyData_t); + structureOutputSize = sizeof(SMCKeyData_t); + + return IOConnectCallStructMethod(conn, index, + // inputStructure + inputStructure, structureInputSize, + // outputStructure + outputStructure, &structureOutputSize); + } + +} // namespace Cpu diff --git a/vendor/btop/src/osx/smc.hpp b/vendor/btop/src/osx/smc.hpp new file mode 100644 index 000000000..80a12b1b1 --- /dev/null +++ b/vendor/btop/src/osx/smc.hpp @@ -0,0 +1,119 @@ +/* Copyright 2021 Aristocratos (jakob@qvantnet.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +indent = tab +tab-size = 4 +*/ + +#pragma once + +#ifdef __APPLE__ +#include +#include +#include +#include + +#include + +#define VERSION "0.01" + +#define KERNEL_INDEX_SMC 2 + +#define SMC_CMD_READ_BYTES 5 +#define SMC_CMD_WRITE_BYTES 6 +#define SMC_CMD_READ_INDEX 8 +#define SMC_CMD_READ_KEYINFO 9 +#define SMC_CMD_READ_PLIMIT 11 +#define SMC_CMD_READ_VERS 12 + +#define DATATYPE_FPE2 "fpe2" +#define DATATYPE_UINT8 "ui8 " +#define DATATYPE_UINT16 "ui16" +#define DATATYPE_UINT32 "ui32" +#define DATATYPE_SP78 "sp78" + +// key values +#define SMC_KEY_CPU_TEMP "TC0P" // proximity temp? +#define SMC_KEY_CPU_DIODE_TEMP "TC0D" // diode temp? +#define SMC_KEY_CPU_DIE_TEMP "TC0F" // die temp? +#define SMC_KEY_CPU1_TEMP "TC1C" +#define SMC_KEY_CPU2_TEMP "TC2C" // etc +#define SMC_KEY_FAN0_RPM_CUR "F0Ac" + +typedef struct { + char major; + char minor; + char build; + char reserved[1]; + UInt16 release; +} SMCKeyData_vers_t; + +typedef struct { + UInt16 version; + UInt16 length; + UInt32 cpuPLimit; + UInt32 gpuPLimit; + UInt32 memPLimit; +} SMCKeyData_pLimitData_t; + +typedef struct { + UInt32 dataSize; + UInt32 dataType; + char dataAttributes; +} SMCKeyData_keyInfo_t; + +typedef char SMCBytes_t[32]; + +typedef struct { + UInt32 key; + SMCKeyData_vers_t vers; + SMCKeyData_pLimitData_t pLimitData; + SMCKeyData_keyInfo_t keyInfo; + char result; + char status; + char data8; + UInt32 data32; + SMCBytes_t bytes; +} SMCKeyData_t; + +typedef char UInt32Char_t[5]; + +typedef struct { + UInt32Char_t key; + UInt32 dataSize; + UInt32Char_t dataType; + SMCBytes_t bytes; +} SMCVal_t; + +namespace Cpu { + class SMCConnection { + public: + SMCConnection(); + virtual ~SMCConnection(); + + long long getTemp(int core); + + private: + kern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val); + long long getSMCTemp(char *key); + kern_return_t SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure); + + io_connect_t conn; + kern_return_t result; + mach_port_t masterPort; + io_iterator_t iterator; + io_object_t device; + }; +} // namespace Cpu +#endif // __APPLE__ From 4b4207960f65306e9f25054d77254948ad58e10f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:51:04 +0000 Subject: [PATCH 02/60] feat(vendor): add btop_embed header for embedded btop integration Introduce a header that exposes the interface needed to embed btop's collection and drawing routines into another application. This lets callers drive btop without going through its standalone main loop. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_embed.hpp | 73 ++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 vendor/btop/src/btop_embed.hpp diff --git a/vendor/btop/src/btop_embed.hpp b/vendor/btop/src/btop_embed.hpp new file mode 100644 index 000000000..0edcd1cb3 --- /dev/null +++ b/vendor/btop/src/btop_embed.hpp @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// Medulla embedding seam for btop. +// +// Upstream btop owns a real terminal: it puts stdin in raw mode, reads keys +// with pselect, wakes itself with SIGUSR1, writes escape sequences to stdout and +// ends the process with quick_exit. None of that is acceptable inside a host +// process that owns the terminal itself. This namespace is what the patched +// btop sources call instead: +// +// - output goes to an in-memory buffer the host drains (Embed::write); +// - the terminal size is whatever the host last reported (Embed::size); +// - input arrives as discrete chunks queued by the host (Embed::wait_input); +// - an interrupt is a condition-variable notify, not a signal; +// - "quit" asks the host to leave the view (Embed::request_leave), and a +// fatal error unwinds btop's own thread (Embed::Fatal) instead of exiting. +// +// The C ABI the host links against is in include/medulla_btop.h. + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Embed { + + //* Thrown by clean_quit() on a fatal error; caught at the top of btop's thread. + struct Fatal { + std::string message; + }; + + //* Append terminal output for the host to drain, and wake the host. + void write(std::string_view out); + + //* The host-reported view size in cells. + auto width() -> int; + auto height() -> int; + + //* Block up to for one input chunk from the host. + //* Returns false on timeout or on interrupt(), true with filled otherwise. + bool wait_input(uint64_t timeout_ms, std::string& out); + + //* Wake a thread blocked in wait_input() without delivering input. + void interrupt(); + + //* Record that the operator asked to leave btop (q, or Quit in the menu). + void request_leave(); + + //* Whether the host currently shows btop; collection pauses while hidden. + bool visible(); + + //* Block until the host shows btop again or asks it to stop. + void wait_visible(); + + //* Whether the host asked btop's thread to stop. + bool stopping(); + + //* Directory holding btop.conf, btop.log and user themes. + auto config_dir() -> std::filesystem::path; + + //* One coding-agent process the host classified. + struct Agent { + std::string label; + bool launched{}; + }; + + //* Snapshot of the host's agent table and its change generation. + auto agents() -> std::pair, uint64_t>; +} From ede059a232dbf7d1b620bb831da1f10cc269dec8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:51:14 +0000 Subject: [PATCH 03/60] feat(vendor): add medulla btop header Introduce a new header under the vendored btop include directory to expose the medulla integration interface. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/include/medulla_btop.h | 72 ++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 vendor/btop/include/medulla_btop.h diff --git a/vendor/btop/include/medulla_btop.h b/vendor/btop/include/medulla_btop.h new file mode 100644 index 000000000..cd143a9ee --- /dev/null +++ b/vendor/btop/include/medulla_btop.h @@ -0,0 +1,72 @@ +/* SPDX-License-Identifier: Apache-2.0 + * + * C ABI for running btop inside Medulla. + * + * btop runs on its own thread inside the host process. The host feeds it a + * view size and input bytes, and drains the ANSI output btop would otherwise + * have written to a terminal. Every function is safe to call from any thread. + * + * btop keeps its state in process globals, so it can be started at most once + * per process: medulla_btop_start() after a stop, or a second start, fails. + */ + +#ifndef MEDULLA_BTOP_H +#define MEDULLA_BTOP_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Called (from btop's threads) whenever new output is ready to drain. */ +typedef void (*medulla_btop_waker)(void *ctx); + +/* One coding-agent process, as classified by the host. */ +typedef struct { + uint32_t pid; + /* Short name shown in the Agent column, UTF-8, NUL-terminated. */ + const char *label; + /* Non-zero when the host itself launched this process. */ + uint8_t launched; +} medulla_btop_agent; + +/* Start btop's thread. holds btop.conf and is created if absent. + * Returns 0 on success, -1 if btop was already started in this process, -2 if + * the thread could not be created. */ +int medulla_btop_start(const char *config_dir, uint16_t cols, uint16_t rows, + medulla_btop_waker waker, void *waker_ctx); + +/* Report a new view size in cells. */ +void medulla_btop_resize(uint16_t cols, uint16_t rows); + +/* Queue one key or mouse event, encoded as the terminal bytes a real terminal + * would send (e.g. "\x1b[A", "\x1b[<0;12;4M"). */ +void medulla_btop_input(const uint8_t *bytes, size_t len); + +/* Show or hide btop. While hidden, btop stops collecting and drawing; on show + * it redraws everything. */ +void medulla_btop_set_visible(int visible); + +/* Replace the agent table. Strings are copied. */ +void medulla_btop_set_agents(const medulla_btop_agent *agents, size_t len); + +/* Copy and clear pending output. Calls with the bytes when any exist. */ +void medulla_btop_drain(void (*sink)(void *ctx, const uint8_t *bytes, size_t len), void *ctx); + +/* Returns 1 once per operator request to leave btop, else 0. */ +int medulla_btop_take_leave(void); + +/* Copies a fatal error message, if btop's thread died, into (truncated + * and NUL-terminated). Returns the full message length, or 0 when running. */ +size_t medulla_btop_error(char *buf, size_t cap); + +/* Ask btop's thread to stop, save its config, and wait up to . */ +void medulla_btop_stop(uint32_t timeout_ms); + +#ifdef __cplusplus +} +#endif + +#endif /* MEDULLA_BTOP_H */ From 11265ea4e116bdc2899f5194f59e5fa3bdb46605 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:51:37 +0000 Subject: [PATCH 04/60] feat(vendor): add btop_embed.cpp for embedded btop support Adds the btop embedding source file to the vendored btop tree so the embedded build path can be compiled. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_embed.cpp | 239 +++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 vendor/btop/src/btop_embed.cpp diff --git a/vendor/btop/src/btop_embed.cpp b/vendor/btop/src/btop_embed.cpp new file mode 100644 index 000000000..abcf3c3d8 --- /dev/null +++ b/vendor/btop/src/btop_embed.cpp @@ -0,0 +1,239 @@ +// SPDX-License-Identifier: Apache-2.0 +// +// State behind the Embed seam (btop_embed.hpp) and the C ABI the host links +// against (include/medulla_btop.h). btop's own loop lives in btop.cpp as +// btop_embed_main(); this file only owns the shared state it talks through. + +#include "btop_embed.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include "medulla_btop.h" + +//* btop's thread body, defined in btop.cpp. Returns when Embed::stopping(). +auto btop_embed_main() -> void; + +namespace { + std::mutex out_mtx; + std::string out_buf; + medulla_btop_waker waker = nullptr; + void* waker_ctx = nullptr; + + std::mutex in_mtx; + std::condition_variable in_cv; + std::deque in_queue; + bool in_interrupted = false; + bool shown = true; + + std::atomic view_width{0}; + std::atomic view_height{0}; + std::atomic leave_requested{false}; + std::atomic stop_requested{false}; + std::atomic started{false}; + std::atomic finished{false}; + + std::mutex err_mtx; + std::string fatal_message; + + std::mutex done_mtx; + std::condition_variable done_cv; + + std::filesystem::path conf_dir; + + std::mutex agents_mtx; + std::unordered_map agent_table; + uint64_t agent_generation = 0; + + void wake_host() { + if (waker != nullptr) waker(waker_ctx); + } + + void thread_entry() { + try { + btop_embed_main(); + } + catch (const Embed::Fatal& fatal) { + std::lock_guard lock{err_mtx}; + fatal_message = fatal.message.empty() ? "btop stopped unexpectedly" : fatal.message; + } + catch (const std::exception& e) { + std::lock_guard lock{err_mtx}; + fatal_message = e.what(); + } + catch (...) { + std::lock_guard lock{err_mtx}; + fatal_message = "btop stopped on an unknown exception"; + } + { + std::lock_guard lock{done_mtx}; + finished = true; + } + done_cv.notify_all(); + wake_host(); + } +} + +namespace Embed { + void write(std::string_view out) { + if (out.empty()) return; + { + std::lock_guard lock{out_mtx}; + out_buf.append(out); + } + wake_host(); + } + + auto width() -> int { return view_width.load(); } + auto height() -> int { return view_height.load(); } + + bool wait_input(uint64_t timeout_ms, std::string& out) { + std::unique_lock lock{in_mtx}; + const auto ready = [] { return in_interrupted or not in_queue.empty() or stop_requested.load(); }; + if (timeout_ms == std::numeric_limits::max()) in_cv.wait(lock, ready); + else in_cv.wait_for(lock, std::chrono::milliseconds(timeout_ms), ready); + if (in_interrupted) { + in_interrupted = false; + return false; + } + if (in_queue.empty()) return false; + out = std::move(in_queue.front()); + in_queue.pop_front(); + return true; + } + + void interrupt() { + { + std::lock_guard lock{in_mtx}; + in_interrupted = true; + } + in_cv.notify_all(); + } + + void request_leave() { + leave_requested = true; + wake_host(); + } + + bool visible() { + std::lock_guard lock{in_mtx}; + return shown; + } + + void wait_visible() { + std::unique_lock lock{in_mtx}; + in_cv.wait(lock, [] { return shown or stop_requested.load(); }); + } + + bool stopping() { return stop_requested.load(); } + + auto config_dir() -> std::filesystem::path { return conf_dir; } + + auto agents() -> std::pair, uint64_t> { + std::lock_guard lock{agents_mtx}; + return {agent_table, agent_generation}; + } +} + +extern "C" { + +int medulla_btop_start(const char* config_dir, uint16_t cols, uint16_t rows, + medulla_btop_waker wake, void* wake_ctx) { + if (started.exchange(true)) return -1; + conf_dir = config_dir != nullptr ? std::filesystem::path(config_dir) : std::filesystem::path(); + view_width = cols; + view_height = rows; + waker = wake; + waker_ctx = wake_ctx; + try { + std::thread(thread_entry).detach(); + } + catch (const std::system_error&) { + return -2; + } + return 0; +} + +void medulla_btop_resize(uint16_t cols, uint16_t rows) { + if (view_width.exchange(cols) == cols and view_height.exchange(rows) == rows) return; + Embed::interrupt(); +} + +void medulla_btop_input(const uint8_t* bytes, size_t len) { + if (bytes == nullptr or len == 0) return; + { + std::lock_guard lock{in_mtx}; + in_queue.emplace_back(reinterpret_cast(bytes), len); + } + in_cv.notify_all(); +} + +void medulla_btop_set_visible(int visible) { + { + std::lock_guard lock{in_mtx}; + if (shown == (visible != 0)) return; + shown = visible != 0; + in_interrupted = true; + } + in_cv.notify_all(); +} + +void medulla_btop_set_agents(const medulla_btop_agent* agents, size_t len) { + std::unordered_map table; + for (size_t i = 0; agents != nullptr and i < len; ++i) { + table[agents[i].pid] = Embed::Agent{ + agents[i].label != nullptr ? std::string(agents[i].label) : std::string(), + agents[i].launched != 0, + }; + } + std::lock_guard lock{agents_mtx}; + bool same = table.size() == agent_table.size(); + for (auto it = table.begin(); same and it != table.end(); ++it) { + auto found = agent_table.find(it->first); + same = found != agent_table.end() and found->second.label == it->second.label + and found->second.launched == it->second.launched; + } + if (same) return; + agent_table = std::move(table); + ++agent_generation; +} + +void medulla_btop_drain(void (*sink)(void*, const uint8_t*, size_t), void* ctx) { + std::string taken; + { + std::lock_guard lock{out_mtx}; + taken.swap(out_buf); + } + if (sink != nullptr and not taken.empty()) + sink(ctx, reinterpret_cast(taken.data()), taken.size()); +} + +int medulla_btop_take_leave(void) { + return leave_requested.exchange(false) ? 1 : 0; +} + +size_t medulla_btop_error(char* buf, size_t cap) { + std::lock_guard lock{err_mtx}; + if (buf != nullptr and cap > 0) { + const size_t n = std::min(cap - 1, fatal_message.size()); + std::memcpy(buf, fatal_message.data(), n); + buf[n] = '\0'; + } + return fatal_message.size(); +} + +void medulla_btop_stop(uint32_t timeout_ms) { + if (not started.load()) return; + stop_requested = true; + in_cv.notify_all(); + Embed::interrupt(); + std::unique_lock lock{done_mtx}; + done_cv.wait_for(lock, std::chrono::milliseconds(timeout_ms), [] { return finished.load(); }); +} + +} From e39f3a83b8636c781d56da2b94dfc95e57837ef3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:51:42 +0000 Subject: [PATCH 05/60] fix(btop): evaluate both view dimensions before early return The resize handler short-circuited on the width comparison, so the height exchange was skipped whenever the width was unchanged. Both exchanges now run before the early return so the stored dimensions stay in sync. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_embed.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/vendor/btop/src/btop_embed.cpp b/vendor/btop/src/btop_embed.cpp index abcf3c3d8..8ba952745 100644 --- a/vendor/btop/src/btop_embed.cpp +++ b/vendor/btop/src/btop_embed.cpp @@ -160,7 +160,9 @@ int medulla_btop_start(const char* config_dir, uint16_t cols, uint16_t rows, } void medulla_btop_resize(uint16_t cols, uint16_t rows) { - if (view_width.exchange(cols) == cols and view_height.exchange(rows) == rows) return; + const bool same_width = view_width.exchange(cols) == cols; + const bool same_height = view_height.exchange(rows) == rows; + if (same_width and same_height) return; Embed::interrupt(); } From 352afe544170b0ca6477f694cadde0b74e0fa921 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:51:55 +0000 Subject: [PATCH 06/60] refactor(btop): replace process exit handlers with embed fatal unwinding The vendored btop no longer installs signal handlers or calls quick_exit from clean_quit; fatal errors now throw Embed::Fatal so the host can report the message and unwind btop's thread instead of terminating the process. The standalone main entry point and its CLI, config and TTY setup were removed since Medulla drives btop through the embed API. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop.cpp | 503 +-------------------------------------- 1 file changed, 9 insertions(+), 494 deletions(-) diff --git a/vendor/btop/src/btop.cpp b/vendor/btop/src/btop.cpp index 01e20d991..814098c85 100644 --- a/vendor/btop/src/btop.cpp +++ b/vendor/btop/src/btop.cpp @@ -69,6 +69,7 @@ tab-size = 4 #include "btop_shared.hpp" #include "btop_theme.hpp" #include "btop_tools.hpp" +#include "btop_embed.hpp" using std::atomic; using std::cout; @@ -207,118 +208,17 @@ void term_resize(bool force) { Input::interrupt(); } -//* Exit handler; stops threads, restores terminal and saves config changes +//* Fatal-error handler. Upstream stops threads, restores the terminal and ends +//* the process; embedded in Medulla there is no process to end, so it unwinds +//* btop's own thread instead and the host shows the message. An operator's +//* request to quit goes through Embed::request_leave(), never through here. void clean_quit(int sig) { if (Global::quitting) return; Global::quitting = true; - Runner::stop(); - if (Global::_runner_started) { - #if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__ - if (pthread_join(Runner::runner_id, nullptr) != 0) { - Logger::warning("Failed to join _runner thread on exit!"); - } - #else - constexpr struct timespec ts { .tv_sec = 5, .tv_nsec = 0 }; - if (pthread_timedjoin_np(Runner::runner_id, nullptr, &ts) != 0) { - Logger::warning("Failed to join _runner thread on exit!"); - } - #endif - } - -#ifdef GPU_SUPPORT - Gpu::Nvml::shutdown(); - Gpu::Rsmi::shutdown(); - Gpu::Asysfs::shutdown(); - #ifdef __APPLE__ - Gpu::AppleSilicon::shutdown(); - #endif -#endif - - - if (Config::getB("save_config_on_exit")) { - Config::write(); - } - - if (Term::initialized) { - Input::clear(); - Term::restore(); - } - - if (not Global::exit_error_msg.empty()) { - sig = 1; - Logger::error("{}", Global::exit_error_msg); - fmt::println(std::cerr, "{}ERROR: {}{}{}", Global::fg_red, Global::fg_white, Global::exit_error_msg, Fx::reset); - } - Logger::info("Quitting! Runtime: {}", sec_to_dhms(time_s() - Global::start_time)); - - const auto excode = (sig != -1 ? sig : 0); - -#if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__ - _Exit(excode); -#else - quick_exit(excode); -#endif -} - -//* Handler for SIGTSTP; stops threads, restores terminal and sends SIGSTOP -static void _sleep() { - Runner::stop(); - Term::restore(); - std::raise(SIGSTOP); -} - -//* Handler for SIGCONT; re-initialize terminal and force a resize event -static void _resume() { - Term::init(); - term_resize(true); -} - -static void _exit_handler() { - clean_quit(-1); -} - -static void _crash_handler(const int sig) { - // Restore terminal before crashing - if (Term::initialized) { - Term::restore(); - } - // Re-raise the signal to get default behavior (core dump) - std::signal(sig, SIG_DFL); - std::raise(sig); -} - -static void _signal_handler(const int sig) { - switch (sig) { - case SIGINT: - Global::should_quit = true; - if (Runner::active) Runner::stopping = true; - Input::interrupt(); - break; - case SIGTSTP: - if (Runner::active) { - Global::should_sleep = true; - Runner::stopping = true; - Input::interrupt(); - } - else { - _sleep(); - } - break; - case SIGCONT: - _resume(); - break; - case SIGWINCH: - Global::resized = true; - Input::interrupt(); - break; - case SIGUSR1: - // Input::poll interrupt - break; - case SIGUSR2: - Global::reload_conf = true; - Input::interrupt(); - break; - } + string message = Global::exit_error_msg; + if (message.empty()) message = fmt::format("btop stopped (code {})", sig); + Logger::error("{}", message); + throw Embed::Fatal{message}; } //* Config init @@ -802,388 +702,3 @@ namespace Runner { } -static auto configure_tty_mode(std::optional force_tty) { - if (force_tty.has_value()) { - Config::set("tty_mode", force_tty.value()); - Logger::debug("TTY mode set via command line"); - } - else if (Config::getB("force_tty")) { - Config::set("tty_mode", true); - Logger::debug("TTY mode set via config"); - } - -#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__NetBSD__) - else if (Term::current_tty.starts_with("/dev/tty")) { - Config::set("tty_mode", true); - Logger::debug("Auto detect real TTY"); - } -#endif - - Logger::debug("TTY mode enabled: {}", Config::getB("tty_mode")); -} - - -//* --------------------------------------------- Main starts here! --------------------------------------------------- -[[nodiscard]] auto btop_main(const std::span args) -> int { - - //? ------------------------------------------------ INIT --------------------------------------------------------- - - Global::start_time = time_s(); - - //? Save real and effective userid's and drop privileges until needed if running with SUID bit set - Global::real_uid = getuid(); - Global::set_uid = geteuid(); - if (Global::real_uid != Global::set_uid) { - if (seteuid(Global::real_uid) != 0) { - Global::real_uid = Global::set_uid; - Global::exit_error_msg = "Failed to change effective user ID. Unset btop SUID bit to ensure security on this system. Quitting!"; - clean_quit(1); - } - } - - Cli::Cli cli; - { - // Get the cli options or return with an exit code - auto result = Cli::parse(args); - if (result.has_value()) { - cli = result.value(); - } else { - auto error = result.error(); - if (error != 0) { - Cli::usage(); - Cli::help_hint(); - } - return error; - } - } - - Global::debug = cli.debug; - - { - const auto config_dir = Config::get_config_dir(); - - if (cli.config_file.has_value()) { - Config::conf_file = cli.config_file.value(); - } else if (config_dir.has_value()) { - Config::conf_dir = config_dir.value(); - Config::conf_file = Config::conf_dir / "btop.conf"; - - auto log_file = Config::get_log_file(); - if (log_file.has_value()) { - Logger::init(log_file.value()); - } - - Theme::user_theme_dir = Config::conf_dir / "themes"; - - // If necessary create the user theme directory - std::error_code error; - if (not fs::exists(Theme::user_theme_dir, error) and not fs::create_directories(Theme::user_theme_dir, error)) { - Theme::user_theme_dir.clear(); - Logger::warning("Failed to create user theme directory: {}", error.message()); - } - } - } - - //? Try to find global btop theme path relative to binary path -#ifdef __linux__ - { std::error_code ec; - Global::self_path = fs::read_symlink("/proc/self/exe", ec).remove_filename(); - } -#elif __APPLE__ - { - char buf [PATH_MAX]; - uint32_t bufsize = PATH_MAX; - if(!_NSGetExecutablePath(buf, &bufsize)) - Global::self_path = fs::path(buf).remove_filename(); - } -#elif __NetBSD__ - { - int mib[4]; - char buf[PATH_MAX]; - size_t bufsize = sizeof buf; - - mib[0] = CTL_KERN; - mib[1] = KERN_PROC_ARGS; - mib[2] = getpid(); - mib[3] = KERN_PROC_PATHNAME; - if (sysctl(mib, 4, buf, &bufsize, NULL, 0) == 0) - Global::self_path = fs::path(buf).remove_filename(); - } -#endif - if (std::error_code ec; not Global::self_path.empty()) { - Theme::theme_dir = fs::canonical(Global::self_path / "../share/btop/themes", ec); - if (ec or not fs::is_directory(Theme::theme_dir) or access(Theme::theme_dir.c_str(), R_OK) == -1) Theme::theme_dir.clear(); - } - //? If relative path failed, check two most common absolute paths - if (Theme::theme_dir.empty()) { - for (auto theme_path : {"/usr/local/share/btop/themes", "/usr/share/btop/themes"}) { - if (fs::is_directory(fs::path(theme_path)) and access(theme_path, R_OK) != -1) { - Theme::theme_dir = fs::path(theme_path); - break; - } - } - } - - //? Set custom themes directory from command line if provided - if (cli.themes_dir.has_value()) { - Theme::custom_theme_dir = cli.themes_dir.value(); - Logger::info("Using custom themes directory: {}", Theme::custom_theme_dir.string()); - } - - //? Config init - init_config(cli.low_color, cli.filter); - - //? Try to find and set a UTF-8 locale - if (std::setlocale(LC_ALL, "") != nullptr and not std::string_view { std::setlocale(LC_ALL, "") }.contains(";") - and str_to_upper(s_replace((string)std::setlocale(LC_ALL, ""), "-", "")).ends_with("UTF8")) { - Logger::debug("Using locale {}", std::locale().name()); - } - else { - string found; - bool set_failure{}; - for (const auto loc_env : array{"LANG", "LC_ALL", "LC_CTYPE"}) { - if (std::getenv(loc_env) != nullptr and str_to_upper(s_replace((string)std::getenv(loc_env), "-", "")).ends_with("UTF8")) { - found = std::getenv(loc_env); - if (std::setlocale(LC_ALL, found.c_str()) == nullptr) { - set_failure = true; - Logger::warning("Failed to set locale {} continuing anyway.", found); - } - } - } - if (found.empty()) { - if (setenv("LC_ALL", "", 1) == 0 and setenv("LANG", "", 1) == 0) { - try { - if (const auto loc = std::locale("").name(); not loc.empty() and loc != "*") { - for (auto& l : ssplit(loc, ';')) { - if (str_to_upper(s_replace(l, "-", "")).ends_with("UTF8")) { - found = l.substr(l.find('=') + 1); - if (std::setlocale(LC_ALL, found.c_str()) != nullptr) { - break; - } - } - } - } - } - catch (...) { found.clear(); } - } - } - // - #ifdef __APPLE__ - if (found.empty()) { - CFLocaleRef cflocale = CFLocaleCopyCurrent(); - CFStringRef id_value = (CFStringRef)CFLocaleGetValue(cflocale, kCFLocaleIdentifier); - auto loc_id = CFStringGetCStringPtr(id_value, kCFStringEncodingUTF8); - CFRelease(cflocale); - std::string cur_locale = (loc_id != nullptr ? loc_id : ""); - if (cur_locale.empty()) { - Logger::warning("No UTF-8 locale detected! Some symbols might not display correctly."); - } - else if (std::setlocale(LC_ALL, string(cur_locale + ".UTF-8").c_str()) != nullptr) { - Logger::debug("Setting LC_ALL={}.UTF-8", cur_locale); - } - else if(std::setlocale(LC_ALL, "en_US.UTF-8") != nullptr) { - Logger::debug("Setting LC_ALL=en_US.UTF-8"); - } - else { - Logger::warning("Failed to set macos locale, continuing anyway."); - } - } - #else - if (found.empty() and cli.force_utf) { - Logger::warning("No UTF-8 locale detected! Forcing start with --force-utf argument."); - } else if (found.empty()) { - Global::exit_error_msg = "No UTF-8 locale detected!\nUse --force-utf argument to force start if you're sure your terminal can handle it."; - clean_quit(1); - } - #endif - else if (not set_failure) { - Logger::debug("Setting LC_ALL={}", found); - } - } - - //? Initialize terminal and set options - if (not Term::init()) { - Global::exit_error_msg = "No tty detected!\nbtop++ needs an interactive shell to run."; - clean_quit(1); - } - - if (Term::current_tty != "unknown") { - Logger::info("Running on {}", Term::current_tty); - } - - configure_tty_mode(cli.force_tty); - - //? Check for valid terminal dimensions - { - int t_count = 0; - while (Term::width <= 0 or Term::width > 10000 or Term::height <= 0 or Term::height > 10000) { - sleep_ms(10); - Term::refresh(); - if (++t_count == 100) { - Global::exit_error_msg = "Failed to get size of terminal!"; - clean_quit(1); - } - } - } - - //? Platform dependent init and error check - try { - Shared::init(); - } - catch (const std::exception& e) { - Global::exit_error_msg = fmt::format("Exception in Shared::init() -> {}", e.what()); - clean_quit(1); - } - - if (not Config::set_boxes(Config::getS("shown_boxes"))) { - Config::set_boxes("cpu mem net proc"); - Config::set("shown_boxes", "cpu mem net proc"s); - } - - //? Update list of available themes and generate the selected theme - Theme::updateThemes(); - Theme::setTheme(); - - //? Setup signal handlers for CTRL-C, CTRL-Z, resume and terminal resize - std::atexit(_exit_handler); - std::signal(SIGINT, _signal_handler); - std::signal(SIGTSTP, _signal_handler); - std::signal(SIGCONT, _signal_handler); - std::signal(SIGWINCH, _signal_handler); - std::signal(SIGUSR1, _signal_handler); - std::signal(SIGUSR2, _signal_handler); - // Add crash handlers to restore terminal on crash - std::signal(SIGSEGV, _crash_handler); - std::signal(SIGABRT, _crash_handler); - std::signal(SIGTRAP, _crash_handler); - std::signal(SIGBUS, _crash_handler); - std::signal(SIGILL, _crash_handler); - - sigset_t mask; - sigemptyset(&mask); - sigaddset(&mask, SIGUSR1); - pthread_sigmask(SIG_BLOCK, &mask, &Input::signal_mask); - - if (pthread_create(&Runner::runner_id, nullptr, &Runner::_runner, nullptr) != 0) { - Global::exit_error_msg = "Failed to create _runner thread!"; - clean_quit(1); - } - else { - Global::_runner_started = true; - } - - //? Calculate sizes of all boxes - Config::presetsValid(Config::getS("presets")); - if (cli.preset.has_value()) { - Config::current_preset = min(static_cast(cli.preset.value()), static_cast(Config::preset_list.size() - 1)); - Config::apply_preset(Config::preset_list.at(Config::current_preset.value())); - } - - { - const auto [x, y] = Term::get_min_size(Config::getS("shown_boxes")); - if (Term::height < y or Term::width < x) { - pthread_sigmask(SIG_SETMASK, &Input::signal_mask, &mask); - term_resize(true); - pthread_sigmask(SIG_SETMASK, &mask, nullptr); - Global::resized = false; - } - - } - - Draw::calcSizes(); - - //? Print out box outlines - const bool term_sync = Config::getB("terminal_sync"); - cout << (term_sync ? Term::sync_start : "") << Cpu::box << Mem::box << Net::box << Proc::box << (term_sync ? Term::sync_end : "") << flush; - - - //? ------------------------------------------------ MAIN LOOP ---------------------------------------------------- - - if (cli.updates.has_value()) { - Config::set("update_ms", static_cast(cli.updates.value())); - } - uint64_t update_ms = Config::getI("update_ms"); - auto future_time = time_ms(); - - try { - while (not true not_eq not false) { - //? Check for exceptions in secondary thread and exit with fail signal if true - if (Global::thread_exception) { - clean_quit(1); - } - else if (Global::should_quit) { - clean_quit(0); - } - else if (Global::should_sleep) { - Global::should_sleep = false; - _sleep(); - } - //? Hot reload config from CTRL + R or SIGUSR2 - else if (Global::reload_conf) { - Global::reload_conf = false; - if (Runner::active) Runner::stop(); - Config::unlock(); - init_config(cli.low_color, cli.filter); - Theme::updateThemes(); - Theme::setTheme(); - Draw::banner_gen(0, 0, false, true); - Global::resized = true; - } - - //? Make sure terminal size hasn't changed (in case of SIGWINCH not working properly) - term_resize(Global::resized); - - //? Trigger secondary thread to redraw if terminal has been resized - if (Global::resized) { - Draw::calcSizes(); - Draw::update_clock(true); - Global::resized = false; - if (Menu::active) Menu::process(); - else Runner::run("all", true, true); - atomic_wait_for(Runner::active, true, 1000); - } - - //? Update clock if needed - if (Draw::update_clock() and not Menu::active) { - Runner::run("clock"); - } - - //? Start secondary collect & draw thread at the interval set by config value - if (time_ms() >= future_time and not Global::resized) { - Runner::run("all"); - update_ms = Config::getI("update_ms"); - future_time = time_ms() + update_ms; - } - - //? Loop over input polling and input action processing - for (auto current_time = time_ms(); current_time < future_time; current_time = time_ms()) { - - //? Check for external clock changes and for changes to the update timer - if (std::cmp_not_equal(update_ms, Config::getI("update_ms"))) { - update_ms = Config::getI("update_ms"); - future_time = time_ms() + update_ms; - } - else if (future_time - current_time > update_ms) { - future_time = current_time; - } - //? Poll for input and process any input detected - else if (Input::poll(min((uint64_t)1000, future_time - current_time))) { - if (not Runner::active) Config::unlock(); - - if (Menu::active) Menu::process(Input::get()); - else Input::process(Input::get()); - } - - //? Break the loop at 1000ms intervals or if input polling was interrupted - else break; - - } - - } - } - catch (const std::exception& e) { - Global::exit_error_msg = fmt::format("Exception in main loop -> {}", e.what()); - clean_quit(1); - } - return 0; -} From b80b003a30617df0c42b3f99dbf9b976b1116f92 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:52:16 +0000 Subject: [PATCH 07/60] feat(btop): add embedded main loop for host-driven btop Adds btop_embed_main, an entry point that runs btop's main loop on a host-created thread without argument parsing, controlling terminal or signal handling. It reads config and themes from a host-chosen directory, pauses drawing while the host hides the view, and unwinds cleanly when the host requests a stop. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop.cpp | 159 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) diff --git a/vendor/btop/src/btop.cpp b/vendor/btop/src/btop.cpp index 814098c85..7566166b0 100644 --- a/vendor/btop/src/btop.cpp +++ b/vendor/btop/src/btop.cpp @@ -702,3 +702,162 @@ namespace Runner { } + +//* Find a UTF-8 LC_CTYPE. btop measures glyph widths with mbstowcs, which needs +//* one; only LC_CTYPE is touched because the host process shares the locale. +static void embed_set_ctype() { + for (const char* candidate : {"", "C.UTF-8", "en_US.UTF-8"}) { + if (const char* set = std::setlocale(LC_CTYPE, candidate); set != nullptr) { + if (str_to_upper(s_replace(string{set}, "-", "")).ends_with("UTF8")) return; + } + } + Logger::warning("No UTF-8 LC_CTYPE available; some glyphs may be measured wrongly."); +} + +//* Wait for the host to make btop visible again, then force a full redraw. +static void embed_pause() { + if (Runner::active) Runner::stop(); + Embed::wait_visible(); + Global::resized = true; +} + +//* --------------------------------------- Embedded main (Medulla) --------------------------------------------------- +//* Upstream btop_main(), minus argument parsing, the controlling terminal and +//* signal handling. Runs on the thread medulla_btop_start() creates and returns +//* once Embed::stopping(); fatal errors unwind as Embed::Fatal. +auto btop_embed_main() -> void { + Global::start_time = time_s(); + Global::real_uid = getuid(); + Global::set_uid = geteuid(); + + //? Config, log and user themes all live under the host-chosen directory + Config::conf_dir = Embed::config_dir(); + { + std::error_code error; + fs::create_directories(Config::conf_dir, error); + } + Config::conf_file = Config::conf_dir / "btop.conf"; + Logger::init(Config::conf_dir / "btop.log"); + Theme::user_theme_dir = Config::conf_dir / "themes"; + { + std::error_code error; + if (not fs::exists(Theme::user_theme_dir, error) and not fs::create_directories(Theme::user_theme_dir, error)) + Theme::user_theme_dir.clear(); + } + for (auto theme_path : {"/usr/local/share/btop/themes", "/usr/share/btop/themes", "/opt/homebrew/share/btop/themes"}) { + if (fs::is_directory(fs::path(theme_path)) and access(theme_path, R_OK) != -1) { + Theme::theme_dir = fs::path(theme_path); + break; + } + } + + std::optional no_filter; + init_config(false, no_filter); + embed_set_ctype(); + + Term::init(); + Config::set("tty_mode", Config::getB("force_tty")); + + Shared::init(); + + if (not Config::set_boxes(Config::getS("shown_boxes"))) { + Config::set_boxes("cpu mem net proc"); + Config::set("shown_boxes", "cpu mem net proc"s); + } + + Theme::updateThemes(); + Theme::setTheme(); + + if (pthread_create(&Runner::runner_id, nullptr, &Runner::_runner, nullptr) != 0) { + throw Embed::Fatal{"Failed to create btop's runner thread"}; + } + Global::_runner_started = true; + + //? Stop the runner thread however this function is left + struct runner_guard { + ~runner_guard() { + Global::quitting = true; + Runner::stopping = true; + Runner::thread_trigger(); + if (Config::getB("save_config_on_exit")) { + try { Config::write(); } catch (...) {} + } + } + } guard; + + Config::presetsValid(Config::getS("presets")); + Draw::calcSizes(); + Global::resized = true; + + uint64_t update_ms = Config::getI("update_ms"); + auto future_time = time_ms(); + + try { + while (not Embed::stopping()) { + if (Global::thread_exception) { + clean_quit(1); + } + if (not Embed::visible()) { + embed_pause(); + continue; + } + //? Hot reload config from CTRL + R + if (Global::reload_conf) { + Global::reload_conf = false; + if (Runner::active) Runner::stop(); + Config::unlock(); + init_config(false, no_filter); + Theme::updateThemes(); + Theme::setTheme(); + Draw::banner_gen(0, 0, false, true); + Global::resized = true; + } + + //? Pick up a host-reported resize + term_resize(Global::resized); + if (Embed::stopping()) break; + + if (Global::resized) { + Draw::calcSizes(); + Draw::update_clock(true); + Global::resized = false; + if (Menu::active) Menu::process(); + else Runner::run("all", true, true); + atomic_wait_for(Runner::active, true, 1000); + } + + if (Draw::update_clock() and not Menu::active) { + Runner::run("clock"); + } + + if (time_ms() >= future_time and not Global::resized) { + Runner::run("all"); + update_ms = Config::getI("update_ms"); + future_time = time_ms() + update_ms; + } + + for (auto current_time = time_ms(); current_time < future_time; current_time = time_ms()) { + if (std::cmp_not_equal(update_ms, Config::getI("update_ms"))) { + update_ms = Config::getI("update_ms"); + future_time = time_ms() + update_ms; + } + else if (future_time - current_time > update_ms) { + future_time = current_time; + } + else if (Input::poll(min((uint64_t)1000, future_time - current_time))) { + if (not Runner::active) Config::unlock(); + + if (Menu::active) Menu::process(Input::get()); + else Input::process(Input::get()); + } + //? Interrupted (resize, visibility, stop) or 1s elapsed + else break; + } + } + } + catch (const std::exception& e) { + Global::exit_error_msg = fmt::format("Exception in main loop -> {}", e.what()); + clean_quit(1); + } + if (Runner::active) Runner::stop(); +} From 9283ba0db42f0a0304406cefa7b9bccd42073bee Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:52:57 +0000 Subject: [PATCH 08/60] feat(embed): route terminal I/O through embed host hooks Replace direct terminal writes, stdin polling, and signal-based interrupts with Embed calls so btop can run as an embedded pane driven by a host process. Quit requests now go through Embed::request_leave instead of exiting directly, letting the host decide when to tear down the session. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop.cpp | 14 +++--- vendor/btop/src/btop_input.cpp | 33 +++---------- vendor/btop/src/btop_menu.cpp | 6 ++- vendor/btop/src/btop_tools.cpp | 89 ++++++---------------------------- 4 files changed, 33 insertions(+), 109 deletions(-) diff --git a/vendor/btop/src/btop.cpp b/vendor/btop/src/btop.cpp index 7566166b0..5d5ef34b1 100644 --- a/vendor/btop/src/btop.cpp +++ b/vendor/btop/src/btop.cpp @@ -160,7 +160,7 @@ void term_resize(bool force) { sleep_ms(100); if (Term::width < minWidth or Term::height < minHeight) { int width = Term::width, height = Term::height; - cout << fmt::format("{clear}{fg_white}" + Embed::write(fmt::format("{clear}{fg_white}" "{mv1}Terminal size too small:" "{mv2} Width = {fg_width}{width} {fg_white}Height = {fg_height}{height}" "{mv3}{fg_white}Needed for current config:" @@ -176,14 +176,14 @@ void term_resize(bool force) { "mv4"_a = Mv::to((height / 2) + 2, (width / 2) - 10), "minWidth"_a = minWidth, "minHeight"_a = minHeight - ) << std::flush; + )); bool got_key = false; for (; not Term::refresh() and not got_key; got_key = Input::poll(10)); if (got_key) { auto key = Input::get(); if (key == "q") - clean_quit(0); + Embed::request_leave(); else if (key.size() == 1 and isint(key)) { auto intKey = stoi(key); #ifdef GPU_SUPPORT @@ -618,10 +618,10 @@ namespace Runner { //? If overlay isn't empty, print output without color and then print overlay on top const bool term_sync = Config::getB("terminal_sync"); - cout << (term_sync ? Term::sync_start : "") << (conf.overlay.empty() + Embed::write((term_sync ? Term::sync_start : "") + (conf.overlay.empty() ? output : (output.empty() ? "" : Fx::ub + Theme::c("inactive_fg") + Fx::uncolor(output)) + conf.overlay) - << (term_sync ? Term::sync_end : "") << flush; + + (term_sync ? Term::sync_end : "")); } //* ----------------------------------------------- THREAD LOOP ----------------------------------------------- return {}; @@ -643,11 +643,11 @@ namespace Runner { if (box == "overlay") { const bool term_sync = Config::getB("terminal_sync"); - cout << (term_sync ? Term::sync_start : "") << Global::overlay << (term_sync ? Term::sync_end : "") << flush; + Embed::write((term_sync ? Term::sync_start : "") + Global::overlay + (term_sync ? Term::sync_end : "")); } else if (box == "clock") { const bool term_sync = Config::getB("terminal_sync"); - cout << (term_sync ? Term::sync_start : "") << Global::clock << (term_sync ? Term::sync_end : "") << flush; + Embed::write((term_sync ? Term::sync_start : "") + Global::clock + (term_sync ? Term::sync_end : "")); } else { Config::unlock(); diff --git a/vendor/btop/src/btop_input.cpp b/vendor/btop/src/btop_input.cpp index 4c77b718a..a18186b48 100644 --- a/vendor/btop/src/btop_input.cpp +++ b/vendor/btop/src/btop_input.cpp @@ -29,6 +29,7 @@ tab-size = 4 #include "btop_input.hpp" #include "btop_tools.hpp" +#include "btop_embed.hpp" #include "btop_config.hpp" #include "btop_shared.hpp" #include "btop_menu.hpp" @@ -92,32 +93,11 @@ namespace Input { string old_filter; string input; + //* Medulla: input arrives as one chunk per key or mouse event from the host. bool poll(const uint64_t timeout) { atomic_lock lck(polling); - fd_set fds; - FD_ZERO(&fds); - FD_SET(STDIN_FILENO, &fds); - struct timespec wait; - struct timespec *waitptr = nullptr; - - if(timeout != std::numeric_limits::max()) { - wait.tv_sec = timeout / 1000; - wait.tv_nsec = (timeout % 1000) * 1000000; - waitptr = &wait; - } - - if(pselect(STDIN_FILENO + 1, &fds, nullptr, nullptr, waitptr, &signal_mask) > 0) { - input.clear(); - char buf[1024]; - ssize_t count = 0; - while((count = read(STDIN_FILENO, buf, sizeof(buf))) > 0) { - input.append(std::string_view(buf, count)); - } - - return true; - } - - return false; + input.clear(); + return Embed::wait_input(timeout, input); } string get() { @@ -204,7 +184,7 @@ namespace Input { } void interrupt() { - kill(getpid(), SIGUSR1); + Embed::interrupt(); } void clear() { @@ -222,7 +202,8 @@ namespace Input { if (not filtering) { bool keep_going = false; if (key == "q") { - clean_quit(0); + Embed::request_leave(); + return; } else if (is_in(key, "escape", "m")) { Menu::show(Menu::Menus::Main); diff --git a/vendor/btop/src/btop_menu.cpp b/vendor/btop/src/btop_menu.cpp index bcb64bf7b..29a13759e 100644 --- a/vendor/btop/src/btop_menu.cpp +++ b/vendor/btop/src/btop_menu.cpp @@ -24,6 +24,7 @@ tab-size = 4 #include "btop_shared.hpp" #include "btop_theme.hpp" #include "btop_tools.hpp" +#include "btop_embed.hpp" #include #include @@ -1263,7 +1264,8 @@ namespace Menu { currentMenu = Menus::Help; return Switch; case Quit: - clean_quit(0); + Embed::request_leave(); + return Closed; } } else if (is_in(key, "down", "tab", "mouse_scroll_down", "j")) { @@ -1526,7 +1528,7 @@ static int optionsMenu(const string& key) { } else if (option == "disable_mouse") { const auto is_mouse_enabled = !Config::getB("disable_mouse"); - std::cout << (is_mouse_enabled ? Term::mouse_on : Term::mouse_off) << std::flush; + Embed::write(is_mouse_enabled ? Term::mouse_on : Term::mouse_off); } } else if (selPred.test(isBrowsable)) { diff --git a/vendor/btop/src/btop_tools.cpp b/vendor/btop/src/btop_tools.cpp index f0e0de63e..113589605 100644 --- a/vendor/btop/src/btop_tools.cpp +++ b/vendor/btop/src/btop_tools.cpp @@ -36,6 +36,7 @@ tab-size = 4 #include "btop_log.hpp" #include "btop_shared.hpp" #include "btop_tools.hpp" +#include "btop_embed.hpp" #include "btop_config.hpp" using std::cout; @@ -59,57 +60,14 @@ namespace Term { atomic height{}; string current_tty; - namespace { - struct termios initial_settings; - - //* Toggle terminal input echo - bool echo(bool on=true) { - struct termios settings; - if (tcgetattr(STDIN_FILENO, &settings)) return false; - if (on) settings.c_lflag |= ECHO; - else settings.c_lflag &= ~(ECHO); - return 0 == tcsetattr(STDIN_FILENO, TCSANOW, &settings); - } - - //* Toggle need for return key when reading input - bool linebuffered(bool on=true) { - struct termios settings; - if (tcgetattr(STDIN_FILENO, &settings)) return false; - if (on) settings.c_lflag |= ICANON; - else { - settings.c_lflag &= ~(ICANON); - settings.c_cc[VMIN] = 0; - settings.c_cc[VTIME] = 0; - } - if (tcsetattr(STDIN_FILENO, TCSANOW, &settings)) return false; - if (on) setlinebuf(stdin); - else setbuf(stdin, nullptr); - return true; - } - } - + //* Medulla: the "terminal" is the host's view, sized by medulla_btop_resize(). bool refresh(bool only_check) { - // Query dimensions of '/dev/tty' of the 'STDOUT_FILENO' isn't available. - // This variable is set in those cases to avoid calls to ioctl - constinit static bool uses_dev_tty = false; - struct winsize wsize {}; - if (uses_dev_tty || ioctl(STDOUT_FILENO, TIOCGWINSZ, &wsize) < 0 || (wsize.ws_col == 0 && wsize.ws_row == 0)) { - Logger::error(R"(Couldn't determine terminal size of "STDOUT_FILENO"!)"); - auto dev_tty = open("/dev/tty", O_RDONLY | O_CLOEXEC); - if (dev_tty != -1) { - ioctl(dev_tty, TIOCGWINSZ, &wsize); - close(dev_tty); - } - else { - Logger::error(R"(Couldn't determine terminal size of "/dev/tty"!)"); - return false; - } - uses_dev_tty = true; - } - if (width != wsize.ws_col or height != wsize.ws_row) { + const int w = Embed::width(), h = Embed::height(); + if (w <= 0 or h <= 0) return false; + if (width != w or height != h) { if (not only_check) { - width = wsize.ws_col; - height = wsize.ws_row; + width = w; + height = h; } return true; } @@ -147,38 +105,21 @@ namespace Term { return { width, height }; } + //* Medulla: no tty to configure; the host parses output with its own emulator. bool init() { if (not initialized) { - initialized = (bool)isatty(STDIN_FILENO); - if (initialized) { - tcgetattr(STDIN_FILENO, &initial_settings); - current_tty = (ttyname(STDIN_FILENO) != nullptr ? static_cast(ttyname(STDIN_FILENO)) : "unknown"); - - //? Disable stream sync - this does not seem to work on OpenBSD -#ifndef __OpenBSD__ - cout.sync_with_stdio(false); -#endif - - //? Disable stream ties - cout.tie(nullptr); - echo(false); - linebuffered(false); - refresh(); - - const auto is_mouse_enabled = !Config::getB("disable_mouse"); - cout << alt_screen << hide_cursor << (is_mouse_enabled ? mouse_on : mouse_off) << flush; - Global::resized = false; - } + initialized = true; + current_tty = "medulla"; + refresh(); + const auto is_mouse_enabled = !Config::getB("disable_mouse"); + Embed::write(hide_cursor + (is_mouse_enabled ? mouse_on : mouse_off)); + Global::resized = false; } return initialized; } void restore() { - if (initialized) { - tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings); - cout << mouse_off << clear << Fx::reset << normal_screen << show_cursor << flush; - initialized = false; - } + initialized = false; } } From e7d40154b18dd9581fec7ff150512adcde834c4f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:53:06 +0000 Subject: [PATCH 09/60] fix(btop): avoid blocking resize loop and signal-based reload The terminal resize loop now exits early when the embedded instance is stopping or hidden, preventing it from spinning while the UI is not visible. The ctrl_r reload shortcut sets the reload flag directly instead of raising SIGUSR2, so reloads no longer depend on signal handling. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop.cpp | 1 + vendor/btop/src/btop_input.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/vendor/btop/src/btop.cpp b/vendor/btop/src/btop.cpp index 5d5ef34b1..bd230ddce 100644 --- a/vendor/btop/src/btop.cpp +++ b/vendor/btop/src/btop.cpp @@ -157,6 +157,7 @@ void term_resize(bool force) { auto minWidth = min_size.at(0), minHeight = min_size.at(1); while (not force or (Term::width < minWidth or Term::height < minHeight)) { + if (Embed::stopping() or not Embed::visible()) break; sleep_ms(100); if (Term::width < minWidth or Term::height < minHeight) { int width = Term::width, height = Term::height; diff --git a/vendor/btop/src/btop_input.cpp b/vendor/btop/src/btop_input.cpp index a18186b48..cc5b01711 100644 --- a/vendor/btop/src/btop_input.cpp +++ b/vendor/btop/src/btop_input.cpp @@ -264,7 +264,7 @@ namespace Input { Runner::run("all", false, true); return; } else if (is_in(key, "ctrl_r")) { - kill(getpid(), SIGUSR2); + Global::reload_conf = true; return; } else if (key == "mouse_release") { dragging_scroll = false; From 8b878be0268d1109b4bff701ea605acc54d89d9d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:53:12 +0000 Subject: [PATCH 10/60] chore(vendor): add reload_conf flag to btop globals Declare an atomic reload_conf flag alongside init_conf in the Global namespace so configuration reloads can be signalled across threads. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_shared.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/vendor/btop/src/btop_shared.hpp b/vendor/btop/src/btop_shared.hpp index 0abd18c60..898858f24 100644 --- a/vendor/btop/src/btop_shared.hpp +++ b/vendor/btop/src/btop_shared.hpp @@ -72,6 +72,7 @@ namespace Global { extern string clock; extern uid_t real_uid, set_uid; extern atomic init_conf; + extern atomic reload_conf; } namespace Runner { From fa4c9eb879e8555d68a0f4f152c605a5c94840b4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:53:29 +0000 Subject: [PATCH 11/60] chore(vendor): remove unused btop cli sources Delete the vendored btop command-line parser implementation and header, which are no longer referenced by the build. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_cli.cpp | 272 ----------------------------------- vendor/btop/src/btop_cli.hpp | 53 ------- 2 files changed, 325 deletions(-) delete mode 100644 vendor/btop/src/btop_cli.cpp delete mode 100644 vendor/btop/src/btop_cli.hpp diff --git a/vendor/btop/src/btop_cli.cpp b/vendor/btop/src/btop_cli.cpp deleted file mode 100644 index a5f7f7cb5..000000000 --- a/vendor/btop/src/btop_cli.cpp +++ /dev/null @@ -1,272 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -#include "btop_cli.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include - -#include "btop_config.hpp" -#include "btop_shared.hpp" -#include "config.h" - -using namespace std::string_view_literals; - -static constexpr auto BOLD = "\033[1m"sv; -static constexpr auto BOLD_UNDERLINE = "\033[1;4m"sv; -static constexpr auto BOLD_RED = "\033[1;31m"sv; -static constexpr auto BOLD_GREEN = "\033[1;32m"sv; -static constexpr auto BOLD_YELLOW = "\033[1;33m"sv; -static constexpr auto BOLD_BRIGHT_BLACK = "\033[1;90m"sv; -static constexpr auto YELLOW = "\033[33m"sv; -static constexpr auto RESET = "\033[0m"sv; - -static void version() noexcept { - if constexpr (GIT_COMMIT.empty()) { - fmt::println("btop version: {}{}{}", BOLD, Global::Version, RESET); - } else { - fmt::println("btop version: {}{}+{}{}", BOLD, Global::Version, GIT_COMMIT, RESET); - } -} - -static void build_info() noexcept { - fmt::println("Compiled with: {} ({})", COMPILER, COMPILER_VERSION); - fmt::println("Configured with: {}", CONFIGURE_COMMAND); -} - -static void error(std::string_view msg) noexcept { - fmt::println("{}error:{} {}\n", BOLD_RED, RESET, msg); -} - -namespace Cli { - [[nodiscard]] auto parse(const std::span args) noexcept -> Result { - Cli cli {}; - - for (auto it = args.begin(); it != args.end(); ++it) { - auto arg = *it; - - if (arg == "--default-config") { - return default_config(); - } - if (arg == "-h" || arg == "--help") { - usage(); - help(); - return std::unexpected { 0 }; - } - if (arg == "-v" || arg == "-V") { - version(); - return std::unexpected { 0 }; - } - if (arg == "--version") { - version(); - build_info(); - return std::unexpected { 0 }; - } - - if (arg == "-d" || arg == "--debug") { - cli.debug = true; - continue; - } - if (arg == "--force-utf") { - cli.force_utf = true; - continue; - } - if (arg == "-l" || arg == "--low-color") { - cli.low_color = true; - continue; - } - if (arg == "-t" || arg == "--tty") { - if (cli.force_tty.has_value()) { - error("tty mode can't be set twice"); - return std::unexpected { 1 }; - } - cli.force_tty = std::make_optional(true); - continue; - } - if (arg == "--no-tty") { - if (cli.force_tty.has_value()) { - error("tty mode can't be set twice"); - return std::unexpected { 1 }; - } - cli.force_tty = std::make_optional(false); - continue; - } - - if (arg == "-c" || arg == "--config") { - // This flag requires an argument. - if (++it == args.end()) { - error("Config requires an argument"); - return std::unexpected { 1 }; - } - - auto arg = *it; - auto config_file = stdfs::path { arg }; - - if (stdfs::is_directory(config_file)) { - error("Config file can't be a directory"); - return std::unexpected { 1 }; - } - - cli.config_file = std::make_optional(config_file); - continue; - } - if (arg == "-f" || arg == "--filter") { - // This flag requires an argument. - if (++it == args.end()) { - error("Filter requires an argument"); - return std::unexpected { 1 }; - } - - auto arg = *it; - cli.filter = std::make_optional(arg); - continue; - } - if (arg == "-p" || arg == "--preset") { - // This flag requires an argument. - if (++it == args.end()) { - error("Preset requires an argument"); - return std::unexpected { 1 }; - } - - auto arg = *it; - try { - auto preset_id = std::clamp(std::stoi(arg.data()), 0, 9); - cli.preset = std::make_optional(preset_id); - } catch (std::invalid_argument& e) { - error("Preset must be a positive number"); - return std::unexpected { 1 }; - } catch (std::out_of_range& e) { - error(fmt::format("Preset argument is out of range: {}", arg.data())); - return std::unexpected { 1 }; - } - continue; - } - if (arg == "--themes-dir") { - // This flag requires an argument. - if (++it == args.end()) { - error("Themes directory requires an argument"); - return std::unexpected { 1 }; - } - - auto arg = *it; - auto themes_dir = stdfs::path { arg }; - - if (not stdfs::is_directory(themes_dir)) { - error("Themes directory does not exist or is not a directory"); - return std::unexpected { 1 }; - } - - cli.themes_dir = std::make_optional(themes_dir); - continue; - } - if (arg == "-u" || arg == "--update") { - // This flag requires an argument. - if (++it == args.end()) { - error("Update requires an argument"); - return std::unexpected { 1 }; - } - - auto arg = *it; - try { - auto refresh_rate = std::max(std::stoi(arg.data()), 100); - cli.updates = refresh_rate; - } catch (std::invalid_argument& e) { - error("Update must be a positive number"); - return std::unexpected { 1 }; - } catch (std::out_of_range& e) { - error(fmt::format("Update argument is out of range: {}", arg.data())); - return std::unexpected { 1 }; - } - continue; - } - - error(fmt::format("Unknown argument '{}{}{}'", YELLOW, arg, RESET)); - return std::unexpected { 1 }; - } - return cli; - } - - auto default_config() noexcept -> Result { - // The idea of using `current_config` is that the CLI parser is run before loading the actual config and thus - // provides default values. - auto config = Config::current_config(); - - if (isatty(STDOUT_FILENO)) { - std::string buffer {}; - // The config buffer ends in `\n`. `std::views::split` will then create an empty element after the last - // newline, which we would write as an additional empty line at the very end. - auto trimmed_config = config.substr(0, config.length() - 1); - for (const auto line : std::views::split(trimmed_config, '\n')) { - auto line_view = std::string_view { line }; - if (line_view.starts_with("#")) { - fmt::format_to( - std::back_inserter(buffer), "{1}{0}{2}\n", line_view, BOLD_BRIGHT_BLACK, RESET - ); - } else if (!line_view.empty()) { - auto pos = line_view.find("="); - if (pos == line_view.npos) { - error("invalid default config: '=' not found"); - return std::unexpected { 1 }; - } - auto name = line_view.substr(0, pos); - auto value = line_view.substr(pos + 1); - fmt::format_to( - std::back_inserter(buffer), - "{2}{0}{4}={3}{1}{4}\n", - name, - value, - BOLD_YELLOW, - BOLD_GREEN, - RESET - ); - } else { - fmt::format_to(std::back_inserter(buffer), "\n"); - } - } - fmt::print("{}", buffer); - } else { - fmt::print("{}", config); - } - return std::unexpected { 0 }; - } - - void usage() noexcept { - fmt::println("{0}Usage:{1} {2}btop{1} [OPTIONS]\n", BOLD_UNDERLINE, RESET, BOLD); - } - - void help() noexcept { - fmt::print( - "{0}Options:{1}\n" - " {2}-c, --config{1} Path to a config file\n" - " {2}-d, --debug{1} Start in debug mode with additional logs and metrics\n" - " {2}-f, --filter{1} Set an initial process filter\n" - " {2} --force-utf{1} Override automatic UTF locale detection\n" - " {2}-l, --low-color{1} Disable true color, 256 colors only\n" - " {2}-p, --preset{1} Start with a preset (0-9)\n" - " {2}-t, --tty{1} Force tty mode with ANSI graph symbols and 16 colors only\n" - " {2} --themes-dir{1} Path to a custom themes directory\n" - " {2} --no-tty{1} Force disable tty mode\n" - " {2}-u, --update{1} Set an initial update rate in milliseconds\n" - " {2} --default-config{1} Print default config to standard output\n" - " {2}-h, --help{1} Show this help message and exit\n" - " {2}-V, --version{1} Show a version message and exit (more with --version)\n", - BOLD_UNDERLINE, RESET, BOLD - ); - } - - void help_hint() noexcept { - fmt::println("For more information, try '{}--help{}'", BOLD, RESET); - } -} // namespace Cli diff --git a/vendor/btop/src/btop_cli.hpp b/vendor/btop/src/btop_cli.hpp deleted file mode 100644 index 69e1f9dbd..000000000 --- a/vendor/btop/src/btop_cli.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace Cli { - namespace stdfs = std::filesystem; - - // Configuration options set via the command line. - struct Cli { - // Alternate path to a configuration file - std::optional config_file; - // Enable debug mode with additional logs and metrics - bool debug {}; - // Set an initial process filter. - std::optional filter; - // Only use ANSI supported graph symbols and colors - std::optional force_tty; - // Use UTF-8 locale even if not detected - bool force_utf {}; - // Disable true color and only use 256 color mode - bool low_color {}; - // Start with one of the provided presets - std::optional preset; - // Path to a custom themes directory - std::optional themes_dir; - // The initial refresh rate - std::optional updates; - }; - - using Result = std::expected; - - // Parse the command line arguments - [[nodiscard]] auto parse(std::span args) noexcept -> Result; - - // Print default config to standard output - [[nodiscard]] auto default_config() noexcept -> Result; - - // Print a usage header - void usage() noexcept; - - // Print a help message - void help() noexcept; - - // Print a hint on how to show more help - void help_hint() noexcept; -} // namespace Cli From adf06105da1b79abaa65608ffc799258e837882a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:53:34 +0000 Subject: [PATCH 12/60] chore(vendor): drop unused btop_cli include from btop.cpp Removed the btop_cli.hpp include from the vendored btop source since nothing in the file references it, keeping the vendored tree free of a stale dependency. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/vendor/btop/src/btop.cpp b/vendor/btop/src/btop.cpp index bd230ddce..5db1d75a6 100644 --- a/vendor/btop/src/btop.cpp +++ b/vendor/btop/src/btop.cpp @@ -60,7 +60,6 @@ tab-size = 4 #include #include -#include "btop_cli.hpp" #include "btop_config.hpp" #include "btop_draw.hpp" #include "btop_input.hpp" From c1de8cf6d14bb7d7eba79c6eb54f0aece18b7cf4 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:53:46 +0000 Subject: [PATCH 13/60] build: add src/btop to workspace members Register the new btop crate as a workspace member so it is built and tested alongside the existing crates. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.toml | 2 +- src/btop/Cargo.toml | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 src/btop/Cargo.toml diff --git a/Cargo.toml b/Cargo.toml index 41a5cb054..b2bc65fb0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["src/link", "src/sdk", "src/tui"] +members = ["src/btop", "src/link", "src/sdk", "src/tui"] # Vendored path deps must not become workspace members: they carry their own # lints/tests and would otherwise fall under the CI clippy/test gates. # diff --git a/src/btop/Cargo.toml b/src/btop/Cargo.toml new file mode 100644 index 000000000..9c003ccad --- /dev/null +++ b/src/btop/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "medulla-btop" +description = "btop, compiled in: the vendored C++ system monitor behind a safe embedding API" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +# Compiles `vendor/btop`, which lives outside this package directory. +build = "build.rs" +links = "medulla_btop" + +[lib] +name = "medulla_btop" +path = "src/lib.rs" + +[dependencies] +thiserror = { workspace = true } + +[build-dependencies] +cc = "1" From 2a8e44a7acfbf25efcea43e7bbdabef3755bae99 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:53:51 +0000 Subject: [PATCH 14/60] feat(tui): add medulla-btop dependency for the Resources tab Wire the vendored btop crate into the workspace and the TUI so the host Resources tab can drive it through its C ABI. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.toml | 3 +++ src/tui/Cargo.toml | 2 ++ 2 files changed, 5 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index b2bc65fb0..c6c641f37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,9 @@ medulla = { path = "src/sdk", default-features = false } # The host-link transport (docs/host-link-protocol.md). A plain path dep: it is # ours, has no registry coordinate, and is not vendored. medulla-link = { path = "src/link" } +# btop, compiled in from `vendor/btop` and driven through a C ABI; the host +# Resources tab is this crate's only consumer. +medulla-btop = { path = "src/btop" } # The agent harness lives in the split `tinyagents-harness` package inside the # direct `tinyagents` submodule. Keep the dependency key as `tinyagents` so the # host code can migrate independently of the upstream package rename. diff --git a/src/tui/Cargo.toml b/src/tui/Cargo.toml index 456b80795..339fe9660 100644 --- a/src/tui/Cargo.toml +++ b/src/tui/Cargo.toml @@ -30,6 +30,8 @@ medulla = { workspace = true, default-features = false } # The host-link transport: `main.rs` brings the link up before handing the # worker loop a bridge over it. medulla-link = { workspace = true } +# The Resources tab: btop itself, compiled in. +medulla-btop = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } regex = { workspace = true } From e3da517a05c02b6b18a99eb10ed1a4fab32c8761 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:54:06 +0000 Subject: [PATCH 15/60] feat(btop): add build script for btop integration Add a build script that compiles the btop sources and wires up the native build so the integration can be built as part of the crate. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/btop/build.rs | 100 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 src/btop/build.rs diff --git a/src/btop/build.rs b/src/btop/build.rs new file mode 100644 index 000000000..e06355e46 --- /dev/null +++ b/src/btop/build.rs @@ -0,0 +1,100 @@ +//! Compiles the vendored btop (`vendor/btop`) into a static library. +//! +//! btop is C++23 and has collectors only for Linux, macOS and the BSDs. On any +//! other target nothing is compiled and the crate is built with +//! `cfg(medulla_btop_unsupported)`, under which [`Btop::start`] reports +//! `Unsupported` instead of linking. +//! +//! [`Btop::start`]: ../src/lib.rs + +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Sources shared by every platform, relative to `vendor/btop/src`. +const SHARED: [&str; 10] = [ + "btop.cpp", + "btop_config.cpp", + "btop_draw.cpp", + "btop_embed.cpp", + "btop_input.cpp", + "btop_log.cpp", + "btop_menu.cpp", + "btop_shared.cpp", + "btop_theme.cpp", + "btop_tools.cpp", +]; + +fn main() { + println!("cargo::rustc-check-cfg=cfg(medulla_btop_unsupported)"); + println!("cargo:rerun-if-env-changed=CXX"); + + let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("manifest dir")) + .join("../../vendor/btop"); + let src = root.join("src"); + let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + + let platform: &[&str] = match target_os.as_str() { + "linux" => &["linux/btop_collect.cpp"], + "macos" => &["osx/btop_collect.cpp", "osx/sensors.cpp", "osx/smc.cpp"], + _ => { + println!("cargo:rustc-cfg=medulla_btop_unsupported"); + return; + } + }; + + let mut build = cc::Build::new(); + build + .cpp(true) + .std("c++23") + .include(root.join("include")) + .include(&src) + .define("FMT_HEADER_ONLY", None) + .define("_FILE_OFFSET_BITS", "64") + // Upstream's own build is -Wall -Wextra; its warnings are not ours to fix. + .warnings(false) + .flag_if_supported("-Wno-deprecated-declarations"); + if target_os == "linux" && std::env::var_os("CXX").is_none() { + if let Some(compiler) = modern_gxx() { + build.compiler(compiler); + } + } + for file in SHARED.iter().chain(platform) { + let path = src.join(file); + println!("cargo:rerun-if-changed={}", path.display()); + build.file(path); + } + for header in watched_headers(&src).into_iter().chain([root.join("include/medulla_btop.h")]) { + println!("cargo:rerun-if-changed={}", header.display()); + } + build.compile("medulla_btop"); + + if target_os == "macos" { + println!("cargo:rustc-link-lib=framework=CoreFoundation"); + println!("cargo:rustc-link-lib=framework=IOKit"); + } +} + +/// btop needs `std::ranges::to` and `std::expected`, which libstdc++ ships from +/// GCC 14. Ubuntu 24.04's default `g++` is 13 with `g++-14` installed beside +/// it, so prefer a versioned compiler when the default is too old. +fn modern_gxx() -> Option<&'static str> { + let major = |cmd: &str| -> Option { + let out = Command::new(cmd).arg("-dumpversion").output().ok()?; + String::from_utf8(out.stdout).ok()?.trim().split('.').next()?.parse().ok() + }; + if major("g++").is_some_and(|v| v >= 14) { + return None; + } + ["g++-15", "g++-14"].into_iter().find(|cmd| major(cmd).is_some()) +} + +/// Headers whose edits must rebuild the library. +fn watched_headers(src: &Path) -> Vec { + std::fs::read_dir(src) + .into_iter() + .flatten() + .flatten() + .map(|entry| entry.path()) + .filter(|path| path.extension().is_some_and(|ext| ext == "hpp")) + .collect() +} From 6957b3e0f15539de03ecdf5261018ac427115f1e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:54:12 +0000 Subject: [PATCH 16/60] docs(btop): replace intra-doc link with plain code reference The build script's module docs referenced `Btop::start` via an intra-doc link, which cannot resolve from a build script and would warn during doc builds. The reference is now plain code text, and the trailing link definition was dropped. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/btop/build.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/btop/build.rs b/src/btop/build.rs index e06355e46..76c385d7b 100644 --- a/src/btop/build.rs +++ b/src/btop/build.rs @@ -2,10 +2,8 @@ //! //! btop is C++23 and has collectors only for Linux, macOS and the BSDs. On any //! other target nothing is compiled and the crate is built with -//! `cfg(medulla_btop_unsupported)`, under which [`Btop::start`] reports +//! `cfg(medulla_btop_unsupported)`, under which `Btop::start` reports //! `Unsupported` instead of linking. -//! -//! [`Btop::start`]: ../src/lib.rs use std::path::{Path, PathBuf}; use std::process::Command; From a681d9a6f2f0ce837686ec53e87ab31e85921790 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:54:29 +0000 Subject: [PATCH 17/60] feat(btop): add Rust FFI bindings for btop types and library Introduce a new Rust crate exposing FFI bindings so btop's types and core library can be consumed from Rust. This provides the foundation for integrating btop functionality into Rust-based tooling. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/btop/src/ffi.rs | 33 +++++++++++++++++++++++++++++++++ src/btop/src/lib.rs | 32 ++++++++++++++++++++++++++++++++ src/btop/src/types.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 94 insertions(+) create mode 100644 src/btop/src/ffi.rs create mode 100644 src/btop/src/lib.rs create mode 100644 src/btop/src/types.rs diff --git a/src/btop/src/ffi.rs b/src/btop/src/ffi.rs new file mode 100644 index 000000000..644a4446d --- /dev/null +++ b/src/btop/src/ffi.rs @@ -0,0 +1,33 @@ +//! Raw bindings to `vendor/btop/include/medulla_btop.h`. Every call is +//! thread-safe on the C++ side; [`crate::Btop`] is the only caller. + +use std::ffi::{c_char, c_int, c_void}; + +/// Mirrors `medulla_btop_agent`. +#[repr(C)] +pub struct RawAgent { + pub pid: u32, + pub label: *const c_char, + pub launched: u8, +} + +pub type Waker = extern "C" fn(ctx: *mut c_void); +pub type Sink = extern "C" fn(ctx: *mut c_void, bytes: *const u8, len: usize); + +extern "C" { + pub fn medulla_btop_start( + config_dir: *const c_char, + cols: u16, + rows: u16, + waker: Option, + waker_ctx: *mut c_void, + ) -> c_int; + pub fn medulla_btop_resize(cols: u16, rows: u16); + pub fn medulla_btop_input(bytes: *const u8, len: usize); + pub fn medulla_btop_set_visible(visible: c_int); + pub fn medulla_btop_set_agents(agents: *const RawAgent, len: usize); + pub fn medulla_btop_drain(sink: Option, ctx: *mut c_void); + pub fn medulla_btop_take_leave() -> c_int; + pub fn medulla_btop_error(buf: *mut c_char, cap: usize) -> usize; + pub fn medulla_btop_stop(timeout_ms: u32); +} diff --git a/src/btop/src/lib.rs b/src/btop/src/lib.rs new file mode 100644 index 000000000..8d0940572 --- /dev/null +++ b/src/btop/src/lib.rs @@ -0,0 +1,32 @@ +//! btop, compiled in. +//! +//! The vendored btop sources (`vendor/btop`) are built into this crate by +//! `build.rs` and run on their own thread inside the host process. btop draws +//! exactly as it would on a terminal, but its terminal is virtual: the host +//! reports a size, feeds key and mouse bytes, and drains the ANSI output into +//! its own emulator. Medulla's patches to btop narrow its process box to coding +//! agents, which the host classifies and hands over with [`Btop::set_agents`]. +//! +//! btop keeps its state in C++ process globals, so there is one btop per +//! process: [`Btop::start`] succeeds once, and every later call fails with +//! [`StartError::AlreadyStarted`]. +//! +//! - [`handle`] — [`Btop`], the safe handle over the C ABI. +//! - [`types`] — agent tags and errors. +//! - `ffi` — the raw C ABI declared in `vendor/btop/include/medulla_btop.h`. + +#[cfg(not(medulla_btop_unsupported))] +mod ffi; +pub mod handle; +pub mod types; + +pub use handle::Btop; +pub use types::{AgentTag, StartError}; + +/// Whether this build carries btop. False on targets btop has no collector +/// for (Windows), where [`Btop::start`] always fails with +/// [`StartError::Unsupported`]. +pub const SUPPORTED: bool = cfg!(not(medulla_btop_unsupported)); + +#[cfg(test)] +mod tests; diff --git a/src/btop/src/types.rs b/src/btop/src/types.rs new file mode 100644 index 000000000..653c7b3a5 --- /dev/null +++ b/src/btop/src/types.rs @@ -0,0 +1,29 @@ +//! Data passed across the btop embedding boundary. + +/// One coding-agent process to show in btop's agents box. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AgentTag { + /// Operating-system process id of the agent's root process. + pub pid: u32, + /// Short name shown in the Agent column, such as `claude`. + pub label: String, + /// Whether Medulla launched this process (a session or task it owns). + pub launched: bool, +} + +/// Why btop could not be started. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum StartError { + /// This build has no btop: the target has no btop collector. + #[error("btop is not available on this platform")] + Unsupported, + /// btop was already started in this process; its globals allow one run. + #[error("btop is already running in this process")] + AlreadyStarted, + /// btop's thread could not be created. + #[error("could not start btop's thread")] + Spawn, + /// The config directory path cannot cross the C boundary. + #[error("btop config path contains a NUL byte")] + BadPath, +} From 43dd6dbe4702954c8f0bb0420704ea53b9c6934a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:54:57 +0000 Subject: [PATCH 18/60] feat(btop): add handle module for btop process management Introduce a new handle module that wraps btop process interaction, giving the rest of the code a single place to start, stop, and query btop instances instead of duplicating that logic. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/btop/src/handle.rs | 223 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 src/btop/src/handle.rs diff --git a/src/btop/src/handle.rs b/src/btop/src/handle.rs new file mode 100644 index 000000000..807f1566c --- /dev/null +++ b/src/btop/src/handle.rs @@ -0,0 +1,223 @@ +//! [`Btop`]: the safe handle over btop's C ABI. +//! +//! The handle is a token proving [`Btop::start`] succeeded; btop's state itself +//! is process-global on the C++ side, so the handle carries no data and every +//! method is a thin, thread-safe call across the boundary. + +use std::path::Path; +use std::sync::OnceLock; +use std::time::Duration; + +use crate::types::{AgentTag, StartError}; + +/// The host's wake callback. btop's threads call it whenever output is ready, +/// so it must be cheap and must not call back into btop. +type WakeFn = Box; + +static WAKER: OnceLock = OnceLock::new(); + +/// A running btop. See the crate docs for the one-per-process rule. +#[derive(Debug)] +pub struct Btop { + _started: (), +} + +#[cfg(not(medulla_btop_unsupported))] +mod imp { + use std::ffi::{c_void, CString}; + + use super::WAKER; + use crate::ffi; + + pub extern "C" fn wake(_ctx: *mut c_void) { + if let Some(waker) = WAKER.get() { + waker(); + } + } + + /// Hands drained bytes to the Rust closure passed as `ctx`. + pub extern "C" fn sink(ctx: *mut c_void, bytes: *const u8, len: usize) { + // SAFETY: `ctx` is the `&mut &mut dyn FnMut` built in `Btop::drain`, + // alive for the whole synchronous `medulla_btop_drain` call, and btop + // passes a buffer of `len` readable bytes. + let (consume, bytes) = unsafe { + ( + &mut *(ctx as *mut &mut dyn FnMut(&[u8])), + std::slice::from_raw_parts(bytes, len), + ) + }; + consume(bytes); + } + + /// Owned labels plus the raw table that borrows them. + pub fn raw_agents(agents: &[crate::AgentTag]) -> (Vec, Vec) { + let labels: Vec = agents + .iter() + .map(|agent| CString::new(agent.label.replace('\0', "")).unwrap_or_default()) + .collect(); + let raw = agents + .iter() + .zip(&labels) + .map(|(agent, label)| ffi::RawAgent { + pid: agent.pid, + label: label.as_ptr(), + launched: u8::from(agent.launched), + }) + .collect(); + (labels, raw) + } +} + +impl Btop { + /// Start btop's thread with a `cols`×`rows` view, keeping `btop.conf`, + /// its log and user themes under `config_dir` (created if absent). + /// + /// `waker` runs on btop's threads each time output is ready to + /// [`drain`](Self::drain); use it to schedule a redraw. + /// + /// # Errors + /// + /// [`StartError::Unsupported`] on targets without btop, + /// [`StartError::AlreadyStarted`] on any call after the first, + /// [`StartError::BadPath`] for a path with an interior NUL, and + /// [`StartError::Spawn`] if the thread could not be created. + pub fn start( + config_dir: &Path, + cols: u16, + rows: u16, + waker: impl Fn() + Send + Sync + 'static, + ) -> Result { + #[cfg(medulla_btop_unsupported)] + { + let _ = (config_dir, cols, rows, waker); + Err(StartError::Unsupported) + } + #[cfg(not(medulla_btop_unsupported))] + { + let dir = std::ffi::CString::new(config_dir.as_os_str().to_string_lossy().as_bytes()) + .map_err(|_| StartError::BadPath)?; + if WAKER.set(Box::new(waker)).is_err() { + return Err(StartError::AlreadyStarted); + } + // SAFETY: `dir` is a valid C string for the duration of the call + // (btop copies it), and `imp::wake` is a plain extern fn. + let status = unsafe { + crate::ffi::medulla_btop_start( + dir.as_ptr(), + cols, + rows, + Some(imp::wake), + std::ptr::null_mut(), + ) + }; + match status { + 0 => Ok(Self { _started: () }), + -1 => Err(StartError::AlreadyStarted), + _ => Err(StartError::Spawn), + } + } + } + + /// Report the view size in cells. A no-op when unchanged. + pub fn resize(&self, cols: u16, rows: u16) { + #[cfg(not(medulla_btop_unsupported))] + // SAFETY: plain value arguments. + unsafe { + crate::ffi::medulla_btop_resize(cols, rows) + }; + #[cfg(medulla_btop_unsupported)] + let _ = (cols, rows); + } + + /// Queue one key or mouse event, as the bytes a terminal would send. + pub fn send(&self, bytes: &[u8]) { + #[cfg(not(medulla_btop_unsupported))] + // SAFETY: btop copies `bytes.len()` bytes from a valid slice. + unsafe { + crate::ffi::medulla_btop_input(bytes.as_ptr(), bytes.len()) + }; + #[cfg(medulla_btop_unsupported)] + let _ = bytes; + } + + /// Show or hide btop. Hidden, it neither collects nor draws; shown again, + /// it redraws everything. + pub fn set_visible(&self, visible: bool) { + #[cfg(not(medulla_btop_unsupported))] + // SAFETY: plain value argument. + unsafe { + crate::ffi::medulla_btop_set_visible(i32::from(visible)) + }; + #[cfg(medulla_btop_unsupported)] + let _ = visible; + } + + /// Replace the set of agent processes btop's agents box shows. + pub fn set_agents(&self, agents: &[AgentTag]) { + #[cfg(not(medulla_btop_unsupported))] + { + let (_labels, raw) = imp::raw_agents(agents); + // SAFETY: `raw` and the labels it points into outlive the call, and + // btop copies every string before returning. + unsafe { crate::ffi::medulla_btop_set_agents(raw.as_ptr(), raw.len()) }; + } + #[cfg(medulla_btop_unsupported)] + let _ = agents; + } + + /// Take everything btop has drawn since the last drain, passing it to + /// `consume` (not called when there is nothing new). + pub fn drain(&self, mut consume: impl FnMut(&[u8])) { + #[cfg(not(medulla_btop_unsupported))] + { + let mut consume: &mut dyn FnMut(&[u8]) = &mut consume; + let ctx = &mut consume as *mut &mut dyn FnMut(&[u8]) as *mut std::ffi::c_void; + // SAFETY: `ctx` points at `consume`, which outlives this + // synchronous call; `imp::sink` casts it back to the same type. + unsafe { crate::ffi::medulla_btop_drain(Some(imp::sink), ctx) }; + } + #[cfg(medulla_btop_unsupported)] + let _ = &mut consume; + } + + /// Whether the operator asked to leave btop (`q`, or Quit in its menu) + /// since the last call. + pub fn take_leave(&self) -> bool { + #[cfg(not(medulla_btop_unsupported))] + // SAFETY: no arguments. + return unsafe { crate::ffi::medulla_btop_take_leave() } != 0; + #[cfg(medulla_btop_unsupported)] + false + } + + /// The message btop's thread died with, if it has. + pub fn error(&self) -> Option { + #[cfg(not(medulla_btop_unsupported))] + { + let mut buf = vec![0u8; 512]; + // SAFETY: btop writes at most `buf.len()` bytes, NUL included. + let len = unsafe { + crate::ffi::medulla_btop_error(buf.as_mut_ptr().cast(), buf.len()) + }; + if len == 0 { + return None; + } + buf.truncate(len.min(buf.len() - 1)); + Some(String::from_utf8_lossy(&buf).into_owned()) + } + #[cfg(medulla_btop_unsupported)] + None + } + + /// Stop btop's thread, saving its config, waiting at most `timeout`. + /// btop cannot be started again in this process afterwards. + pub fn stop(&self, timeout: Duration) { + #[cfg(not(medulla_btop_unsupported))] + // SAFETY: plain value argument. + unsafe { + crate::ffi::medulla_btop_stop(u32::try_from(timeout.as_millis()).unwrap_or(u32::MAX)) + }; + #[cfg(medulla_btop_unsupported)] + let _ = timeout; + } +} From 76b710d8dd1cfd5db3b1632bfa2ff065b855f199 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:55:11 +0000 Subject: [PATCH 19/60] feat(btop): add tests for btop module Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/btop/src/tests.rs | 101 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 src/btop/src/tests.rs diff --git a/src/btop/src/tests.rs b/src/btop/src/tests.rs new file mode 100644 index 000000000..3905c8e2a --- /dev/null +++ b/src/btop/src/tests.rs @@ -0,0 +1,101 @@ +//! btop runs once per process, so its lifecycle is exercised by one test that +//! walks it end to end; the pure helpers get their own. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use super::*; + +/// Drain until `pred` holds over everything drawn so far, or give up. +#[cfg(not(medulla_btop_unsupported))] +fn drain_until(btop: &Btop, seen: &mut String, pred: impl Fn(&str) -> bool) -> bool { + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline { + btop.drain(|bytes| seen.push_str(&String::from_utf8_lossy(bytes))); + if pred(seen) { + return true; + } + std::thread::sleep(Duration::from_millis(20)); + } + false +} + +#[cfg(not(medulla_btop_unsupported))] +#[test] +fn btop_runs_embedded_and_hands_quit_back_to_the_host() { + let dir = std::env::temp_dir().join(format!("medulla-btop-test-{}", std::process::id())); + let wakes = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&wakes); + let btop = Btop::start(&dir, 160, 48, move || { + counter.fetch_add(1, Ordering::Relaxed); + }) + .expect("btop starts"); + + // It draws its boxes into the virtual terminal, and wakes the host to say so. + let mut seen = String::new(); + assert!( + drain_until(&btop, &mut seen, |out| out.contains("cpu") && out.contains("mem")), + "no boxes drawn: {seen:?}" + ); + assert!(wakes.load(Ordering::Relaxed) > 0); + assert!(dir.join("btop.log").exists() || dir.exists()); + + // Agents are accepted and the agents box is titled for them. + btop.set_agents(&[AgentTag { + pid: std::process::id(), + label: "claude".into(), + launched: true, + }]); + btop.resize(170, 50); + seen.clear(); + assert!( + drain_until(&btop, &mut seen, |out| out.contains("agents")), + "agents box not drawn: {seen:?}" + ); + + // `q` asks the host to leave rather than ending the process. + assert!(!btop.take_leave()); + btop.send(b"q"); + let deadline = Instant::now() + Duration::from_secs(5); + let mut left = false; + while !left && Instant::now() < deadline { + left = btop.take_leave(); + std::thread::sleep(Duration::from_millis(10)); + } + assert!(left, "q did not request leave"); + assert_eq!(btop.error(), None); + + // A second start in the same process is refused, not undefined. + assert_eq!( + Btop::start(&dir, 80, 24, || {}).unwrap_err(), + StartError::AlreadyStarted + ); + + btop.set_visible(false); + btop.set_visible(true); + btop.stop(Duration::from_secs(5)); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(medulla_btop_unsupported)] +#[test] +fn unsupported_targets_refuse_to_start() { + assert!(!SUPPORTED); + assert_eq!( + Btop::start(std::path::Path::new("."), 80, 24, || {}).unwrap_err(), + StartError::Unsupported + ); +} + +#[test] +fn start_errors_read_as_sentences() { + assert_eq!( + StartError::AlreadyStarted.to_string(), + "btop is already running in this process" + ); + assert_eq!( + StartError::Unsupported.to_string(), + "btop is not available on this platform" + ); +} From cc90c1b702adb2879bb92a137f6ab904ef95205f Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:55:49 +0000 Subject: [PATCH 20/60] chore(deps): add medulla-btop crate to the lockfile Registers the new medulla-btop package and wires it into the medulla dependency set so the workspace lockfile reflects the added crate. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- Cargo.lock | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index b6241b577..61f836cb7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1850,6 +1850,14 @@ dependencies = [ "uuid", ] +[[package]] +name = "medulla-btop" +version = "0.15.0" +dependencies = [ + "cc", + "thiserror 2.0.19", +] + [[package]] name = "medulla-link" version = "0.15.0" @@ -1881,6 +1889,7 @@ dependencies = [ "futures", "libc", "medulla", + "medulla-btop", "medulla-link", "portable-pty", "ratatui", From 454d04ffeb1284b7de22e7971a2c9c20b020bcb1 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:57:14 +0000 Subject: [PATCH 21/60] feat(btop): add coding-agents-only process filter Add a proc_agents option that narrows the process box to coding-agent processes and their children, toggled with the A key and exposed in the options menu. Tree view and the filter are enabled by default so the process list starts focused on agents. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_config.cpp | 5 ++++- vendor/btop/src/btop_input.cpp | 8 ++++++++ vendor/btop/src/btop_menu.cpp | 7 +++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/vendor/btop/src/btop_config.cpp b/vendor/btop/src/btop_config.cpp index 3f0b0b00c..ca346b586 100644 --- a/vendor/btop/src/btop_config.cpp +++ b/vendor/btop/src/btop_config.cpp @@ -129,6 +129,8 @@ namespace Config { {"proc_tree", "#* Show processes as a tree."}, + {"proc_agents", "#* (Medulla) Show only coding-agent processes and their children in the process box."}, + {"proc_colors", "#* Use the cpu graph colors in the process list."}, {"proc_gradient", "#* Use a darkening gradient in the process list."}, @@ -319,7 +321,8 @@ namespace Config { {"truecolor", true}, {"rounded_corners", true}, {"proc_reversed", false}, - {"proc_tree", false}, + {"proc_tree", true}, + {"proc_agents", true}, {"proc_colors", true}, {"proc_gradient", true}, {"proc_per_core", false}, diff --git a/vendor/btop/src/btop_input.cpp b/vendor/btop/src/btop_input.cpp index cc5b01711..3032eeef7 100644 --- a/vendor/btop/src/btop_input.cpp +++ b/vendor/btop/src/btop_input.cpp @@ -329,6 +329,14 @@ namespace Input { no_update = false; Config::set("update_following", true); } + else if (key == "A") { + Config::flip("proc_agents"); + Config::set("proc_start", 0); + Config::set("proc_selected", 0); + Draw::calcSizes(); + Runner::run("all", true, true); + return; + } else if (key == "E" and Config::getB("proc_tree")) { atomic_wait(Runner::active); Proc::collapse_all = 1; diff --git a/vendor/btop/src/btop_menu.cpp b/vendor/btop/src/btop_menu.cpp index 29a13759e..37db9c76d 100644 --- a/vendor/btop/src/btop_menu.cpp +++ b/vendor/btop/src/btop_menu.cpp @@ -209,6 +209,7 @@ namespace Menu { {"c", "Toggle per-core cpu usage of processes."}, {"r", "Reverse sorting order in processes box."}, {"e", "Toggle processes tree view."}, + {"A", "Toggle coding agents only / all processes."}, {"E", "Collapse/expand all processes in tree view."}, {"%", "Toggles memory display mode in processes box."}, {"Selected +, -", "Expand/collapse the selected process in tree view."}, @@ -838,6 +839,12 @@ namespace Menu { "Set true to show processes grouped by", "parents with lines drawn between parent", "and child process."}, + {"proc_agents", + "Show only coding agents.", + "", + "Narrow the process box to the coding", + "agents Medulla knows about, and their", + "child processes. Toggle with A."}, {"proc_aggregate", "Aggregate child's resources in parent.", "", From 2d8728ac03f922fb621e441b19253df4f92a4be2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:57:23 +0000 Subject: [PATCH 22/60] fix(btop): wait for runner before flipping proc agents mode The agents toggle now waits on the active runner before changing the proc_agents config, since the box title depends on the mode and the boxes need to be rebuilt safely. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_input.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vendor/btop/src/btop_input.cpp b/vendor/btop/src/btop_input.cpp index 3032eeef7..4e7d8d506 100644 --- a/vendor/btop/src/btop_input.cpp +++ b/vendor/btop/src/btop_input.cpp @@ -330,6 +330,8 @@ namespace Input { Config::set("update_following", true); } else if (key == "A") { + //? Medulla: the box title changes with the mode, so rebuild the boxes + atomic_wait(Runner::active); Config::flip("proc_agents"); Config::set("proc_start", 0); Config::set("proc_selected", 0); From fcacf9f66c2e89e8589e3ba34cf192b7bc3e4b4a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:57:44 +0000 Subject: [PATCH 23/60] feat(proc): add agents mode to filter the process tree by coding agent Introduce an agents mode that narrows the process box to processes belonging to coding agents reported by the host, marking each process with its agent label and whether it is the agent root or a descendant. Agent ownership is resolved by walking each process up its ancestry with memoisation, and the filter is recomputed whenever the agent set or the toggle changes so the visible tree stays current. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_shared.cpp | 70 +++++++++++++++++++++++++- vendor/btop/src/btop_shared.hpp | 23 +++++++++ vendor/btop/src/linux/btop_collect.cpp | 9 ++-- 3 files changed, 97 insertions(+), 5 deletions(-) diff --git a/vendor/btop/src/btop_shared.cpp b/vendor/btop/src/btop_shared.cpp index 55490161e..834ca4bad 100644 --- a/vendor/btop/src/btop_shared.cpp +++ b/vendor/btop/src/btop_shared.cpp @@ -26,6 +26,7 @@ tab-size = 4 #include "btop_config.hpp" #include "btop_shared.hpp" +#include "btop_embed.hpp" #include "btop_tools.hpp" namespace fs = std::filesystem; @@ -193,13 +194,78 @@ bool set_priority(pid_t pid, int priority) { s_contains_ic(proc.cmd, filter) || s_contains_ic(proc.user, filter); } + //* ------------------------------------------ Medulla agent focus ------------------------------------------------ + //? Only the runner thread collects and draws, so these need no lock. + namespace { + std::unordered_map agent_marks; + uint64_t agents_seen_generation = UINT64_MAX; + bool agents_seen_mode = false; + size_t agents_seen_count = 0; + } + + bool agents_mode() { + return Config::getB("proc_agents"); + } + + bool refresh_agents(const vector& procs) { + auto [table, generation] = Embed::agents(); + const bool mode = agents_mode(); + std::unordered_map parent_of; + parent_of.reserve(procs.size()); + for (const auto& p : procs) parent_of[p.pid] = p.ppid; + + //? Walk each process up its ancestry to the nearest agent root, memoising + //? every pid on the way so the whole pass stays linear in practice. + std::unordered_map owner; + owner.reserve(procs.size()); + std::unordered_map marks; + for (const auto& p : procs) { + vector path; + const Embed::Agent* found = nullptr; + size_t at = p.pid; + for (size_t hops = 0; at != 0 and hops < 512; ++hops) { + if (auto known = owner.find(at); known != owner.end()) { found = known->second; break; } + if (auto agent = table.find(at); agent != table.end()) { found = &agent->second; break; } + path.push_back(at); + auto parent = parent_of.find(at); + if (parent == parent_of.end() or parent->second == at) break; + at = parent->second; + } + for (auto pid : path) owner[pid] = found; + if (found != nullptr) { + marks[p.pid] = agent_mark{found->label, found->launched, table.contains(p.pid)}; + } + } + const bool changed = generation != agents_seen_generation or mode != agents_seen_mode + or marks.size() != agents_seen_count; + agents_seen_generation = generation; + agents_seen_mode = mode; + agents_seen_count = marks.size(); + agent_marks = std::move(marks); + return changed; + } + + auto agent_of(size_t pid) -> const agent_mark* { + auto found = agent_marks.find(pid); + return found == agent_marks.end() ? nullptr : &found->second; + } + + auto passes_filter(const proc_info& proc, const std::string& filter) -> bool { + if (agents_mode() and agent_of(proc.pid) == nullptr) return false; + return filter.empty() or matches_filter(proc, filter); + } + + auto box_title() -> string { + return agents_mode() ? "agents" : "proc"; + } + void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, int cur_depth, bool collapsed, const string& filter, bool found, bool no_update, bool should_filter) { bool filtering = false; //? If filtering, include children of matching processes - if (not found and (should_filter or not filter.empty())) { - if (!matches_filter(cur_proc, filter)) { + if (not found and (should_filter or not filter.empty() or agents_mode())) { + if (!passes_filter(cur_proc, filter)) { filtering = true; cur_proc.filtered = true; filter_found++; diff --git a/vendor/btop/src/btop_shared.hpp b/vendor/btop/src/btop_shared.hpp index 898858f24..e72dec17e 100644 --- a/vendor/btop/src/btop_shared.hpp +++ b/vendor/btop/src/btop_shared.hpp @@ -444,6 +444,29 @@ namespace Proc { auto matches_filter(const proc_info& proc, const std::string& filter) -> bool; + //* Medulla: how one process relates to the coding agents the host reported. + struct agent_mark { + string label; + bool launched{}; + //? True for the agent's own process, false for its descendants + bool root{}; + }; + + //* Medulla: whether the process box is narrowed to coding agents. + bool agents_mode(); + + //* Medulla: recompute agent marks for ; true when the visible set may have changed. + bool refresh_agents(const vector& procs); + + //* Medulla: the agent mark for , or nullptr when it is not part of an agent. + auto agent_of(size_t pid) -> const agent_mark*; + + //* Medulla: the text filter plus, in agents mode, membership of an agent's process tree. + auto passes_filter(const proc_info& proc, const std::string& filter) -> bool; + + //* Medulla: "agents" in agents mode, otherwise upstream's "proc". + auto box_title() -> string; + //* Generate process tree list void _tree_gen(proc_info& cur_proc, vector& in_procs, vector& out_procs, int cur_depth, bool collapsed, const string& filter, diff --git a/vendor/btop/src/linux/btop_collect.cpp b/vendor/btop/src/linux/btop_collect.cpp index fe4c8ba47..8b43502f7 100644 --- a/vendor/btop/src/linux/btop_collect.cpp +++ b/vendor/btop/src/linux/btop_collect.cpp @@ -3511,12 +3511,15 @@ namespace Proc { } //* ---------------------------------------------Collection done----------------------------------------------- + //* Medulla: re-filter whenever the agent set or the agents toggle changes + if (refresh_agents(current_procs)) should_filter = true; + //* Match filter if defined if (should_filter) { filter_found = 0; for (auto& p : current_procs) { - if (not tree and not filter.empty()) { - if (!matches_filter(p, filter)) { + if (not tree and (not filter.empty() or agents_mode())) { + if (!passes_filter(p, filter)) { p.filtered = true; filter_found++; } else { @@ -3576,7 +3579,7 @@ namespace Proc { if (Config::ints.at("proc_selected") > 0) locate_selection = true; } - if (should_filter or not filter.empty()) filter_found = 0; + if (should_filter or not filter.empty() or agents_mode()) filter_found = 0; vector tree_procs; tree_procs.reserve(current_procs.size()); From 618711033036e845cf5a1a8f9ff7d75d5befe1f9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:57:50 +0000 Subject: [PATCH 24/60] fix(btop): reapply process filter when agent mode changes The macOS collector now re-runs filtering whenever the agent set or the agents toggle changes, and the filter pass also applies in agent mode even with an empty filter string. This keeps the process list consistent when switching agent mode instead of leaving stale filtered state. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/osx/btop_collect.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/vendor/btop/src/osx/btop_collect.cpp b/vendor/btop/src/osx/btop_collect.cpp index d89406962..92c0e1b3b 100644 --- a/vendor/btop/src/osx/btop_collect.cpp +++ b/vendor/btop/src/osx/btop_collect.cpp @@ -1940,12 +1940,15 @@ namespace Proc { //* ---------------------------------------------Collection done----------------------------------------------- + //* Medulla: re-filter whenever the agent set or the agents toggle changes + if (refresh_agents(current_procs)) should_filter = true; + //* Match filter if defined if (should_filter) { filter_found = 0; for (auto &p : current_procs) { - if (not tree and not filter.empty()) { - if (!matches_filter(p, filter)) { + if (not tree and (not filter.empty() or agents_mode())) { + if (!passes_filter(p, filter)) { p.filtered = true; filter_found++; } else { @@ -2005,7 +2008,7 @@ namespace Proc { if (Config::ints.at("proc_selected") > 0) locate_selection = true; } - if (should_filter or not filter.empty()) filter_found = 0; + if (should_filter or not filter.empty() or agents_mode()) filter_found = 0; vector tree_procs; tree_procs.reserve(current_procs.size()); From c91fc33d8b9d85aefb0b1c83815025888a684d43 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 18:58:53 +0000 Subject: [PATCH 25/60] feat(proc): add agent column and empty-state to the process box The process box now shows an Agent column in agents mode, labelling each agent's own process and dimming its descendants, and displays a hint instead of a blank list when no agents are running. The box title and filter controls shift to accommodate the longer title. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_draw.cpp | 39 ++++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/vendor/btop/src/btop_draw.cpp b/vendor/btop/src/btop_draw.cpp index 1c3b1bc23..b17c0b719 100644 --- a/vendor/btop/src/btop_draw.cpp +++ b/vendor/btop/src/btop_draw.cpp @@ -1704,6 +1704,17 @@ namespace Proc { return (not changed ? -1 : selected); } + //* Medulla: the Agent column. The agent's own process shows its name, marked + //* when Medulla launched it; its descendants show the name dimmed. + static string agent_cell(size_t pid, int size, const string& g_color, const string& end, bool highlighted) { + const auto* mark = agent_of(pid); + if (mark == nullptr) return string(max(0, size), ' '); + const string text = (mark->root ? (mark->launched ? "◆ " : "") : "↳ ") + mark->label; + const string color = highlighted ? "" : (not mark->root ? Theme::c("inactive_fg") + : mark->launched ? Theme::c("hi_fg") : g_color); + return color + uresize(text, size) + string(max(0, size - (int)ulen(text)), ' ') + end; + } + string draw(const vector& plist, bool force_redraw, bool data_same) { if (Runner::stopping) return ""; auto proc_tree = Config::getB("proc_tree"); @@ -1832,8 +1843,8 @@ namespace Proc { //? Draw structure of details box const string pid_str = to_string(detailed.entry.pid); out += Mv::to(y, x) + Theme::c("proc_box") + Symbols::div_left + Symbols::h_line + title_left + Theme::c("hi_fg") + Fx::b - + (tty_mode ? "4" : Symbols::superscript.at(4)) + Theme::c("title") + "proc" - + Fx::ub + title_right + Symbols::h_line * (width - 10) + Symbols::div_right + + (tty_mode ? "4" : Symbols::superscript.at(4)) + Theme::c("title") + box_title() + + Fx::ub + title_right + Symbols::h_line * (width - 6 - (int)box_title().size()) + Symbols::div_right + Mv::to(d_y, dgraph_x + 2) + title_left + Fx::b + Theme::c("title") + pid_str + Fx::ub + title_right + title_left + Fx::b + Theme::c("title") + uresize(detailed.entry.name, dgraph_width - pid_str.size() - 7, true) + Fx::ub + title_right; @@ -1899,17 +1910,19 @@ namespace Proc { //? Filter auto filtering = Config::getB("proc_filtering"); // ? filter(20) : Config::getS("proc_filter")) const auto filter_text = (filtering) ? filter(max(6, width - 66)) : uresize(Config::getS("proc_filter"), max(6, width - 66)); - out += Mv::to(y, x+9) + title_left + (not filter_text.empty() ? Fx::b : "") + Theme::c("hi_fg") + 'f' + //? Medulla: the box title may be longer than "proc"; keep the filter clear of it + const int title_shift = (int)box_title().size() - 4; + out += Mv::to(y, x + 9 + title_shift) + title_left + (not filter_text.empty() ? Fx::b : "") + Theme::c("hi_fg") + 'f' + Theme::c("title") + (not filter_text.empty() ? ' ' + filter_text : "ilter") + (not filtering and not filter_text.empty() ? Theme::c("hi_fg") + " del" : "") + (filtering ? Theme::c("hi_fg") + ' ' + Symbols::enter : "") + Fx::ub + title_right; if (not filtering) { int f_len = (filter_text.empty() ? 6 : ulen(filter_text) + 2); - Input::mouse_mappings["f"] = {y, x + 10, 1, f_len}; + Input::mouse_mappings["f"] = {y, x + 10 + title_shift, 1, f_len}; if (filter_text.empty() and Input::mouse_mappings.contains("delete")) Input::mouse_mappings.erase("delete"); else if (not filter_text.empty()) - Input::mouse_mappings["delete"] = {y, x + 11 + f_len, 1, 3}; + Input::mouse_mappings["delete"] = {y, x + 11 + title_shift + f_len, 1, 3}; } //? pause, per-core, reverse, tree and sorting @@ -1990,7 +2003,7 @@ namespace Proc { + ljust("Tree:", tree_size) + ' '; out += (thread_size > 0 ? Mv::l(4) + "Threads: " : "") - + ljust("User:", user_size) + ' ' + + ljust((agents_mode() ? "Agent:" : "User:"), user_size) + ' ' + rjust((mem_bytes ? "MemB" : "Mem%"), 5) + ' ' + rjust("Cpu%", (show_graphs ? 10 : 5)) + Fx::ub; } @@ -2163,7 +2176,8 @@ namespace Proc { }(); out += (thread_size > 0 ? t_color + rjust(proc_threads_string, thread_size) + ' ' + end : "" ) - + g_color + ljust((cmp_greater(p.user.size(), user_size) ? p.user.substr(0, user_size - 1) + '+' : p.user), user_size) + ' ' + + (agents_mode() ? agent_cell(p.pid, user_size, g_color, end, is_selected or is_followed) + : g_color + ljust((cmp_greater(p.user.size(), user_size) ? p.user.substr(0, user_size - 1) + '+' : p.user), user_size)) + ' ' + m_color + rjust(mem_str, 5) + end + ' ' + (is_selected or is_followed ? "" : Theme::c("inactive_fg")) + (show_graphs ? graph_bg * 5: "") + (p_graphs.contains(p.pid) ? Mv::l(5) + c_color + p_graphs.at(p.pid)({(p.cpu_p >= 0.1 and p.cpu_p < 5 ? 5ll : (long long)round(p.cpu_p))}, data_same) : "") + end + ' ' @@ -2172,6 +2186,15 @@ namespace Proc { else if (lc > height - 5 and proc_banner_shown) break; } + //? Medulla: say why an agents box is empty instead of showing a blank list + if (lc == 0 and agents_mode() and height > 6) { + const string lines[] = {"No coding agents running.", "Press A to show all processes."}; + for (int i = 0; const auto& line : lines) { + out += Mv::to(y + 3 + i++, x + max(1, (width - (int)line.size()) / 2)) + + Theme::c("inactive_fg") + line; + } + } + out += Fx::reset; while (lc++ < height - 3) out += Mv::to(y+lc+1, x+1) + string(width - 2, ' '); if (proc_banner_shown) { @@ -2545,7 +2568,7 @@ namespace Draw { y = (cpu_bottom and Cpu::shown) ? 1 : Cpu::height + 1; #endif select_max = height - 3; - box = createBox(x, y, width, height, Theme::c("proc_box"), true, "proc", "", 4); + box = createBox(x, y, width, height, Theme::c("proc_box"), true, Proc::box_title(), "", 4); } } } From d0f04bb11d5474f62cf5c60fefcef073be424e4b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:00:02 +0000 Subject: [PATCH 26/60] refactor(resources): remove resource sampler and plot modules The resource sampler, plot rendering, and their configuration types have been deleted along with the associated tests and the resources tab feature test. This removes the resource monitoring subsystem entirely. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/sdk/src/config/resources/mod.rs | 10 - src/sdk/src/config/resources/tests.rs | 93 --- src/sdk/src/config/resources/types.rs | 145 ----- src/tui/src/event_loop/resources.rs | 63 --- src/tui/src/remote/serve/tests/usage.rs | 222 -------- src/tui/src/remote/serve/usage.rs | 149 ----- .../ui/app/render/resources/agents/command.rs | 79 --- .../src/ui/app/render/resources/agents/mod.rs | 432 -------------- .../ui/app/render/resources/agents/rows.rs | 341 ----------- .../ui/app/render/resources/agents/tests.rs | 410 -------------- .../ui/app/render/resources/agents/types.rs | 34 -- .../ui/app/render/resources/agents_detail.rs | 62 -- src/tui/src/ui/app/render/resources/mod.rs | 6 - src/tui/src/ui/app/resources/agent_input.rs | 243 -------- src/tui/src/ui/app/resources/chrome.rs | 303 ---------- src/tui/src/ui/app/resources/cpu/mod.rs | 529 ------------------ src/tui/src/ui/app/resources/cpu/tests.rs | 37 -- src/tui/src/ui/app/resources/disks.rs | 276 --------- src/tui/src/ui/app/resources/disks_tests.rs | 11 - src/tui/src/ui/app/resources/input.rs | 187 ------- src/tui/src/ui/app/resources/keys.rs | 40 -- src/tui/src/ui/app/resources/layout.rs | 142 ----- src/tui/src/ui/app/resources/mem.rs | 251 --------- src/tui/src/ui/app/resources/mod.rs | 227 -------- src/tui/src/ui/app/resources/net.rs | 336 ----------- src/tui/src/ui/app/resources/net_tests.rs | 31 - .../src/ui/app/resources/tests/agent_rows.rs | 232 -------- src/tui/src/ui/app/resources/tests/agents.rs | 283 ---------- .../src/ui/app/resources/tests/controls.rs | 267 --------- src/tui/src/ui/app/resources/tests/mod.rs | 433 -------------- src/tui/src/ui/app/resources/tests/panels.rs | 450 --------------- src/tui/src/ui/app/resources/types.rs | 395 ------------- .../src/ui/app/settings_edit/resources/mod.rs | 213 ------- .../ui/app/settings_edit/resources/rows.rs | 236 -------- .../ui/app/settings_edit/resources/tests.rs | 33 -- .../ui/app/settings_edit/resources/types.rs | 48 -- .../ui/app/settings_edit/resources/values.rs | 129 ----- src/tui/src/ui/plot/graph.rs | 150 ----- src/tui/src/ui/plot/meter.rs | 53 -- src/tui/src/ui/plot/mod.rs | 95 ---- src/tui/src/ui/plot/symbols.rs | 53 -- src/tui/src/ui/plot/tests.rs | 136 ----- src/tui/src/ui/resources/cpu.rs | 438 --------------- src/tui/src/ui/resources/cpu_tests.rs | 98 ---- src/tui/src/ui/resources/net.rs | 151 ----- src/tui/src/ui/resources/net_tests.rs | 113 ---- src/tui/src/ui/resources/sampler/disks.rs | 114 ---- src/tui/src/ui/resources/sampler/filters.rs | 147 ----- src/tui/src/ui/resources/sampler/history.rs | 49 -- src/tui/src/ui/resources/sampler/linux.rs | 153 ----- .../src/ui/resources/sampler/linux_tests.rs | 7 - src/tui/src/ui/resources/sampler/macos.rs | 81 --- src/tui/src/ui/resources/sampler/mod.rs | 168 ------ src/tui/src/ui/resources/sampler/source.rs | 467 ---------------- .../src/ui/resources/sampler/tests/filters.rs | 285 ---------- src/tui/src/ui/resources/sampler/tests/mod.rs | 392 ------------- src/tui/src/ui/resources/sampler/types.rs | 316 ----------- src/tui/src/ui/theme/gradient.rs | 220 -------- src/tui/tests/feature_resources_tab.rs | 69 --- 59 files changed, 11133 deletions(-) delete mode 100644 src/sdk/src/config/resources/mod.rs delete mode 100644 src/sdk/src/config/resources/tests.rs delete mode 100644 src/sdk/src/config/resources/types.rs delete mode 100644 src/tui/src/event_loop/resources.rs delete mode 100644 src/tui/src/remote/serve/tests/usage.rs delete mode 100644 src/tui/src/remote/serve/usage.rs delete mode 100644 src/tui/src/ui/app/render/resources/agents/command.rs delete mode 100644 src/tui/src/ui/app/render/resources/agents/mod.rs delete mode 100644 src/tui/src/ui/app/render/resources/agents/rows.rs delete mode 100644 src/tui/src/ui/app/render/resources/agents/tests.rs delete mode 100644 src/tui/src/ui/app/render/resources/agents/types.rs delete mode 100644 src/tui/src/ui/app/render/resources/agents_detail.rs delete mode 100644 src/tui/src/ui/app/render/resources/mod.rs delete mode 100644 src/tui/src/ui/app/resources/agent_input.rs delete mode 100644 src/tui/src/ui/app/resources/chrome.rs delete mode 100644 src/tui/src/ui/app/resources/cpu/mod.rs delete mode 100644 src/tui/src/ui/app/resources/cpu/tests.rs delete mode 100644 src/tui/src/ui/app/resources/disks.rs delete mode 100644 src/tui/src/ui/app/resources/disks_tests.rs delete mode 100644 src/tui/src/ui/app/resources/input.rs delete mode 100644 src/tui/src/ui/app/resources/keys.rs delete mode 100644 src/tui/src/ui/app/resources/layout.rs delete mode 100644 src/tui/src/ui/app/resources/mem.rs delete mode 100644 src/tui/src/ui/app/resources/mod.rs delete mode 100644 src/tui/src/ui/app/resources/net.rs delete mode 100644 src/tui/src/ui/app/resources/net_tests.rs delete mode 100644 src/tui/src/ui/app/resources/tests/agent_rows.rs delete mode 100644 src/tui/src/ui/app/resources/tests/agents.rs delete mode 100644 src/tui/src/ui/app/resources/tests/controls.rs delete mode 100644 src/tui/src/ui/app/resources/tests/mod.rs delete mode 100644 src/tui/src/ui/app/resources/tests/panels.rs delete mode 100644 src/tui/src/ui/app/resources/types.rs delete mode 100644 src/tui/src/ui/app/settings_edit/resources/mod.rs delete mode 100644 src/tui/src/ui/app/settings_edit/resources/rows.rs delete mode 100644 src/tui/src/ui/app/settings_edit/resources/tests.rs delete mode 100644 src/tui/src/ui/app/settings_edit/resources/types.rs delete mode 100644 src/tui/src/ui/app/settings_edit/resources/values.rs delete mode 100644 src/tui/src/ui/plot/graph.rs delete mode 100644 src/tui/src/ui/plot/meter.rs delete mode 100644 src/tui/src/ui/plot/mod.rs delete mode 100644 src/tui/src/ui/plot/symbols.rs delete mode 100644 src/tui/src/ui/plot/tests.rs delete mode 100644 src/tui/src/ui/resources/cpu.rs delete mode 100644 src/tui/src/ui/resources/cpu_tests.rs delete mode 100644 src/tui/src/ui/resources/net.rs delete mode 100644 src/tui/src/ui/resources/net_tests.rs delete mode 100644 src/tui/src/ui/resources/sampler/disks.rs delete mode 100644 src/tui/src/ui/resources/sampler/filters.rs delete mode 100644 src/tui/src/ui/resources/sampler/history.rs delete mode 100644 src/tui/src/ui/resources/sampler/linux.rs delete mode 100644 src/tui/src/ui/resources/sampler/linux_tests.rs delete mode 100644 src/tui/src/ui/resources/sampler/macos.rs delete mode 100644 src/tui/src/ui/resources/sampler/mod.rs delete mode 100644 src/tui/src/ui/resources/sampler/source.rs delete mode 100644 src/tui/src/ui/resources/sampler/tests/filters.rs delete mode 100644 src/tui/src/ui/resources/sampler/tests/mod.rs delete mode 100644 src/tui/src/ui/resources/sampler/types.rs delete mode 100644 src/tui/src/ui/theme/gradient.rs delete mode 100644 src/tui/tests/feature_resources_tab.rs diff --git a/src/sdk/src/config/resources/mod.rs b/src/sdk/src/config/resources/mod.rs deleted file mode 100644 index 855f71697..000000000 --- a/src/sdk/src/config/resources/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! Configuration for the resource sampler. - -mod types; - -pub use types::{ - ResourcesConfig, DEFAULT_RESOURCES_UPDATE_MS, MAX_RESOURCES_UPDATE_MS, MIN_RESOURCES_UPDATE_MS, -}; - -#[cfg(test)] -mod tests; diff --git a/src/sdk/src/config/resources/tests.rs b/src/sdk/src/config/resources/tests.rs deleted file mode 100644 index a05b23c49..000000000 --- a/src/sdk/src/config/resources/tests.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! Unit tests for the Resources configuration. - -use super::*; - -#[test] -fn resources_interval_defaults_and_clamps_during_deserialization() { - let defaults = ResourcesConfig::default(); - assert_eq!(defaults.update_ms, 2_000); - assert_eq!(defaults.shown_boxes, "cpu,mem,net,agents"); - assert!(defaults.presets.starts_with("cpu:0:default")); - assert_eq!(defaults.preset, 0); - assert_eq!(defaults.cpu_graph_upper, "total"); - assert_eq!(defaults.cpu_graph_lower, "iowait"); - assert!(!defaults.cpu_invert_lower); - assert!(!defaults.cpu_single_graph); - assert_eq!(defaults.temp_scale, "celsius"); - assert_eq!(defaults.freq_mode, "auto"); - assert!(defaults.show_battery); - assert!(defaults.mem_graphs && defaults.show_disks && defaults.show_swap); - assert!(defaults.io_graph_speeds.is_empty()); - assert!(defaults.swap_disk && defaults.only_physical && defaults.use_fstab); - assert!(!defaults.io_mode && !defaults.io_graph_combined); - let low: ResourcesConfig = serde_json::from_str(r#"{"updateMs":1}"#).unwrap(); - let high: ResourcesConfig = serde_json::from_str(r#"{"updateMs":50000}"#).unwrap(); - assert_eq!(low.update_ms, MIN_RESOURCES_UPDATE_MS); - assert_eq!(high.update_ms, MAX_RESOURCES_UPDATE_MS); -} - -#[test] -fn memory_and_disk_options_deserialize_in_camel_case_and_old_configs_default() { - let config: ResourcesConfig = serde_json::from_str(r#"{"memGraphs":false,"showDisks":false,"showSwap":false,"swapDisk":true,"onlyPhysical":true,"useFstab":true,"disksFilter":"exclude=/boot","ioMode":true,"ioGraphCombined":true,"ioGraphSpeeds":"/:20 /boot:1"}"#).unwrap(); - assert!(!config.mem_graphs && !config.show_disks && !config.show_swap); - assert!( - config.swap_disk - && config.only_physical - && config.use_fstab - && config.io_mode - && config.io_graph_combined - ); - assert_eq!(config.disks_filter, "exclude=/boot"); - assert_eq!(config.io_graph_speeds, "/:20 /boot:1"); - let old: ResourcesConfig = serde_json::from_str("{}").unwrap(); - assert!(old.show_disks && old.show_swap && old.only_physical && old.use_fstab); -} - -#[test] -fn cpu_sensor_options_deserialize_as_camel_case_and_old_config_keeps_defaults() { - let config: ResourcesConfig = serde_json::from_str( - r#"{"cpuGraphUpper":"user","cpuGraphLower":"system","cpuInvertLower":true,"cpuSingleGraph":true,"tempScale":"fahrenheit","freqMode":"ghz","showBattery":false}"#, - ) - .unwrap(); - assert_eq!(config.cpu_graph_upper, "user"); - assert_eq!(config.cpu_graph_lower, "system"); - assert!(config.cpu_invert_lower); - assert!(config.cpu_single_graph); - assert_eq!(config.temp_scale, "fahrenheit"); - assert_eq!(config.freq_mode, "ghz"); - assert!(!config.show_battery); - let old: ResourcesConfig = serde_json::from_str(r#"{"updateMs":2500}"#).unwrap(); - assert_eq!(old.cpu_graph_upper, "total"); - assert!(old.show_battery); -} - -#[test] -fn resources_layout_settings_deserialize_as_camel_case() { - let config: ResourcesConfig = serde_json::from_str( - r#"{"shownBoxes":"cpu,agents","presets":"cpu:1:block","preset":1,"cpuBottom":true,"memBelowNet":true,"agentsLeft":true}"#, - ).unwrap(); - assert_eq!(config.shown_boxes, "cpu,agents"); - assert_eq!(config.presets, "cpu:1:block"); - assert_eq!(config.preset, 1); - assert_eq!(config.cpu_bottom, Some(true)); - assert_eq!(config.mem_below_net, Some(true)); - assert_eq!(config.agents_left, Some(true)); -} - -#[test] -fn network_options_deserialize_in_camel_case_and_old_configs_default() { - let config: ResourcesConfig = serde_json::from_str( - r#"{"netAuto":false,"netSync":true,"netDownload":250,"netUpload":125,"netIface":"eth0","swapUploadDownload":true}"#, - ).unwrap(); - assert!(!config.net_auto && config.net_sync); - assert_eq!(config.net_download, 250); - assert_eq!(config.net_upload, 125); - assert_eq!(config.net_iface.as_deref(), Some("eth0")); - assert!(config.swap_upload_download); - let old: ResourcesConfig = serde_json::from_str("{}").unwrap(); - assert!(old.net_auto); - assert!(!old.net_sync && !old.swap_upload_download); - assert_eq!(old.net_download, 100); - assert_eq!(old.net_upload, 100); - assert_eq!(old.net_iface, None); -} diff --git a/src/sdk/src/config/resources/types.rs b/src/sdk/src/config/resources/types.rs deleted file mode 100644 index 850398903..000000000 --- a/src/sdk/src/config/resources/types.rs +++ /dev/null @@ -1,145 +0,0 @@ -//! Resource sampler timing configuration. - -use serde::{Deserialize, Serialize}; - -/// Default resource sample interval, in milliseconds. -pub const DEFAULT_RESOURCES_UPDATE_MS: u64 = 2_000; -/// Smallest supported resource sample interval, in milliseconds. -pub const MIN_RESOURCES_UPDATE_MS: u64 = 100; -/// Largest supported resource sample interval, in milliseconds. -pub const MAX_RESOURCES_UPDATE_MS: u64 = 10_000; - -fn default_update_ms() -> u64 { - DEFAULT_RESOURCES_UPDATE_MS -} -fn default_shown_boxes() -> String { - "cpu,mem,net,agents".into() -} -fn default_presets() -> String { - "cpu:0:default,mem:0:default,net:0:default,agents:1:default".into() -} - -fn deserialize_update_ms<'de, D>(deserializer: D) -> Result -where - D: serde::Deserializer<'de>, -{ - let value = u64::deserialize(deserializer)?; - Ok(value.clamp(MIN_RESOURCES_UPDATE_MS, MAX_RESOURCES_UPDATE_MS)) -} - -/// Settings for the background resource sampler. -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[serde(default, rename_all = "camelCase")] -pub struct ResourcesConfig { - /// Milliseconds between system resource samples. - #[serde( - default = "default_update_ms", - deserialize_with = "deserialize_update_ms" - )] - pub update_ms: u64, - /// Comma-separated boxes visible when the tab first opens. - #[serde(default = "default_shown_boxes")] - pub shown_boxes: String, - /// Whitespace-separated btop-style box presets. - #[serde(default = "default_presets")] - pub presets: String, - /// Index of the selected preset in `presets`. - pub preset: usize, - /// Explicit CPU placement override. When absent, the selected preset wins. - pub cpu_bottom: Option, - /// Explicit Mem/Net placement override. When absent, the selected preset wins. - pub mem_below_net: Option, - /// Explicit Agents placement override. When absent, the selected preset wins. - pub agents_left: Option, - /// CPU field drawn by the upper graph. - pub cpu_graph_upper: String, - /// CPU field drawn by the lower graph. - pub cpu_graph_lower: String, - /// Draw the lower CPU graph upside down. - pub cpu_invert_lower: bool, - /// Collapse CPU fields into one graph. - pub cpu_single_graph: bool, - /// Temperature scale (`celsius` or `fahrenheit`). - pub temp_scale: String, - /// Frequency presentation (`auto`, `mhz`, or `ghz`). - pub freq_mode: String, - /// Show battery percentage when the platform reports it. - pub show_battery: bool, - /// Draw memory and swap history as graphs. - pub mem_graphs: bool, - /// Show mounted disks in the memory panel. - pub show_disks: bool, - /// Show swap usage in the memory panel. - pub show_swap: bool, - /// Mount a swap device as a disk row when available. - pub swap_disk: bool, - /// Hide virtual and loop devices from the disk list. - pub only_physical: bool, - /// Prefer filesystems listed in /etc/fstab. - pub use_fstab: bool, - /// Comma-separated mount filters; entries prefixed by `exclude=` are omitted. - pub disks_filter: String, - /// Show disk busy percentage in the disks pane. - pub io_mode: bool, - /// Combine read and write series into one graph. - pub io_graph_combined: bool, - /// Per-mount IO graph ceilings in MiB/s (`mount:speed` pairs). - pub io_graph_speeds: String, - /// Automatically scale network graphs to recent traffic. - pub net_auto: bool, - /// Use the larger network direction scale for both graphs. - pub net_sync: bool, - /// Download graph ceiling in KiB/s when automatic scaling is disabled. - pub net_download: u64, - /// Upload graph ceiling in KiB/s when automatic scaling is disabled. - pub net_upload: u64, - /// Preferred network interface name, if available. - pub net_iface: Option, - /// Swap the displayed download and upload directions. - pub swap_upload_download: bool, -} - -impl Default for ResourcesConfig { - fn default() -> Self { - Self { - update_ms: DEFAULT_RESOURCES_UPDATE_MS, - shown_boxes: default_shown_boxes(), - presets: default_presets(), - preset: 0, - cpu_bottom: None, - mem_below_net: None, - agents_left: None, - cpu_graph_upper: "total".into(), - cpu_graph_lower: "iowait".into(), - cpu_invert_lower: false, - cpu_single_graph: false, - temp_scale: "celsius".into(), - freq_mode: "auto".into(), - show_battery: true, - mem_graphs: true, - show_disks: true, - show_swap: true, - swap_disk: true, - only_physical: true, - use_fstab: true, - disks_filter: String::new(), - io_mode: false, - io_graph_combined: false, - io_graph_speeds: String::new(), - net_auto: true, - net_sync: false, - net_download: 100, - net_upload: 100, - net_iface: None, - swap_upload_download: false, - } - } -} - -impl ResourcesConfig { - /// Return the supported interval, clamping programmatic values as well. - pub fn update_interval_ms(&self) -> u64 { - self.update_ms - .clamp(MIN_RESOURCES_UPDATE_MS, MAX_RESOURCES_UPDATE_MS) - } -} diff --git a/src/tui/src/event_loop/resources.rs b/src/tui/src/event_loop/resources.rs deleted file mode 100644 index 71e3ae693..000000000 --- a/src/tui/src/event_loop/resources.rs +++ /dev/null @@ -1,63 +0,0 @@ -//! The background resource sampler behind the Resources tab. -//! -//! Sampling runs off the UI task and only while the tab is on screen, so the -//! rest of the app never pays for a whole-host process walk. - -use std::time::Duration; - -use medulla_tui::ui::app::App; -use medulla_tui::ui::resources::sampler::{self, DiskOptions, SystemResourceSource}; -use tokio::sync::{mpsc, watch}; - -use super::types::AppMsg; - -/// The handles the loop uses to retune a running sampler. -pub(super) struct ResourceSampler { - interval: watch::Sender>, - disk_options: watch::Sender, -} - -impl ResourceSampler { - /// Start sampling, keeping `history_capacity` readings for the graphs. - pub(super) fn spawn( - app: &App, - history_capacity: usize, - msg_tx: &mpsc::UnboundedSender, - ) -> Self { - let (interval, interval_rx) = watch::channel(sampling_period(app)); - let (disk_options, disk_options_rx) = watch::channel(disk_options_for(app)); - let msg_tx = msg_tx.clone(); - sampler::spawn_sampler_with_disk_options( - SystemResourceSource::default(), - interval_rx, - disk_options_rx, - history_capacity, - move |snapshot| msg_tx.send(AppMsg::Resources(snapshot)).is_ok(), - ); - Self { - interval, - disk_options, - } - } - - /// Follow the visible tab and the configured cadence and disk filters. - pub(super) fn retune(&self, app: &App) { - sampler::update_interval(&self.interval, sampling_period(app)); - sampler::update_disk_options(&self.disk_options, disk_options_for(app)); - } -} - -/// How often to sample, or `None` to pause while nothing shows the readings. -fn sampling_period(app: &App) -> Option { - (app.tab() == "Resources") - .then(|| Duration::from_millis(app.loaded.config.resources.update_interval_ms())) -} - -fn disk_options_for(app: &App) -> DiskOptions { - let resources = &app.loaded.config.resources; - DiskOptions { - only_physical: resources.only_physical, - use_fstab: resources.use_fstab, - filter: resources.disks_filter.clone(), - } -} diff --git a/src/tui/src/remote/serve/tests/usage.rs b/src/tui/src/remote/serve/tests/usage.rs deleted file mode 100644 index 57014c720..000000000 --- a/src/tui/src/remote/serve/tests/usage.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! Session rows carry their agent process usage, and a list too large for one -//! message is split into chunks without losing a row. - -use super::support::*; -use medulla::protocol::{AgentUsage, RemoteSessionRow, RemoteSessionState}; - -#[test] -fn session_usage_matches_classified_descendant_and_aggregated_tree() { - use medulla::resources::agents::{ - discover_agents, AgentOrigin, KnownProcessRoot, ProcessRecord, ProcessUsage, - }; - let process = |pid, ppid, argv: &[&str], cpu, rss| ProcessRecord { - pid, - ppid, - exe: (pid == 11).then(|| std::path::PathBuf::from("/usr/bin/claude")), - argv: Some(argv.iter().map(|arg| (*arg).to_owned()).collect()), - cwd: None, - started_at_secs: pid as u64, - usage: ProcessUsage { - cpu_percent: cpu, - rss_bytes: rss, - threads: 1, - io: None, - }, - }; - let processes = vec![ - process(10, None, &["pty-host"], 1.0, 100), - process(11, Some(10), &["claude"], 4.0, 200), - process(12, Some(11), &["git", "status"], 2.0, 50), - ]; - let roots = vec![KnownProcessRoot { - pid: 10, - started_at_secs: 10, - origin: AgentOrigin::Session { id: "w_10".into() }, - }]; - let agents = discover_agents(&processes, &roots, 99, 20); - let agent = super::super::usage::classified_session_agent(&agents, "w_10") - .expect("the discovered child agent belongs to the session root"); - assert_eq!(agent.pid, Some(11)); - assert_eq!(agent.kind, medulla::resources::agents::AgentKind::Claude); - assert_eq!(agent.usage.cpu_percent, 6.0); - assert_eq!(agent.usage.rss_bytes, 250); -} - -#[test] -fn oversized_session_usage_is_trimmed_per_bounded_message() { - let row = |id: &str, pid| RemoteSessionRow { - id: id.into(), - label: "agent".into(), - provider: "claude".into(), - preset: None, - state: RemoteSessionState::Running, - cwd: "/workspace".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: true, - working: true, - attention: None, - bracketed_paste: false, - last_error: None, - usage: Some(AgentUsage { - kind: "Claude".into(), - pid, - cpu: 12.5, - rss: 1024, - threads: 5, - started_at: 1_700_000_000, - cpu_history: vec![12.5; 300], - }), - }; - let source = vec![row("w_1", 101), row("w_2", 202)]; - let messages = super::super::chunks::sessions_messages(&source, 6); - let rows = messages - .iter() - .flat_map(|message| match message { - RemoteMessage::Sessions { rows } | RemoteMessage::SessionsChunk { rows, .. } => rows, - _ => panic!("expected a session list message"), - }) - .collect::>(); - assert!(messages.iter().all(|message| { - encode_remote_message(message).len() <= medulla_link::MAX_MESSAGE_BYTES - })); - assert_eq!(rows.len(), 2, "usage trimming must preserve session rows"); - assert!(rows.iter().all(|row| row.usage.is_some())); - assert!(rows.iter().all(|row| { - row.usage - .as_ref() - .is_some_and(|usage| usage.cpu_history.len() < 300) - })); -} - -#[test] -fn oversized_base_session_lists_are_chunked_without_dropping_rows() { - let rows = (0..80) - .map(|index| RemoteSessionRow { - id: format!("session-{index:03}"), - label: format!("session label {index}"), - provider: "shell".into(), - preset: None, - state: RemoteSessionState::Running, - cwd: "/workspace/project".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: false, - working: false, - attention: None, - bracketed_paste: false, - last_error: None, - usage: None, - }) - .collect::>(); - let messages = super::super::chunks::sessions_messages(&rows, 7); - assert!(messages.len() > 1); - let mut received = Vec::new(); - for message in &messages { - assert!(encode_remote_message(message).len() <= medulla_link::MAX_MESSAGE_BYTES); - match message { - RemoteMessage::SessionsChunk { rows, .. } => { - received.extend(rows.iter().map(|row| row.id.clone())) - } - other => panic!("expected chunked list, got {other:?}"), - } - } - assert_eq!( - received, - rows.iter().map(|row| row.id.clone()).collect::>() - ); -} - -#[test] -fn oversized_usage_lists_keep_usage_on_chunks_that_fit_it() { - let rows = (0..80) - .map(|index| RemoteSessionRow { - id: format!("agent-{index:03}"), - label: format!("agent {index}"), - provider: "claude".into(), - preset: None, - state: RemoteSessionState::Running, - cwd: "/workspace/project".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: true, - working: true, - attention: None, - bracketed_paste: false, - last_error: None, - usage: Some(AgentUsage { - kind: "Claude".into(), - pid: 10_000 + index, - cpu: 4.5, - rss: 1024, - threads: 5, - started_at: 1_700_000_000, - cpu_history: vec![4.5; 32], - }), - }) - .collect::>(); - let messages = super::super::chunks::sessions_messages(&rows, 8); - assert!(messages.len() > 1); - let mut received = Vec::new(); - for message in &messages { - assert!(encode_remote_message(message).len() <= medulla_link::MAX_MESSAGE_BYTES); - let RemoteMessage::SessionsChunk { rows, .. } = message else { - panic!("expected bounded chunks") - }; - assert!( - rows.iter().all(|row| row.usage.is_some()), - "a chunk that fits its usage should retain it" - ); - received.extend(rows.iter().map(|row| row.id.clone())); - } - assert_eq!( - received, - rows.iter().map(|row| row.id.clone()).collect::>() - ); -} - -#[test] -fn oversized_multibyte_session_fields_are_safely_bounded() { - let mut row = RemoteSessionRow { - id: "unicode-row".into(), - label: "界".repeat(2048), - provider: "shell".into(), - preset: Some("é".repeat(2048)), - state: RemoteSessionState::Running, - cwd: "/workspace".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: false, - working: false, - attention: Some(medulla::protocol::RemoteAttention { - summary: "é漢".repeat(2048), - kind: "permission".into(), - }), - bracketed_paste: false, - last_error: None, - usage: None, - }; - let messages = super::super::chunks::sessions_messages(&[row.clone()], 9); - assert_eq!(messages.len(), 1); - assert!(encode_remote_message(&messages[0]).len() <= medulla_link::MAX_MESSAGE_BYTES); - let RemoteMessage::SessionsChunk { rows, .. } = &messages[0] else { - panic!("oversized row should use a bounded chunk") - }; - row = rows[0].clone(); - assert_eq!(row.id, "unicode-row"); - assert!(row.label.len() < "界".repeat(2048).len()); - assert!(row.preset.unwrap().len() < "é".repeat(2048).len()); - assert!(row.attention.unwrap().summary.len() < "é漢".repeat(2048).len()); - - let mut boundary = "é漢".to_owned(); - super::super::chunks::truncate_to_char_boundary(&mut boundary, 3); - assert_eq!(boundary, "é"); -} diff --git a/src/tui/src/remote/serve/usage.rs b/src/tui/src/remote/serve/usage.rs deleted file mode 100644 index 939b35784..000000000 --- a/src/tui/src/remote/serve/usage.rs +++ /dev/null @@ -1,149 +0,0 @@ -//! Per-session agent process usage for the session rows a host serves, so a -//! client's Resources tab can list the agents running on that host. - -use std::collections::{HashMap, HashSet}; -use std::time::{Duration, Instant}; - -use medulla::protocol::{AgentUsage, RemoteSessionRow}; -use medulla::resources::agents::{discover_agents, AgentOrigin, AgentProcess, KnownProcessRoot}; - -use crate::ui::resources::sampler::{ResourceSource, SystemResourceSource}; -use crate::worker::pty::PtyManager; - -/// How many CPU readings each session's usage carries. -const CPU_HISTORY: usize = 32; - -/// Samples the host's processes at most once per interval and remembers each -/// session's latest usage between samples. -pub(super) struct UsageSampler { - source: SystemResourceSource, - sampled_at: Option, - interval: Duration, - history: HashMap<(u32, u64), Vec>, - cache: HashMap, -} - -impl Default for UsageSampler { - fn default() -> Self { - Self { - source: SystemResourceSource::default(), - sampled_at: None, - interval: Duration::from_millis(2_000), - history: HashMap::new(), - cache: HashMap::new(), - } - } -} - -impl UsageSampler { - /// Set the minimum time between process samples. - pub(super) fn set_interval(&mut self, interval: Duration) { - self.interval = interval.max(Duration::from_millis(1)); - } - - /// Attach each session's agent usage to its row, sampling when one is due. - pub(super) fn annotate( - &mut self, - sessions: &PtyManager, - mut rows: Vec, - ) -> Vec { - let now = Instant::now(); - let sample = self - .sampled_at - .is_none_or(|last| now.duration_since(last) >= self.interval); - if sample { - self.sampled_at = Some(now); - // Rebuild from this sample so exited/reaped PIDs cannot leave - // stale process metrics attached to a still-retained session row. - self.cache.clear(); - let agents = self.discover(sessions, &rows); - for row in &rows { - if let Some(agent) = classified_session_agent(&agents, &row.id) { - self.record(&row.id, agent); - } - } - } - for row in &mut rows { - row.usage = self.cache.get(&row.id).cloned(); - } - // Keep the process history bounded to live identities only. - let current: HashSet<_> = rows - .iter() - .filter_map(|row| { - row.usage - .as_ref() - .map(|usage| (usage.pid, usage.started_at)) - }) - .collect(); - self.history - .retain(|identity, _| current.contains(identity)); - self.cache - .retain(|id, _| rows.iter().any(|row| &row.id == id)); - rows - } - - fn discover(&mut self, sessions: &PtyManager, rows: &[RemoteSessionRow]) -> Vec { - let snapshot = self.source.sample(); - let processes: Vec<_> = snapshot - .processes - .iter() - .map(|process| process.to_record()) - .collect(); - let roots: Vec<_> = rows - .iter() - .filter_map(|row| { - let pid = sessions.pid(&row.id)?; - let process = processes.iter().find(|process| process.pid == pid)?; - Some(KnownProcessRoot { - pid, - started_at_secs: process.started_at_secs, - origin: AgentOrigin::Session { id: row.id.clone() }, - }) - }) - .collect(); - discover_agents( - &processes, - &roots, - std::process::id(), - (medulla::clock::now_millis().max(0) as u64) / 1000, - ) - } - - fn record(&mut self, session_id: &str, agent: &AgentProcess) { - let Some(pid) = agent.pid else { - return; - }; - let history = self - .history - .entry((pid, agent.started_at_secs)) - .or_default(); - history.push(f64::from(agent.usage.cpu_percent)); - if history.len() > CPU_HISTORY { - history.remove(0); - } - self.cache.insert( - session_id.to_owned(), - AgentUsage { - kind: agent.kind.label().to_owned(), - pid, - cpu: f64::from(agent.usage.cpu_percent), - rss: agent.usage.rss_bytes, - threads: agent.usage.threads as usize, - started_at: agent.started_at_secs, - cpu_history: history.clone(), - }, - ); - } -} - -pub(super) fn classified_session_agent<'a>( - agents: &'a [AgentProcess], - session_id: &str, -) -> Option<&'a AgentProcess> { - agents.iter().find(|agent| { - agent.origin - == (AgentOrigin::Session { - id: session_id.to_owned(), - }) - }) -} diff --git a/src/tui/src/ui/app/render/resources/agents/command.rs b/src/tui/src/ui/app/render/resources/agents/command.rs deleted file mode 100644 index b04264db4..000000000 --- a/src/tui/src/ui/app/render/resources/agents/command.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! A process command line as the signal prompt shows it, with secrets redacted. - -use super::*; - -pub(super) fn display_command(process: &ProcessSnapshot) -> String { - let mut rendered = Vec::new(); - let mut redact_next = false; - for argument in process - .cmd - .iter() - .filter(|arg| !is_environment_assignment(arg)) - { - if redact_next { - redact_next = false; - continue; - } - if let Some((key, _)) = argument.split_once('=') { - if argument.starts_with('-') && is_secret_name(key) { - rendered.push(format!("{key}=[REDACTED]")); - continue; - } - } - if argument.starts_with('-') && is_secret_name(argument) { - rendered.push(format!("{argument}=[REDACTED]")); - redact_next = !argument.contains('='); - } else { - rendered.push(argument.clone()); - } - } - if rendered.is_empty() { - rendered.push( - process - .exe - .as_deref() - .map(std::path::Path::new) - .and_then(std::path::Path::file_name) - .and_then(|name| name.to_str()) - .unwrap_or("unavailable") - .to_owned(), - ); - } - let command = rendered.join(" "); - const LIMIT: usize = 72; - if command.len() <= LIMIT { - return command; - } - let mut end = LIMIT.saturating_sub(1); - while !command.is_char_boundary(end) { - end -= 1; - } - format!("{}…", &command[..end]) -} - -pub(super) fn is_environment_assignment(argument: &str) -> bool { - let Some((name, _)) = argument.split_once('=') else { - return false; - }; - !name.is_empty() - && !argument.starts_with('-') - && name - .chars() - .all(|character| character.is_ascii_alphanumeric() || character == '_') -} - -pub(super) fn is_secret_name(name: &str) -> bool { - let name = name.trim_start_matches('-').to_ascii_lowercase(); - [ - "token", - "secret", - "password", - "passwd", - "api-key", - "apikey", - "auth", - "credential", - ] - .iter() - .any(|secret| name.contains(secret)) -} diff --git a/src/tui/src/ui/app/render/resources/agents/mod.rs b/src/tui/src/ui/app/render/resources/agents/mod.rs deleted file mode 100644 index f88b6b4ba..000000000 --- a/src/tui/src/ui/app/render/resources/agents/mod.rs +++ /dev/null @@ -1,432 +0,0 @@ -//! The Agents box: every coding-agent process on this host and on each -//! connected remote host, as a btop-style process table. - -use std::cmp::Ordering; - -use crate::ui::resources::sampler::{ProcessSnapshot, ResourceSnapshot}; -use medulla::protocol::HarnessProvider; -use ratatui::{ - layout::Rect, - style::{Color, Modifier, Style}, - text::{Line, Span}, - widgets::{Block, BorderType, Borders, Cell, Clear, Paragraph, Row, Table, Wrap}, - Frame, -}; - -use crate::ui::app::resources::chrome::{self, Bar}; -use crate::ui::app::resources::types::{AgentSignal, AgentSort, ResourcesState}; -use crate::ui::theme::ResourcesTheme; - -mod command; -mod rows; -#[cfg(test)] -mod tests; -mod types; - -use command::display_command; -use rows::kind_counts; -pub(in crate::ui::app) use rows::{rows, visible_rows_with_remote}; -pub(in crate::ui::app) use types::AgentRow; - -pub(in crate::ui::app) fn draw_agents( - frame: &mut Frame, - rect: Rect, - snapshot: &ResourceSnapshot, - remote_hosts: &[(String, Vec)], - state: &mut ResourcesState, - theme: &ResourcesTheme, -) { - let rows = visible_rows_with_remote(snapshot, remote_hosts, state); - if let Some(following) = state.agent_follow.clone() { - if !snapshot.processes.iter().any(|process| { - (process.pid, process.start_time) == (following.pid, following.started) - && following.host.is_none() - }) { - state.agent_follow = None; - if state.agent_selected.as_ref() == Some(&following) { - state.agent_selected = None; - } - } else if rows.iter().any(|row| row.identity() == following) { - state.agent_selected = Some(following.clone()); - } - } - let now = std::time::Instant::now(); - let sample_due = state - .agent_last_sample - .is_none_or(|last| now.duration_since(last).as_millis() >= u128::from(state.interval_ms)); - let current: std::collections::HashSet<_> = rows.iter().map(AgentRow::identity).collect(); - state - .agent_cpu_history - .retain(|identity, _| current.contains(identity)); - if sample_due { - for row in &rows { - let history = state.agent_cpu_history.entry(row.identity()).or_default(); - history.push(row.cpu); - if history.len() > 24 { - history.remove(0); - } - } - state.agent_last_sample = Some(now); - } - let area = draw_chrome(frame, rect, &rows, state, theme); - if area.is_empty() { - return; - } - if state.agent_detail { - super::agents_detail::draw( - frame, - area, - rows.iter() - .find(|r| Some(r.identity()) == state.agent_selected), - theme, - ); - draw_signal_confirmation(frame, area, snapshot, state, theme); - return; - } - let selected = state.agent_selected.clone(); - let compact = area.width < 88; - let header = if compact { - Row::new(["Pid:", "Agent / Origin:", "Cpu%", "MemB", "Run"]) - } else { - Row::new([ - "Pid:", - "Agent:", - "Origin:", - "Workspace:", - "Th:", - "MemB", - "Cpu%", - "", - "Runtime", - ]) - }; - let main = Style::default().fg(theme.main_fg); - let dim = Style::default().fg(theme.inactive_fg); - let agent_table_rows: Vec = rows - .iter() - .map(|row| { - let history = state.agent_cpu_history.get(&row.identity()); - let graph = history - .map(|history| mini_graph(history)) - .unwrap_or_default(); - let cpu = Style::default().fg(chrome::shade(&theme.process, row.cpu)); - let workspace = shorten(&row.workspace, if compact { 18 } else { 25 }); - let origin = if row.external { - "external".to_owned() - } else { - row.origin.clone() - }; - let tree = format!( - "{}{}", - " ".repeat(row.depth), - if row.depth > 0 { "└─ " } else { "" } - ); - let cells: Vec = if compact { - vec![ - Cell::from(row.pid.to_string()).style(dim), - Cell::from(Line::from(vec![ - Span::styled(tree, dim), - Span::styled(row.kind.clone(), main.add_modifier(Modifier::BOLD)), - Span::styled(format!(" · {origin}"), main), - ])), - Cell::from(format!("{:>5.1}", row.cpu)).style(cpu), - Cell::from(format!("{:>6}", bytes(row.memory))).style(main), - Cell::from(duration(row.runtime)).style(main), - ] - } else { - vec![ - Cell::from(row.pid.to_string()).style(dim), - Cell::from(Line::from(vec![ - Span::styled(tree, dim), - Span::styled(row.kind.clone(), main.add_modifier(Modifier::BOLD)), - ])), - Cell::from(origin).style(if row.external { dim } else { main }), - Cell::from(workspace).style(main), - Cell::from(format!("{:>3}", row.threads)).style(main), - Cell::from(format!("{:>6}", bytes(row.memory))).style(main), - Cell::from(format!("{:>5.1}", row.cpu)).style(cpu), - Cell::from(graph).style(cpu), - Cell::from(format!("{:>7}", duration(row.runtime))).style(main), - ] - }; - let mut item = Row::new(cells); - if Some(row.identity()) == selected { - item = item.style( - Style::default() - .bg(theme.selected_bg) - .fg(theme.selected_fg) - .add_modifier(Modifier::BOLD), - ); - } - item - }) - .collect(); - let mut table_rows = Vec::new(); - let mut display_indices = Vec::with_capacity(rows.len()); - let mut last_remote_host: Option<&str> = None; - for (row, item) in rows.iter().zip(agent_table_rows) { - if let Some(host) = row.host.as_deref() { - if last_remote_host != Some(host) { - table_rows.push(Row::new(vec![ - Cell::from("Remote").style(Style::default().fg(theme.hi_fg)), - Cell::from(host.to_owned()).style( - Style::default() - .fg(theme.title) - .add_modifier(Modifier::BOLD), - ), - ])); - } - last_remote_host = Some(host); - } else { - last_remote_host = None; - } - display_indices.push(table_rows.len()); - table_rows.push(item); - } - let widths = if compact { - vec![ - ratatui::layout::Constraint::Length(7), - ratatui::layout::Constraint::Min(17), - ratatui::layout::Constraint::Length(5), - ratatui::layout::Constraint::Length(6), - ratatui::layout::Constraint::Length(5), - ] - } else { - vec![ - ratatui::layout::Constraint::Length(7), - ratatui::layout::Constraint::Length(13), - ratatui::layout::Constraint::Length(13), - ratatui::layout::Constraint::Min(12), - ratatui::layout::Constraint::Length(3), - ratatui::layout::Constraint::Length(6), - ratatui::layout::Constraint::Length(5), - ratatui::layout::Constraint::Length(8), - ratatui::layout::Constraint::Length(7), - ] - }; - let table = Table::new(table_rows, widths).header( - header.style( - Style::default() - .fg(theme.title) - .add_modifier(Modifier::BOLD), - ), - ); - let selected_index = selected.as_ref().and_then(|identity| { - rows.iter() - .position(|row| row.identity() == *identity) - .map(|index| display_indices[index]) - }); - let mut table_state = ratatui::widgets::TableState::default(); - table_state.select(selected_index); - frame.render_stateful_widget(table, area, &mut table_state); - if rows.is_empty() { - let message = if state.agent_filter.is_some() { - "No agents match the filter" - } else { - "No agent processes running" - }; - chrome::text( - frame.buffer_mut(), - area.x + 1, - area.y + 2.min(area.height.saturating_sub(1)), - area.width.saturating_sub(2), - message, - dim, - ); - } - draw_signal_confirmation(frame, area, snapshot, state, theme); -} - -/// Draw the Agents frame and its tags, and return the area inside it. -pub(super) fn draw_chrome( - frame: &mut Frame, - rect: Rect, - rows: &[AgentRow], - state: &mut ResourcesState, - theme: &ResourcesTheme, -) -> Rect { - let buffer = frame.buffer_mut(); - let area = chrome::frame(buffer, rect, theme.proc_box); - let mut top = Bar::top(rect, theme.proc_box); - state.hits.agents_toggle = top.left(buffer, &chrome::numbered(theme, 4, "agents")); - let filter = match (&state.agent_filter, state.agent_filter_editing) { - (filter, true) => { - let mut spans = chrome::keyed(theme, "f ", 'f', true); - spans.push(Span::styled( - format!("{}█", filter.as_deref().unwrap_or_default()), - Style::default().fg(theme.title), - )); - spans - } - (Some(filter), false) => { - let mut spans = chrome::keyed(theme, "f ", 'f', true); - spans.push(Span::styled( - filter.clone(), - Style::default().fg(theme.title), - )); - spans - } - (None, false) => chrome::keyed(theme, "filter", 'f', false), - }; - top.left(buffer, &filter); - // Following changes what the selection does, so it outranks the sort - // and view toggles when the border runs out of room. - if let Some(following) = &state.agent_follow { - top.right( - buffer, - &chrome::keyed(theme, &format!("Follow {}", following.pid), 'F', true), - ); - } - top.right( - buffer, - &chrome::stepper(theme, "←", sort_label(state.agent_sort), "→"), - ); - top.right(buffer, &chrome::keyed(theme, "tree", 'e', state.agent_tree)); - top.right( - buffer, - &chrome::keyed(theme, "reverse", 'r', state.agent_reverse), - ); - - let mut bottom = Bar::bottom(rect, theme.proc_box); - let selected = state.agent_selected.is_some(); - bottom.left(buffer, &chrome::stepper(theme, "↑", "select", "↓")); - bottom.left(buffer, &chrome::keyed(theme, "info ↵", '↵', selected)); - bottom.left(buffer, &chrome::keyed(theme, "terminate", 't', selected)); - bottom.left(buffer, &chrome::keyed(theme, "kill", 'k', selected)); - bottom.left(buffer, &chrome::keyed(theme, "stop", 's', selected)); - let position = state - .agent_selected - .as_ref() - .and_then(|identity| rows.iter().position(|row| row.identity() == *identity)) - .map_or(0, |index| index + 1); - bottom.right( - buffer, - &chrome::plain(theme, &format!("{position}/{}", rows.len())), - ); - let summary = format!( - "{} · cpu {:.1}% · {}", - kind_counts(rows), - rows.iter().map(|r| r.cpu).sum::(), - bytes(rows.iter().map(|r| r.memory).sum::()) - ); - if !rows.is_empty() { - top.center(buffer, &chrome::plain(theme, &summary)); - } - area -} - -pub(super) fn sort_label(sort: AgentSort) -> &'static str { - match sort { - AgentSort::Pid => "pid", - AgentSort::Kind => "agent", - AgentSort::Origin => "origin", - AgentSort::Workspace => "workspace", - AgentSort::Threads => "threads", - AgentSort::Memory => "memory", - AgentSort::Cpu => "cpu", - AgentSort::Runtime => "runtime", - } -} - -pub(super) fn draw_signal_confirmation( - frame: &mut Frame, - area: Rect, - snapshot: &ResourceSnapshot, - state: &ResourcesState, - theme: &ResourcesTheme, -) { - let Some(armed) = state.agent_signal_armed else { - return; - }; - let row = rows(snapshot) - .into_iter() - .find(|row| row.pid == armed.pid && row.started == armed.started); - let process = snapshot - .processes - .iter() - .find(|process| process.pid == armed.pid && process.start_time == armed.started); - let kind = row.as_ref().map_or("Unknown", |row| row.kind.as_str()); - let origin = row.as_ref().map_or("external", |row| row.origin.as_str()); - let command = process.map_or_else(|| "unavailable".into(), display_command); - let signal = match armed.signal { - AgentSignal::Terminate => "terminate", - AgentSignal::Kill => "kill", - AgentSignal::Stop => "stop", - }; - let external = row.as_ref().is_some_and(|row| row.external); - let instruction = match (external, armed.stage) { - (true, crate::ui::app::resources::types::AgentSignalConfirmStage::First) => { - "Press y for the second confirmation; Esc cancels" - } - (true, crate::ui::app::resources::types::AgentSignalConfirmStage::ExternalSecond) => { - "External target: press uppercase Y to send; Esc cancels" - } - (false, _) => "Press y to send; Esc cancels", - }; - let prompt = format!( - "Kind: {kind}\nPID: {}\nCommand: {command}\nOrigin: {origin}\nSignal: {signal}\nTarget host: local\n\n{instruction}", - armed.pid - ); - let popup = Rect::new( - area.x.saturating_add(1), - area.y.saturating_add(1), - area.width.saturating_sub(2), - area.height.saturating_sub(2).min(10), - ); - frame.render_widget(Clear, popup); - chrome::fill(frame.buffer_mut(), popup, theme.main_bg); - frame.render_widget( - Paragraph::new(prompt).wrap(Wrap { trim: true }).block( - Block::default() - .borders(Borders::ALL) - .border_type(BorderType::Rounded) - .title(if external { - " EXTERNAL PROCESS · Confirm signal " - } else { - " Confirm process signal " - }) - .style( - Style::default() - .fg(Color::Yellow) - .add_modifier(Modifier::BOLD), - ), - ), - popup, - ); -} - -pub(super) fn bytes(value: u64) -> String { - if value >= 1 << 30 { - format!("{:.1}G", value as f64 / (1u64 << 30) as f64) - } else if value >= 1 << 20 { - format!("{:.0}M", value as f64 / (1u64 << 20) as f64) - } else { - format!("{}K", value / 1024) - } -} -pub(super) fn duration(seconds: u64) -> String { - if seconds >= 3600 { - format!("{}h", seconds / 3600) - } else if seconds >= 60 { - format!("{}m", seconds / 60) - } else { - format!("{}s", seconds) - } -} -pub(super) fn shorten(value: &str, max: usize) -> String { - let chars: Vec = value.chars().collect(); - if chars.len() <= max { - value.to_owned() - } else { - format!( - "…{}", - chars[chars.len().saturating_sub(max.saturating_sub(1))..] - .iter() - .collect::() - ) - } -} -pub(super) fn mini_graph(values: &[f64]) -> String { - let values: Vec = values.iter().map(|value| *value as f32).collect(); - crate::ui::plot::sparkline(&values, 8) -} diff --git a/src/tui/src/ui/app/render/resources/agents/rows.rs b/src/tui/src/ui/app/render/resources/agents/rows.rs deleted file mode 100644 index aed28581e..000000000 --- a/src/tui/src/ui/app/render/resources/agents/rows.rs +++ /dev/null @@ -1,341 +0,0 @@ -//! The Agents table's rows: which processes are agents, and how the operator's -//! filter, sort, and tree settings arrange them. - -use super::*; - -/// One row per harness on this machine: the SDK's classifier picks each -/// harness's root process, and the row carries the whole tree's usage. -/// -/// Classification goes by the program a process is — its executable or the -/// name it was launched as — never by a substring of its path or arguments, -/// so an editor installed under `Cursor.app` or an MCP server started with -/// `--claude` stays out of the list. -pub(in crate::ui::app) fn rows(snapshot: &ResourceSnapshot) -> Vec { - use medulla::resources::agents::{discover_registered_agents, AgentOrigin}; - - let registrations = medulla::resources::launch::agent_registry().snapshot(); - let records: Vec<_> = snapshot - .processes - .iter() - .map(ProcessSnapshot::to_record) - .collect(); - let medulla_pid = std::process::id(); - let now_secs = medulla::clock::now_millis().max(0) as u64 / 1000; - let process = |pid: u32| snapshot.processes.iter().find(|process| process.pid == pid); - let mut rows: Vec = - discover_registered_agents(&records, medulla_pid, now_secs, Default::default()) - .into_iter() - .map(|agent| { - let pid = agent.pid.unwrap_or(medulla_pid); - let registered = registrations.iter().find(|entry| { - entry.pid == pid && entry.started_at_secs == agent.started_at_secs - }); - let kind = registered - .map(|entry| pretty_kind(&entry.provider)) - .unwrap_or_else(|| agent.kind.label().into()); - let (origin, session_id, task_id, external) = match agent.origin { - AgentOrigin::Session { id } => ( - id.clone(), - Some(id), - registered.and_then(|entry| entry.task_id.clone()), - false, - ), - AgentOrigin::Task { id } => (format!("task {id}"), None, Some(id), false), - AgentOrigin::Headless => ("host".into(), None, None, false), - AgentOrigin::Remote { host } => { - (format!("Remote{{{host}}}"), None, None, false) - } - AgentOrigin::External => ("external".into(), None, None, true), - }; - AgentRow { - host: None, - pid, - started: agent.started_at_secs, - kind, - origin, - workspace: agent - .cwd - .map(|cwd| cwd.to_string_lossy().into_owned()) - .unwrap_or_else(|| "—".into()), - threads: agent.usage.threads as usize, - memory: agent.usage.rss_bytes, - cpu: f64::from(agent.usage.cpu_percent), - runtime: agent.runtime_secs, - ppid: process(pid).and_then(|process| process.ppid), - session_id, - task_id, - external, - remote: false, - depth: 0, - } - }) - .collect(); - // A session Medulla launched stays listed even when its program is one - // the classifier does not know, such as a custom harness. - for entry in ®istrations { - let owned = rows.iter().any(|row| { - row.pid == entry.pid - || (entry.session_id.is_some() && row.session_id == entry.session_id) - || (entry.task_id.is_some() && row.task_id == entry.task_id) - }); - let Some(process) = process(entry.pid).filter(|p| p.start_time == entry.started_at_secs) - else { - continue; - }; - if owned { - continue; - } - let origin = match (&entry.session_id, &entry.task_id) { - (Some(id), _) => id.clone(), - (None, Some(id)) => format!("task {id}"), - (None, None) => "host".into(), - }; - rows.push(AgentRow { - host: None, - pid: process.pid, - started: process.start_time, - kind: pretty_kind(&entry.provider), - origin, - workspace: process.cwd.clone().unwrap_or_else(|| "—".into()), - threads: process.threads, - memory: process.memory_bytes, - cpu: process.cpu_percent, - runtime: now_secs.saturating_sub(process.start_time), - ppid: process.ppid, - session_id: entry.session_id.clone(), - task_id: entry.task_id.clone(), - external: false, - remote: false, - depth: 0, - }); - } - for row in &mut rows { - row.remote = row.session_id.as_deref().is_some_and(|id| { - matches!( - crate::ui::app::remote_sessions::SessionRef::parse(id), - crate::ui::app::remote_sessions::SessionRef::Remote { .. } - ) - }); - } - rows.sort_by_key(|row| row.pid); - rows -} - -pub(super) fn pretty_kind(provider: &str) -> String { - match HarnessProvider::from_wire(provider) { - Some(HarnessProvider::Claude) => "Claude".into(), - Some(HarnessProvider::Codex) => "Codex".into(), - Some(HarnessProvider::Opencode) => "OpenCode".into(), - Some(HarnessProvider::Openhuman) => "OpenHuman".into(), - Some(_) => provider.to_owned(), - None if provider.to_lowercase().contains("openhuman") => "OpenHuman".into(), - None if provider.to_lowercase().contains("codex-acp") => "Codex-ACP".into(), - None if provider.to_lowercase().contains("claude") => "Claude".into(), - None => provider.to_owned(), - } -} - -pub(in crate::ui::app) fn visible_rows( - snapshot: &ResourceSnapshot, - state: &ResourcesState, -) -> Vec { - let mut rows = rows(snapshot); - if let Some(filter) = state.agent_filter.as_deref() { - let (regex, pattern) = filter - .strip_prefix('!') - .map_or((false, filter), |pattern| (true, pattern)); - if regex { - if let Ok(pattern) = regex::Regex::new(&format!("(?i){pattern}")) { - rows.retain(|row| pattern.is_match(&row.kind)); - } else { - rows.clear(); - } - } else { - let pattern = pattern.to_lowercase(); - rows.retain(|row| { - format!("{} {} {} {}", row.pid, row.kind, row.origin, row.workspace) - .to_lowercase() - .contains(&pattern) - }); - } - } - rows.sort_by(|a, b| compare(a, b, state.agent_sort)); - if state.agent_reverse { - rows.reverse(); - } - if state.agent_tree { - rows = tree_rows(snapshot, rows); - } - rows -} - -pub(in crate::ui::app) fn visible_rows_with_remote( - snapshot: &ResourceSnapshot, - remote_hosts: &[(String, Vec)], - state: &ResourcesState, -) -> Vec { - let mut rows = visible_rows(snapshot, state); - let mut hosts: Vec<_> = remote_hosts.iter().collect(); - hosts.sort_by(|(a, _), (b, _)| a.cmp(b)); - for (host, sessions) in hosts { - let mut host_rows = Vec::new(); - for session in sessions { - let Some(usage) = &session.usage else { - continue; - }; - let row = AgentRow { - host: Some(host.clone()), - pid: usage.pid, - started: usage.started_at, - kind: usage.kind.clone(), - origin: format!("Remote{{{host}}}"), - workspace: session.cwd.clone(), - threads: usage.threads, - memory: usage.rss, - cpu: usage.cpu, - runtime: (medulla::clock::now_millis() - - usage.started_at.saturating_mul(1000) as i64) - .max(0) as u64 - / 1000, - ppid: None, - session_id: Some(crate::ui::app::remote_sessions::qualify(host, &session.id)), - task_id: None, - external: false, - remote: true, - depth: 0, - }; - if matches_filter(&row, state.agent_filter.as_deref()) { - host_rows.push(row); - } - } - host_rows.sort_by(|a, b| compare(a, b, state.agent_sort)); - if state.agent_reverse { - host_rows.reverse(); - } - rows.extend(host_rows); - } - rows -} - -pub(super) fn matches_filter(row: &AgentRow, filter: Option<&str>) -> bool { - let Some(filter) = filter else { return true }; - let (regex, pattern) = filter - .strip_prefix('!') - .map_or((false, filter), |pattern| (true, pattern)); - if regex { - regex::Regex::new(&format!("(?i){pattern}")) - .is_ok_and(|pattern| pattern.is_match(&row.kind)) - } else { - format!("{} {} {} {}", row.pid, row.kind, row.origin, row.workspace) - .to_lowercase() - .contains(&pattern.to_lowercase()) - } -} - -pub(super) fn tree_rows(snapshot: &ResourceSnapshot, agents: Vec) -> Vec { - let all_agents: std::collections::HashMap = - agents.iter().cloned().map(|row| (row.pid, row)).collect(); - let mut children: std::collections::HashMap> = - std::collections::HashMap::new(); - for process in &snapshot.processes { - if let Some(parent) = process.ppid { - children.entry(parent).or_default().push(process); - } - } - for descendants in children.values_mut() { - descendants.sort_by_key(|process| process.pid); - } - let roots: Vec = agents - .iter() - .filter(|row| { - row.ppid - .is_none_or(|parent| !all_agents.contains_key(&parent)) - }) - .cloned() - .collect(); - let mut result = Vec::new(); - let mut visited = std::collections::HashSet::new(); - for root in roots { - let pid = root.pid; - visited.insert(pid); - result.push(root); - append_children(pid, 1, &children, &all_agents, &mut visited, &mut result); - } - // Cycles or incomplete parent chains should not make a known agent vanish. - for row in agents { - if visited.insert(row.pid) { - result.push(row); - } - } - result -} - -pub(super) fn append_children( - parent: u32, - depth: usize, - children: &std::collections::HashMap>, - agents: &std::collections::HashMap, - visited: &mut std::collections::HashSet, - result: &mut Vec, -) { - if let Some(descendants) = children.get(&parent) { - for process in descendants { - if !visited.insert(process.pid) { - continue; - } - let mut row = agents - .get(&process.pid) - .cloned() - .unwrap_or_else(|| AgentRow { - host: None, - pid: process.pid, - started: process.start_time, - kind: "Process".into(), - origin: "child process".into(), - workspace: process.cwd.clone().unwrap_or_else(|| "—".into()), - threads: process.threads, - memory: process.memory_bytes, - cpu: process.cpu_percent, - runtime: (medulla::clock::now_millis() - - process.start_time.saturating_mul(1000) as i64) - .max(0) as u64 - / 1000, - ppid: process.ppid, - session_id: None, - task_id: None, - external: true, - remote: false, - depth, - }); - row.depth = depth; - let pid = row.pid; - result.push(row); - append_children(pid, depth + 1, children, agents, visited, result); - } - } -} - -pub(super) fn compare(a: &AgentRow, b: &AgentRow, key: AgentSort) -> Ordering { - match key { - AgentSort::Pid => a.pid.cmp(&b.pid), - AgentSort::Kind => a.kind.cmp(&b.kind), - AgentSort::Origin => a.origin.cmp(&b.origin), - AgentSort::Workspace => a.workspace.cmp(&b.workspace), - AgentSort::Threads => a.threads.cmp(&b.threads), - AgentSort::Memory => a.memory.cmp(&b.memory), - AgentSort::Cpu => a.cpu.total_cmp(&b.cpu), - AgentSort::Runtime => a.runtime.cmp(&b.runtime), - } -} - -pub(super) fn kind_counts(rows: &[AgentRow]) -> String { - let mut counts = std::collections::BTreeMap::new(); - for row in rows { - *counts.entry(row.kind.as_str()).or_insert(0usize) += 1; - } - counts - .into_iter() - .map(|(kind, count)| format!("{kind} {count}")) - .collect::>() - .join(" · ") -} diff --git a/src/tui/src/ui/app/render/resources/agents/tests.rs b/src/tui/src/ui/app/render/resources/agents/tests.rs deleted file mode 100644 index 8562f0f02..000000000 --- a/src/tui/src/ui/app/render/resources/agents/tests.rs +++ /dev/null @@ -1,410 +0,0 @@ -//! Unit tests for the Agents table. - -use super::rows::{compare, visible_rows}; -use super::*; -use crate::ui::app::resources::types::ResourcesState; - -fn process(pid: u32, command: &str, cpu: f64, mem: u64) -> ProcessSnapshot { - ProcessSnapshot { - pid, - ppid: None, - exe: Some(command.into()), - cmd: vec![command.into()], - cwd: Some(format!("/workspace/{command}")), - start_time: 100, - owner_uid: None, - cpu_percent: cpu, - memory_bytes: mem, - disk_read_bytes: 0, - disk_written_bytes: 0, - threads: pid as usize, - } -} -fn snapshot() -> ResourceSnapshot { - ResourceSnapshot::default().with_processes(vec![ - process(10, "claude", 10.0, 4000), - process(20, "codex-acp", 20.0, 3000), - process(30, "openhuman", 30.0, 2000), - process(40, "aider", 40.0, 1000), - ]) -} - -#[test] -fn remote_agents_render_beneath_each_host_heading() { - let row = |id: &str, kind: &str, pid| medulla::protocol::RemoteSessionRow { - id: id.into(), - label: kind.into(), - provider: kind.to_lowercase(), - preset: None, - state: medulla::protocol::RemoteSessionState::Running, - cwd: "/work".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: true, - working: true, - attention: None, - bracketed_paste: false, - last_error: None, - usage: Some(medulla::protocol::AgentUsage { - kind: kind.into(), - pid, - cpu: 1.0, - rss: 1024, - threads: 2, - started_at: 1_700_000_000, - cpu_history: vec![0.5, 1.0], - }), - }; - let remote_hosts = vec![ - ("alpha".into(), vec![row("w_a", "Claude", 101)]), - ("beta".into(), vec![row("w_b", "Codex", 202)]), - ]; - let backend = ratatui::backend::TestBackend::new(120, 18); - let mut terminal = ratatui::Terminal::new(backend).unwrap(); - let mut state = ResourcesState::default(); - terminal - .draw(|frame| { - draw_agents( - frame, - frame.area(), - &ResourceSnapshot::default(), - &remote_hosts, - &mut state, - &ResourcesTheme::default(), - ) - }) - .unwrap(); - let buffer = terminal.backend().buffer(); - let rendered = (0..buffer.area.height) - .map(|y| { - (0..buffer.area.width) - .map(|x| buffer[(x, y)].symbol()) - .collect::() - }) - .collect::>() - .join("\n"); - for expected in [ - "Remote", - "alpha", - "Remote{alpha}", - "Claude", - "beta", - "Remote{beta}", - "Codex", - ] { - assert!( - rendered.contains(expected), - "missing {expected:?}:\n{rendered}" - ); - } - assert_eq!( - rendered.matches("alpha").count(), - 2, - "alpha heading and row:\n{rendered}" - ); - assert_eq!( - rendered.matches("beta").count(), - 2, - "beta heading and row:\n{rendered}" - ); - assert!(rendered.find("alpha").unwrap() < rendered.find("beta").unwrap()); -} - -#[test] -fn remote_host_groups_preserve_local_agent_tree_order() { - let mut parent = process(100, "claude", 1.0, 100); - parent.ppid = None; - let mut child = process(50, "codex-acp", 2.0, 200); - child.ppid = Some(100); - let snapshot = ResourceSnapshot::default().with_processes(vec![parent, child]); - let remote = |id: &str, kind: &str, pid| medulla::protocol::RemoteSessionRow { - id: id.into(), - label: kind.into(), - provider: kind.to_lowercase(), - preset: None, - state: medulla::protocol::RemoteSessionState::Running, - cwd: "/work".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: false, - working: false, - attention: None, - bracketed_paste: false, - last_error: None, - usage: Some(medulla::protocol::AgentUsage { - kind: kind.into(), - pid, - cpu: pid as f64, - rss: 1_024, - threads: 1, - started_at: 1_700_000_000, - cpu_history: vec![], - }), - }; - // Deliberately pass hosts and rows out of display order. Remote hosts - // group by host, but local tree order is kept exactly as discovered. - let hosts = vec![ - ("beta".into(), vec![remote("b", "Beta", 1)]), - ( - "alpha".into(), - vec![remote("a2", "Alpha", 999), remote("a1", "Alpha", 2)], - ), - ]; - let state = ResourcesState { - agent_tree: true, - ..ResourcesState::default() - }; - let rows = visible_rows_with_remote(&snapshot, &hosts, &state); - assert_eq!( - rows.iter() - .map(|row| (row.host.as_deref(), row.pid)) - .collect::>(), - [ - (None, 100), - (None, 50), - (Some("alpha"), 2), - (Some("alpha"), 999), - (Some("beta"), 1) - ], - ); -} - -#[test] -fn remote_agents_share_regex_filter_semantics_and_have_host_scoped_identity() { - let row = |id: &str, kind: &str, pid| medulla::protocol::RemoteSessionRow { - id: id.into(), - label: kind.into(), - provider: kind.to_lowercase(), - preset: None, - state: medulla::protocol::RemoteSessionState::Running, - cwd: "/work".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: false, - working: false, - attention: None, - bracketed_paste: false, - last_error: None, - usage: Some(medulla::protocol::AgentUsage { - kind: kind.into(), - pid, - cpu: 1.0, - rss: 1_024, - threads: 2, - started_at: 1_700_000_000, - cpu_history: vec![], - }), - }; - let hosts = vec![ - ("alpha".into(), vec![row("w_same", "Claude", 55)]), - ("beta".into(), vec![row("w_same", "Codex", 55)]), - ]; - let state = ResourcesState { - agent_filter: Some("!^cod".into()), - ..ResourcesState::default() - }; - let rows = visible_rows_with_remote(&ResourceSnapshot::default(), &hosts, &state); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].kind, "Codex"); - assert_eq!(rows[0].host.as_deref(), Some("beta")); - assert_eq!(rows[0].session_id.as_deref(), Some("beta/w_same")); -} - -#[test] -fn classifies_known_and_external_agent_processes() { - let rows = rows(&snapshot()); - assert_eq!( - rows.iter().map(|row| row.kind.as_str()).collect::>(), - ["Claude", "Codex-ACP", "OpenHuman", "Aider"] - ); - assert_eq!( - rows.iter() - .map(|row| row.origin.as_str()) - .collect::>(), - ["external", "external", "external", "external"] - ); -} - -#[test] -fn unregistered_bare_codex_process_is_named_codex_with_an_external_origin() { - let rows = - rows(&ResourceSnapshot::default().with_processes(vec![process(987_105, "codex", 0.0, 1)])); - assert_eq!(rows.len(), 1, "the harness-named process must be visible"); - assert_eq!(rows[0].kind, "Codex"); - assert_eq!(rows[0].origin, "external"); -} - -#[test] -fn registry_classifies_session_task_and_host_origins() { - let registry = medulla::resources::launch::agent_registry(); - let registrations = [ - medulla::resources::launch::AgentRegistration { - pid: 987_101, - started_at_secs: 100, - task_id: None, - session_id: Some("session-label".into()), - provider: "claude".into(), - }, - medulla::resources::launch::AgentRegistration { - pid: 987_102, - started_at_secs: 100, - task_id: Some("task-7".into()), - session_id: None, - provider: "codex-acp".into(), - }, - medulla::resources::launch::AgentRegistration { - pid: 987_103, - started_at_secs: 100, - task_id: None, - session_id: None, - provider: "openhuman".into(), - }, - ]; - let _guards: Vec<_> = registrations - .iter() - .cloned() - .map(|registration| registry.register_at(registration)) - .collect(); - let snapshot = ResourceSnapshot::default().with_processes(vec![ - process(987_101, "claude", 1.0, 1), - process(987_102, "codex-acp", 2.0, 2), - process(987_103, "openhuman", 3.0, 3), - process(987_104, "aider", 4.0, 4), - ]); - let rows = rows(&snapshot); - assert_eq!( - rows.iter() - .map(|row| row.origin.as_str()) - .collect::>(), - ["session-label", "task task-7", "host", "external"] - ); - assert_eq!( - rows.iter().map(|row| row.kind.as_str()).collect::>(), - ["Claude", "Codex-ACP", "OpenHuman", "Aider"] - ); -} - -#[test] -fn tree_mode_nests_child_processes_under_agent_rows() { - let snapshot = ResourceSnapshot::default().with_processes(vec![ - process(10, "claude", 10.0, 4000), - ProcessSnapshot { - pid: 11, - ppid: Some(10), - exe: Some("node".into()), - cmd: vec!["node".into()], - cwd: Some("/work".into()), - start_time: 101, - owner_uid: None, - cpu_percent: 2.0, - memory_bytes: 512, - disk_read_bytes: 0, - disk_written_bytes: 0, - threads: 1, - }, - ]); - let state = ResourcesState { - agent_tree: true, - ..ResourcesState::default() - }; - let rows = visible_rows(&snapshot, &state); - assert_eq!( - rows.iter() - .map(|row| (&*row.kind, row.depth)) - .collect::>(), - [("Claude", 0), ("Process", 1)] - ); -} - -#[test] -fn sorts_each_column_reverses_and_filters_codex_by_regex() { - let snap = snapshot(); - let mut state = ResourcesState::default(); - for sort in [ - AgentSort::Pid, - AgentSort::Kind, - AgentSort::Origin, - AgentSort::Workspace, - AgentSort::Threads, - AgentSort::Memory, - AgentSort::Cpu, - AgentSort::Runtime, - ] { - state.agent_sort = sort; - let sorted = visible_rows(&snap, &state); - assert_eq!(sorted.len(), 4); - assert!(sorted - .windows(2) - .all(|w| compare(&w[0], &w[1], sort) != Ordering::Greater)); - } - state.agent_sort = AgentSort::Cpu; - state.agent_reverse = true; - assert_eq!(visible_rows(&snap, &state)[0].pid, 40); - state.agent_reverse = false; - state.agent_filter = Some("!^cod".into()); - assert_eq!( - visible_rows(&snap, &state) - .iter() - .map(|r| r.kind.as_str()) - .collect::>(), - ["Codex-ACP"] - ); -} - -/// The process table a Mac running Cursor, Claude Code and the Codex app -/// actually has: only the two harnesses are rows, each named for what it is, -/// and each carrying its whole tree's memory. -#[test] -fn only_harnesses_are_rows_and_each_is_named_for_what_it_is() { - let at = |pid: u32, ppid: Option, exe: &str, cmd: &[&str], mem: u64| ProcessSnapshot { - pid, - ppid, - exe: Some(exe.into()), - cmd: cmd.iter().map(|arg| (*arg).to_string()).collect(), - cwd: Some("/work/repo".into()), - start_time: 100, - owner_uid: None, - cpu_percent: 1.0, - memory_bytes: mem, - disk_read_bytes: 0, - disk_written_bytes: 0, - threads: 4, - }; - let codex = "/Users/me/.codex/packages/app-server-daemon/bin/codex"; - let snapshot = ResourceSnapshot::default().with_processes(vec![ - at(687, Some(1), "/Applications/Cursor.app/Contents/MacOS/Cursor", &["Cursor"], 10), - at( - 1847, - Some(687), - "/Applications/Cursor.app/Contents/Frameworks/Cursor Helper (Renderer).app/Contents/MacOS/Cursor Helper (Renderer)", - &["Cursor Helper (Renderer)", "--type=renderer"], - 10, - ), - at(9065, Some(1), "/Users/me/.medulla/bin/medulla", &["medulla"], 10), - at( - 9235, - Some(9065), - "/Users/me/.local/share/claude/versions/2.1.310", - &["claude", "--session-id", "abc"], - 500, - ), - at(9896, Some(9235), "/Users/me/.medulla/bin/medulla", &["medulla", "mcp"], 50), - at(10027, Some(9235), "/usr/local/bin/chrome-devtools-mcp", &["chrome-devtools-mcp"], 50), - at(49530, Some(1), codex, &["codex", "app-server", "daemon"], 10), - at(41393, Some(49530), codex, &["codex", "app-server", "--listen"], 100), - ]); - let rows = rows(&snapshot); - assert_eq!( - rows.iter() - .map(|row| (row.pid, row.kind.as_str(), row.memory, row.threads)) - .collect::>(), - [(9235, "Claude", 600, 12), (49530, "Codex Server", 110, 8)] - ); - assert!(rows.iter().all(|row| row.workspace == "/work/repo")); -} diff --git a/src/tui/src/ui/app/render/resources/agents/types.rs b/src/tui/src/ui/app/render/resources/agents/types.rs deleted file mode 100644 index d0adb95f1..000000000 --- a/src/tui/src/ui/app/render/resources/agents/types.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! Data types for the Agents table. - -use crate::ui::app::resources::types::AgentIdentity; - -/// One row of the Agents table: a harness process (or an aggregate of its tree) with its usage. -#[derive(Debug, Clone, PartialEq)] -pub(in crate::ui::app) struct AgentRow { - pub host: Option, - pub pid: u32, - pub started: u64, - pub kind: String, - pub origin: String, - pub workspace: String, - pub threads: usize, - pub memory: u64, - pub cpu: f64, - pub runtime: u64, - pub ppid: Option, - pub session_id: Option, - pub task_id: Option, - pub external: bool, - pub remote: bool, - pub depth: usize, -} - -impl AgentRow { - pub(in crate::ui::app) fn identity(&self) -> AgentIdentity { - AgentIdentity { - host: self.host.clone(), - pid: self.pid, - started: self.started, - } - } -} diff --git a/src/tui/src/ui/app/render/resources/agents_detail.rs b/src/tui/src/ui/app/render/resources/agents_detail.rs deleted file mode 100644 index 8f7645d0a..000000000 --- a/src/tui/src/ui/app/render/resources/agents_detail.rs +++ /dev/null @@ -1,62 +0,0 @@ -//! Detail pane for the selected agent in the Resources tab. - -use super::agents::AgentRow; -use crate::ui::app::resources::chrome::{self, Bar}; -use crate::ui::theme::ResourcesTheme; -use ratatui::{ - layout::Rect, - style::{Modifier, Style}, - Frame, -}; - -/// Draw the selected agent's details inside the Agents box. -pub(super) fn draw(frame: &mut Frame, area: Rect, row: Option<&AgentRow>, theme: &ResourcesTheme) { - let buffer = frame.buffer_mut(); - let inner = chrome::frame(buffer, area, theme.proc_box); - let mut top = Bar::top(area, theme.proc_box); - top.left(buffer, &chrome::plain(theme, "Agent detail")); - top.right(buffer, &chrome::keyed(theme, "Esc back", 'E', true)); - Bar::bottom(area, theme.proc_box).left(buffer, &chrome::plain(theme, "t/k/s signal")); - if inner.is_empty() { - return; - } - let label = Style::default().fg(theme.main_fg); - let value = Style::default() - .fg(theme.title) - .add_modifier(Modifier::BOLD); - let Some(row) = row else { - chrome::text( - buffer, - inner.x + 1, - inner.y, - inner.width.saturating_sub(2), - "No agent selected", - Style::default().fg(theme.inactive_fg), - ); - return; - }; - let fields = [ - ("PID", row.pid.to_string()), - ("Agent", row.kind.clone()), - ("Origin", row.origin.clone()), - ("Workspace", row.workspace.clone()), - ("Threads", row.threads.to_string()), - ("Memory", format!("{} bytes", row.memory)), - ("CPU", format!("{:.1}%", row.cpu)), - ("Runtime", format!("{} seconds", row.runtime)), - ("Parent", row.ppid.map_or("—".into(), |pid| pid.to_string())), - ]; - for (index, (name, text)) in fields.iter().enumerate() { - let y = inner.y + index as u16; - if y >= inner.bottom() { - break; - } - let x = chrome::text(buffer, inner.x + 1, y, 11, &format!("{name:<10}"), label); - let style = if *name == "CPU" { - Style::default().fg(chrome::shade(&theme.process, row.cpu)) - } else { - value - }; - chrome::text(buffer, x, y, inner.right().saturating_sub(x), text, style); - } -} diff --git a/src/tui/src/ui/app/render/resources/mod.rs b/src/tui/src/ui/app/render/resources/mod.rs deleted file mode 100644 index 5acb13141..000000000 --- a/src/tui/src/ui/app/render/resources/mod.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! Rendering for the Resources tab's Agents table and its detail pane. - -pub(super) mod agents; -pub(super) mod agents_detail; - -pub(in crate::ui::app) use agents::{draw_agents, rows, visible_rows_with_remote}; diff --git a/src/tui/src/ui/app/resources/agent_input.rs b/src/tui/src/ui/app/resources/agent_input.rs deleted file mode 100644 index 1c39437f0..000000000 --- a/src/tui/src/ui/app/resources/agent_input.rs +++ /dev/null @@ -1,243 +0,0 @@ -//! Keys for the Agents box: selection, filter, sort, follow, and signals. - -use super::types; -use crate::ui::app::types::App; - -impl App { - pub(super) fn agent_key(&mut self, key: crossterm::event::KeyCode) -> bool { - use crossterm::event::KeyCode; - use types::{AgentSignal, AgentSignalConfirmStage, AgentSignalConfirmation, AgentSort}; - if !self.resources.shown.agents { - self.resources.agent_signal_armed = None; - return false; - } - if let Some(armed) = self.resources.agent_signal_armed.take() { - let confirmation = match armed.stage { - AgentSignalConfirmStage::First => key == KeyCode::Char('y'), - AgentSignalConfirmStage::ExternalSecond => key == KeyCode::Char('Y'), - }; - if !confirmation { - self.set_status("Process signal cancelled"); - return true; - } - let process = self - .resource_snapshot - .processes - .iter() - .find(|process| process.pid == armed.pid && process.start_time == armed.started) - .cloned(); - let Some(process) = process else { - self.set_status("Process exited before signal was confirmed"); - return true; - }; - let row = crate::ui::app::render::resources::rows(&self.resource_snapshot) - .into_iter() - .find(|row| row.pid == armed.pid && row.started == armed.started); - let Some(row) = row else { - self.set_status("Process is no longer a classified local agent"); - return true; - }; - if row.remote { - self.set_status("Signals to remote processes are disabled"); - return true; - } - if !(self.resources.agent_process_owned_fn)( - armed.pid, - armed.started, - process.owner_uid.as_deref(), - ) { - self.set_status("Cannot signal a process not owned by the current user"); - return true; - } - if row.external && armed.stage == AgentSignalConfirmStage::First { - self.resources.agent_signal_armed = Some(AgentSignalConfirmation { - stage: AgentSignalConfirmStage::ExternalSecond, - ..armed - }); - self.set_status("External process: press uppercase Y to confirm the signal"); - return true; - } - match (self.resources.agent_signal_fn)( - armed.pid, - armed.started, - process.owner_uid.as_deref(), - armed.signal, - ) { - Ok(()) => self.set_status(format!("Signal sent to PID {}", armed.pid)), - Err(error) => self.set_status(format!("Signal failed: {error}")), - } - return true; - } - if self.resources.agent_filter_editing { - match key { - KeyCode::Esc => { - self.resources.agent_filter_editing = false; - } - KeyCode::Enter => { - self.resources.agent_filter_editing = false; - let remote_hosts: Vec<_> = self - .remote_hosts - .iter() - .map(|(id, host)| (id.clone(), host.rows.clone())) - .collect(); - let rows = crate::ui::app::render::resources::visible_rows_with_remote( - &self.resource_snapshot, - &remote_hosts, - &self.resources, - ); - self.resources.agent_selected = rows.first().map(|row| row.identity()); - } - KeyCode::Backspace => { - self.resources.agent_filter.as_mut().map(String::pop); - } - KeyCode::Char(c) => self - .resources - .agent_filter - .get_or_insert_with(String::new) - .push(c), - _ => {} - } - return true; - } - if self.resources.agent_detail && key == KeyCode::Esc { - self.resources.agent_detail = false; - return true; - } - let remote_hosts: Vec<_> = self - .remote_hosts - .iter() - .map(|(id, host)| (id.clone(), host.rows.clone())) - .collect(); - let rows = crate::ui::app::render::resources::visible_rows_with_remote( - &self.resource_snapshot, - &remote_hosts, - &self.resources, - ); - let selected = self - .resources - .agent_selected - .as_ref() - .and_then(|id| rows.iter().position(|row| row.identity() == *id)) - .unwrap_or(0); - match key { - KeyCode::Left | KeyCode::Right => { - self.resources.agent_sort = match (self.resources.agent_sort, key == KeyCode::Right) - { - (AgentSort::Pid, true) => AgentSort::Kind, - (AgentSort::Kind, true) => AgentSort::Origin, - (AgentSort::Origin, true) => AgentSort::Workspace, - (AgentSort::Workspace, true) => AgentSort::Threads, - (AgentSort::Threads, true) => AgentSort::Memory, - (AgentSort::Memory, true) => AgentSort::Cpu, - (AgentSort::Cpu, true) => AgentSort::Runtime, - (AgentSort::Runtime, true) => AgentSort::Pid, - (AgentSort::Pid, false) => AgentSort::Runtime, - (AgentSort::Runtime, false) => AgentSort::Cpu, - (AgentSort::Cpu, false) => AgentSort::Memory, - (AgentSort::Memory, false) => AgentSort::Threads, - (AgentSort::Threads, false) => AgentSort::Workspace, - (AgentSort::Workspace, false) => AgentSort::Origin, - (AgentSort::Origin, false) => AgentSort::Kind, - (AgentSort::Kind, false) => AgentSort::Pid, - }; - true - } - KeyCode::Up - | KeyCode::Down - | KeyCode::PageUp - | KeyCode::PageDown - | KeyCode::Home - | KeyCode::End => { - let next = match key { - KeyCode::Up => selected.saturating_sub(1), - KeyCode::Down => (selected + 1).min(rows.len().saturating_sub(1)), - KeyCode::PageUp => selected.saturating_sub(10), - KeyCode::PageDown => (selected + 10).min(rows.len().saturating_sub(1)), - KeyCode::Home => 0, - KeyCode::End => rows.len().saturating_sub(1), - _ => selected, - }; - self.resources.agent_selected = rows.get(next).map(|row| row.identity()); - if self.resources.agent_follow.is_some() { - self.resources.agent_follow = self.resources.agent_selected.clone(); - } - true - } - KeyCode::Char('r') => { - self.resources.agent_reverse = !self.resources.agent_reverse; - true - } - KeyCode::Char('e') => { - self.resources.agent_tree = !self.resources.agent_tree; - true - } - KeyCode::Char('f') | KeyCode::Char('/') => { - self.resources.agent_filter_editing = true; - self.resources.agent_filter.get_or_insert_with(String::new); - true - } - KeyCode::Char('F') => { - let identity = rows - .get(selected) - .filter(|row| !row.remote) - .map(|row| row.identity()); - if identity.is_none() { - self.set_status("Follow is available for local agents only"); - return true; - } - self.resources.agent_follow = match (self.resources.agent_follow.clone(), identity) - { - (Some(following), Some(selected)) if following == selected => None, - (_, selected) => selected, - }; - if self.resources.agent_follow.is_some() { - self.resources.agent_selected = self.resources.agent_follow.clone(); - } - true - } - KeyCode::Enter => { - if let Some(row) = rows.get(selected) { - if let Some(session) = row.session_id.as_deref() { - self.tab_index = crate::ui::app::types::TABS - .iter() - .position(|tab| *tab == "Sessions") - .unwrap_or(0); - self.select_session_row(session); - } else { - // `agent_selected` is `None` until a cursor key moves it, - // though the handler already resolved it to a row; store - // that row so the detail pane can find what it opens. - self.resources.agent_selected = Some(row.identity()); - self.resources.agent_detail = true; - } - } - true - } - KeyCode::Char('t' | 'k' | 's') => { - if let Some(row) = rows.get(selected) { - if !cfg!(any(target_os = "linux", target_os = "macos")) { - self.set_status("Process signals are disabled on this platform"); - return true; - } - if row.remote { - self.set_status("Signals to remote processes are disabled"); - return true; - } - let signal = match key { - KeyCode::Char('t') => AgentSignal::Terminate, - KeyCode::Char('k') => AgentSignal::Kill, - _ => AgentSignal::Stop, - }; - self.resources.agent_signal_armed = Some(AgentSignalConfirmation { - pid: row.pid, - started: row.started, - signal, - stage: AgentSignalConfirmStage::First, - }); - } - true - } - _ => false, - } - } -} diff --git a/src/tui/src/ui/app/resources/chrome.rs b/src/tui/src/ui/app/resources/chrome.rs deleted file mode 100644 index be8f1e2b5..000000000 --- a/src/tui/src/ui/app/resources/chrome.rs +++ /dev/null @@ -1,303 +0,0 @@ -//! btop-style box chrome shared by the Resources panels. -//! -//! A panel is a rounded frame whose top and bottom borders carry bracketed -//! tags, `─┐¹cpu┌┐menu┌──`. A tag's hotkey letter is drawn in the theme's -//! `hi_fg` so the border reads as the box's key legend, the way btop's does. - -use crate::ui::theme::{Gradient, ResourcesTheme}; -use ratatui::{ - buffer::Buffer, - layout::Rect, - style::{Color, Modifier, Style}, - text::Span, - widgets::{Block, BorderType, Widget}, -}; - -const SUPERSCRIPTS: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']; - -/// Paint `bg` behind every cell of `area`, keeping what is drawn there. -pub(in crate::ui::app) fn fill(buffer: &mut Buffer, area: Rect, bg: Color) { - buffer.set_style(area.intersection(buffer.area), Style::default().bg(bg)); -} - -/// Draw a rounded frame in `line` and return its inner area. -pub(in crate::ui::app) fn frame(buffer: &mut Buffer, area: Rect, line: Color) -> Rect { - if area.width < 2 || area.height < 2 { - return Rect::default(); - } - let block = Block::bordered() - .border_type(BorderType::Rounded) - .border_style(Style::default().fg(line)); - let inner = block.inner(area); - block.render(area, buffer); - inner -} - -/// Tags packed onto one border row, left tags growing rightwards and right -/// tags growing leftwards until they would meet. -pub(in crate::ui::app) struct Bar { - y: u16, - left: u16, - right: u16, - line: Color, - bottom: bool, -} - -impl Bar { - /// Tags on the top border of `area`, a frame drawn by [`frame`]. - pub(in crate::ui::app) fn top(area: Rect, line: Color) -> Self { - Self::new(area, area.y, line, false) - } - - /// Tags on the bottom border of `area`. - pub(in crate::ui::app) fn bottom(area: Rect, line: Color) -> Self { - Self::new(area, area.bottom().saturating_sub(1), line, true) - } - - fn new(area: Rect, y: u16, line: Color, bottom: bool) -> Self { - Self { - y, - left: area.x.saturating_add(2), - right: area.right().saturating_sub(2), - line, - bottom, - } - } - - /// Place a tag after the previous left tag. Returns the rectangle of its - /// text, or an empty one when it does not fit. - pub(in crate::ui::app) fn left(&mut self, buffer: &mut Buffer, spans: &[Span]) -> Rect { - let width = spans_width(spans) + 2; - if self.left + width > self.right { - return Rect::default(); - } - let text = self.put(buffer, self.left, spans); - self.left += width; - text - } - - /// Place a tag before the previous right tag. - pub(in crate::ui::app) fn right(&mut self, buffer: &mut Buffer, spans: &[Span]) -> Rect { - let width = spans_width(spans) + 2; - if self.right < self.left + width { - return Rect::default(); - } - self.right -= width; - self.put(buffer, self.right, spans) - } - - /// Centre a tag between the current left and right tags. Call it last: - /// it does not reserve space for later tags. - pub(in crate::ui::app) fn center(&mut self, buffer: &mut Buffer, spans: &[Span]) -> Rect { - let width = spans_width(spans) + 2; - let room = self.right.saturating_sub(self.left); - if room < width + 2 { - return Rect::default(); - } - self.put(buffer, self.left + (room - width) / 2, spans) - } - - fn put(&self, buffer: &mut Buffer, x: u16, spans: &[Span]) -> Rect { - let (open, close) = if self.bottom { - ("┘", "└") - } else { - ("┐", "┌") - }; - let line = Style::default().fg(self.line); - buffer.set_string(x, self.y, open, line); - let mut cursor = x + 1; - for span in spans { - let (next, _) = buffer.set_span(cursor, self.y, span, span.width() as u16); - cursor = next; - } - buffer.set_string(cursor, self.y, close, line); - Rect::new(x + 1, self.y, cursor - x - 1, 1) - } -} - -/// `¹cpu`: the box number as a hotkey superscript, then its name. -pub(in crate::ui::app) fn numbered( - theme: &ResourcesTheme, - number: usize, - name: &str, -) -> Vec> { - vec![ - Span::styled( - SUPERSCRIPTS[number % 10].to_string(), - Style::default().fg(theme.hi_fg), - ), - Span::styled( - name.to_owned(), - Style::default() - .fg(theme.title) - .add_modifier(Modifier::BOLD), - ), - ] -} - -/// A button label with its first `key` character highlighted. An inactive -/// toggle is drawn dim, as btop draws a switched-off option. -pub(in crate::ui::app) fn keyed( - theme: &ResourcesTheme, - text: &str, - key: char, - active: bool, -) -> Vec> { - let base = Style::default().fg(if active { - theme.title - } else { - theme.inactive_fg - }); - let Some(index) = text.find(key) else { - return vec![Span::styled(text.to_owned(), base)]; - }; - let end = index + key.len_utf8(); - vec![ - Span::styled(text[..index].to_owned(), base), - Span::styled( - text[index..end].to_owned(), - Style::default() - .fg(theme.hi_fg) - .add_modifier(Modifier::BOLD), - ), - Span::styled(text[end..].to_owned(), base), - ] -} - -/// `‹ text ›` or `- text +`: a value flanked by two one-cell buttons. -pub(in crate::ui::app) fn stepper( - theme: &ResourcesTheme, - down: &str, - text: &str, - up: &str, -) -> Vec> { - let key = Style::default() - .fg(theme.hi_fg) - .add_modifier(Modifier::BOLD); - vec![ - Span::styled(down.to_owned(), key), - Span::styled(format!(" {text} "), Style::default().fg(theme.title)), - Span::styled(up.to_owned(), key), - ] -} - -/// Plain title-coloured tag text. -pub(in crate::ui::app) fn plain(theme: &ResourcesTheme, text: &str) -> Vec> { - vec![Span::styled( - text.to_owned(), - Style::default().fg(theme.title), - )] -} - -/// The down and up buttons of a [`stepper`] tag, `down` and `up` cells wide -/// at either end of its text rectangle. -pub(in crate::ui::app) fn stepper_hits(text: Rect, down: u16, up: u16) -> (Rect, Rect) { - if text.width < down + up { - return (Rect::default(), Rect::default()); - } - ( - Rect::new(text.x, text.y, down, 1), - Rect::new(text.right() - up, text.y, up, 1), - ) -} - -/// Draw `text` in `style`, clipped to `width` cells. -pub(in crate::ui::app) fn text( - buffer: &mut Buffer, - x: u16, - y: u16, - width: u16, - text: &str, - style: Style, -) -> u16 { - if width == 0 { - return x; - } - buffer.set_stringn(x, y, text, width as usize, style).0 -} - -/// Draw `text` right-aligned so it ends at `right`. -pub(in crate::ui::app) fn text_right( - buffer: &mut Buffer, - right: u16, - y: u16, - min_x: u16, - value: &str, - style: Style, -) { - let width = value.chars().count() as u16; - let x = right.saturating_sub(width).max(min_x); - text(buffer, x, y, right.saturating_sub(x), value, style); -} - -/// Sample a precomputed theme gradient into a plot gradient. -pub(in crate::ui::app) fn plot_gradient(gradient: Gradient) -> crate::ui::plot::Gradient { - crate::ui::plot::Gradient::new((0..=100).map(|pct| gradient.at(pct)).collect::>()) -} - -/// A colour from `gradient` for a percentage. -pub(in crate::ui::app) fn shade(gradient: &Gradient, percent: f64) -> Color { - gradient.at(if percent.is_finite() { - percent.clamp(0.0, 100.0).round() as usize - } else { - 0 - }) -} - -/// Binary byte size in btop's style: `17.7 GiB`, `950 MiB`, `12 KiB`. -pub(in crate::ui::app) fn bytes(value: f64) -> String { - const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; - let mut value = value.max(0.0); - let mut unit = 0; - while value >= 1024.0 && unit + 1 < UNITS.len() { - value /= 1024.0; - unit += 1; - } - if unit == 0 || value >= 100.0 { - format!("{value:.0} {}", UNITS[unit]) - } else if value >= 10.0 { - format!("{value:.1} {}", UNITS[unit]) - } else { - format!("{value:.2} {}", UNITS[unit]) - } -} - -/// A short binary size for tight columns: `17.7G`, `950M`, `12K`. -pub(in crate::ui::app) fn bytes_short(value: f64) -> String { - const UNITS: [&str; 6] = ["B", "K", "M", "G", "T", "P"]; - let mut value = value.max(0.0); - let mut unit = 0; - while value >= 1024.0 && unit + 1 < UNITS.len() { - value /= 1024.0; - unit += 1; - } - if unit == 0 || value >= 10.0 { - format!("{value:.0}{}", UNITS[unit]) - } else { - format!("{value:.1}{}", UNITS[unit]) - } -} - -/// Bit rate in btop's style: `470 Kibps`, `2.46 Mibps`. -/// -/// At most 10 cells, so a rate line in the 25-cell stats box always fits. -pub(in crate::ui::app) fn bits(bytes_per_second: f64) -> String { - const UNITS: [&str; 5] = ["bps", "Kibps", "Mibps", "Gibps", "Tibps"]; - let mut value = (bytes_per_second * 8.0).max(0.0); - let mut unit = 0; - while value >= 1024.0 && unit + 1 < UNITS.len() { - value /= 1024.0; - unit += 1; - } - if unit == 0 || value >= 100.0 { - format!("{value:.0} {}", UNITS[unit]) - } else if value >= 10.0 { - format!("{value:.1} {}", UNITS[unit]) - } else { - format!("{value:.2} {}", UNITS[unit]) - } -} - -fn spans_width(spans: &[Span]) -> u16 { - spans.iter().map(|span| span.width() as u16).sum() -} diff --git a/src/tui/src/ui/app/resources/cpu/mod.rs b/src/tui/src/ui/app/resources/cpu/mod.rs deleted file mode 100644 index 554d57085..000000000 --- a/src/tui/src/ui/app/resources/cpu/mod.rs +++ /dev/null @@ -1,529 +0,0 @@ -//! The CPU box: a full-height usage history beside a per-core sub-box. - -use super::chrome::{self, Bar}; -use super::types::ResourceHits; -use crate::ui::plot::Graph; -use crate::ui::resources::sampler::ResourceSnapshot; -use crate::ui::resources::CpuField; -use crate::ui::theme::ResourcesTheme; -use ratatui::{ - layout::Rect, - style::{Modifier, Style}, - text::Span, - Frame, -}; - -/// Everything the CPU box draws from besides the snapshot. -pub(super) struct CpuView<'a> { - pub config: &'a medulla::config::ResourcesConfig, - pub theme: &'a ResourcesTheme, - pub preset: usize, - pub interval_ms: u64, -} - -/// Geometry of the per-core sub-box. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct CoreLayout { - columns: usize, - rows: usize, - label: u16, - graph: u16, - temp: bool, - /// Outer width of the sub-box, borders included. - width: u16, -} - -/// Width of a core's percentage field, ` 100%`. -const PCT: u16 = 5; -/// Width of a core's temperature field, ` 45°C`. -const TEMP: u16 = 5; -/// Width of one core in the compact layout, `C10 100% `. -const COMPACT_CORE: u16 = 10; - -pub(super) fn draw( - frame: &mut Frame, - rect: Rect, - snapshot: &ResourceSnapshot, - view: &CpuView, - hits: &mut ResourceHits, -) { - let theme = view.theme; - let config = view.config; - let buffer = frame.buffer_mut(); - let inner = chrome::frame(buffer, rect, theme.cpu_box); - let mut top = Bar::top(rect, theme.cpu_box); - hits.cpu_toggle = top.left(buffer, &chrome::numbered(theme, 1, "cpu")); - hits.menu = top.left(buffer, &chrome::keyed(theme, "menu", 'm', true)); - let preset = top.left( - buffer, - &chrome::stepper(theme, "‹", &format!("preset {}", view.preset), "›"), - ); - (hits.preset_prev, hits.preset_next) = chrome::stepper_hits(preset, 1, 1); - let interval = top.right( - buffer, - &chrome::stepper(theme, "-", &format!("{}ms", view.interval_ms), "+"), - ); - (hits.interval_down, hits.interval_up) = chrome::stepper_hits(interval, 1, 1); - if config.show_battery { - if let Some(battery) = snapshot.cpu.battery_percent { - top.right(buffer, &battery_spans(theme, battery)); - } - } - top.center(buffer, &chrome::plain(theme, &super::clock_text())); - if inner.is_empty() { - return; - } - - let temps = !snapshot.cpu.core_temperatures_c.is_empty(); - let layout = core_layout(inner, snapshot.cpu.cores.len(), temps); - let graph_area = match layout { - Some(layout) => { - // Sized to its rows and centred, as btop places it. - let height = (layout.rows as u16 + 4).min(inner.height); - let cores = Rect::new( - inner.right() - layout.width, - inner.y + (inner.height - height) / 2, - layout.width, - height, - ); - draw_cores(frame, cores, snapshot, view, layout); - Rect::new( - inner.x, - inner.y, - inner.width.saturating_sub(layout.width + 1), - inner.height, - ) - } - None => { - // No room for the sub-box: the cores become text rows under the - // graph, then a one-row summary. - let per_line = usize::from(inner.width / COMPACT_CORE).max(1); - let core_lines = (snapshot.cpu.cores.len().div_ceil(per_line) as u16) - .min(inner.height.saturating_sub(1)); - let summary_y = inner.bottom() - 1; - let cores_y = summary_y - core_lines; - draw_compact_cores(frame, inner, cores_y, core_lines, per_line, snapshot, view); - draw_summary(frame, inner, summary_y, snapshot, view); - Rect::new(inner.x, inner.y, inner.width, cores_y - inner.y) - } - }; - draw_history(frame, graph_area, snapshot, view); -} - -/// The usage history: the upper field grows upwards from the middle and the -/// lower field, unless the box is single-graph, grows downwards beneath it. -fn draw_history(frame: &mut Frame, area: Rect, snapshot: &ResourceSnapshot, view: &CpuView) { - if area.is_empty() { - return; - } - let config = view.config; - let gradient = chrome::plot_gradient(view.theme.cpu); - let upper = CpuField::parse(&config.cpu_graph_upper).unwrap_or(CpuField::Total); - let lower = CpuField::parse(&config.cpu_graph_lower).unwrap_or(CpuField::Iowait); - let series = |field: CpuField| -> Vec { - snapshot - .history - .cpu - .iter() - .map(|sample| sample.total.field(field)) - .collect() - }; - let lower_values = series(lower); - // A lower field the platform never reports (iowait on macOS) would leave - // half the box permanently empty, so the upper graph takes it over. - let lower_reported = lower_values.iter().any(|value| *value > 0.0); - let split = !config.cpu_single_graph && lower_reported && area.height >= 2; - let upper_height = if split { - area.height.div_ceil(2) - } else { - area.height - }; - frame.render_widget( - Graph::new(&series(upper)).gradient(&gradient), - Rect::new(area.x, area.y, area.width, upper_height), - ); - if split { - frame.render_widget( - Graph::new(&lower_values) - .invert(config.cpu_invert_lower) - .gradient(&gradient), - Rect::new( - area.x, - area.y + upper_height, - area.width, - area.height - upper_height, - ), - ); - } - if let Some(uptime) = snapshot.cpu.uptime_seconds { - let text = format!( - "up {}d {:02}:{:02}", - uptime / 86_400, - uptime / 3_600 % 24, - uptime / 60 % 60 - ); - if area.width as usize > text.len() + 2 { - chrome::text( - frame.buffer_mut(), - area.x + 1, - area.bottom() - 1, - text.len() as u16, - &text, - Style::default().fg(view.theme.main_fg), - ); - } - } -} - -/// Fit the per-core sub-box, preferring wide core graphs and temperatures -/// and giving them up before giving up the box. -fn core_layout(inner: Rect, count: usize, temps: bool) -> Option { - if inner.width < 60 || inner.height < 5 { - return None; - } - // A snapshot taken before the first core reading still gets the box, so - // its CPU meter and load average keep their place. - let count = count.max(1); - let rows_available = usize::from(inner.height - 4).max(1); - let columns = count.div_ceil(rows_available); - let rows = count.div_ceil(columns); - let label = (format!("C{}", count - 1).len() as u16 + 1).max(4); - let max_width = inner.width * 55 / 100; - let attempts = [ - (temps, 10), - (temps, 8), - (temps, 6), - (false, 6), - (false, 4), - (false, 0), - ]; - attempts.into_iter().find_map(|(temp, graph)| { - let column = label + graph + PCT + if temp { TEMP } else { 0 }; - let content = columns as u16 * column + columns.saturating_sub(1) as u16; - let width = content.max(28) + 2; - (width <= max_width).then_some(CoreLayout { - columns, - rows, - label, - graph, - temp, - width, - }) - }) -} - -fn draw_cores( - frame: &mut Frame, - area: Rect, - snapshot: &ResourceSnapshot, - view: &CpuView, - layout: CoreLayout, -) { - let theme = view.theme; - let config = view.config; - let buffer = frame.buffer_mut(); - let inner = chrome::frame(buffer, area, theme.cpu_box); - let mut top = Bar::top(area, theme.cpu_box); - let frequencies: Vec = snapshot - .cpu - .frequencies_mhz - .iter() - .flatten() - .copied() - .collect(); - if !frequencies.is_empty() { - let average = frequencies.iter().sum::() / frequencies.len() as u64; - top.right( - buffer, - &chrome::plain(theme, &format_frequency(average, &config.freq_mode)), - ); - } - if let Some(model) = snapshot.cpu.model.as_deref().filter(|m| !m.is_empty()) { - let room = area.width.saturating_sub(16) as usize; - let model = shorten_model(model, room); - if !model.is_empty() { - top.left( - buffer, - &[Span::styled( - model, - Style::default() - .fg(theme.title) - .add_modifier(Modifier::BOLD), - )], - ); - } - } - if inner.is_empty() { - return; - } - - let main = Style::default().fg(theme.main_fg); - let total = f64::from(snapshot.cpu.total.total); - let temp = snapshot.cpu.package_temperature_c.map(|temp| { - let crit = snapshot.cpu.package_temperature_crit_c.unwrap_or(100.0); - (temp, crit) - }); - let temp_width = if temp.is_some() { 6 } else { 0 }; - let x = chrome::text(buffer, inner.x, inner.y, 4, "CPU ", main); - let meter_width = inner.width.saturating_sub(4 + PCT + temp_width); - frame.render_widget( - crate::ui::plot::Meter::new( - total as f32, - &chrome::plot_gradient(theme.cpu), - theme.meter_bg, - ), - Rect::new(x, inner.y, meter_width, 1), - ); - let buffer = frame.buffer_mut(); - chrome::text( - buffer, - x + meter_width, - inner.y, - PCT, - &format!("{:>4.0}%", total), - Style::default().fg(chrome::shade(&theme.cpu, total)), - ); - if let Some((temp, crit)) = temp { - chrome::text( - buffer, - x + meter_width + PCT, - inner.y, - temp_width, - &format!(" {}", format_temp(temp, &config.temp_scale)), - Style::default().fg(chrome::shade( - &theme.temp, - f64::from(temp * 100.0 / crit.max(1.0)), - )), - ); - } - - let gradient = chrome::plot_gradient(theme.cpu); - let column_width = layout.label + layout.graph + PCT + if layout.temp { TEMP } else { 0 } + 1; - let core_rows = inner.height.saturating_sub(2); - for (index, core) in snapshot.cpu.cores.iter().enumerate() { - let column = index / layout.rows; - let row = (index % layout.rows) as u16; - if row >= core_rows || column >= layout.columns { - continue; - } - let x = inner.x + column as u16 * column_width; - let y = inner.y + 1 + row; - chrome::text( - frame.buffer_mut(), - x, - y, - layout.label, - &format!("C{index}"), - main, - ); - if layout.graph > 0 { - let history: Vec = snapshot - .history - .cpu - .iter() - .filter_map(|sample| sample.cores.get(index).map(|core| core.total)) - .collect(); - frame.render_widget( - Graph::new(&history).no_zero(true).gradient(&gradient), - Rect::new(x + layout.label, y, layout.graph, 1), - ); - } - let buffer = frame.buffer_mut(); - let pct_x = x + layout.label + layout.graph; - let usage = f64::from(core.total); - chrome::text( - buffer, - pct_x, - y, - PCT, - &format!("{:>4.0}%", usage), - Style::default().fg(chrome::shade(&theme.cpu, usage)), - ); - if layout.temp { - if let Some((_, temp, crit)) = snapshot - .cpu - .core_temperatures_c - .iter() - .find(|(core, _, _)| *core == index) - { - let crit = if *crit > 0.0 { *crit } else { 100.0 }; - chrome::text( - buffer, - pct_x + PCT, - y, - TEMP, - &format!(" {}", format_temp_short(*temp, &config.temp_scale)), - Style::default().fg(chrome::shade(&theme.temp, f64::from(temp * 100.0 / crit))), - ); - } - } - } - if inner.height >= 2 { - let [one, five, fifteen] = snapshot.cpu.load_average; - chrome::text_right( - frame.buffer_mut(), - inner.right(), - inner.bottom() - 1, - inner.x, - &format!("Load avg: {one:.2} {five:.2} {fifteen:.2}"), - main, - ); - } -} - -/// Core percentages as text rows, for a box too small for the sub-box. -fn draw_compact_cores( - frame: &mut Frame, - inner: Rect, - y: u16, - lines: u16, - per_line: usize, - snapshot: &ResourceSnapshot, - view: &CpuView, -) { - let theme = view.theme; - let buffer = frame.buffer_mut(); - let main = Style::default().fg(theme.main_fg); - for (index, core) in snapshot.cpu.cores.iter().enumerate() { - let line = (index / per_line) as u16; - if line >= lines { - break; - } - let x = inner.x + (index % per_line) as u16 * COMPACT_CORE; - let usage = f64::from(core.total); - let x = chrome::text(buffer, x, y + line, 4, &format!("C{index:<3}"), main); - chrome::text( - buffer, - x, - y + line, - COMPACT_CORE - 4, - &format!("{usage:>3.0}%"), - Style::default().fg(chrome::shade(&theme.cpu, usage)), - ); - } -} - -/// One-row CPU summary for a box too narrow for the core sub-box. -fn draw_summary( - frame: &mut Frame, - inner: Rect, - y: u16, - snapshot: &ResourceSnapshot, - view: &CpuView, -) { - let theme = view.theme; - let main = Style::default().fg(theme.main_fg); - let total = f64::from(snapshot.cpu.total.total); - let [one, five, fifteen] = snapshot.cpu.load_average; - let frequencies: Vec = snapshot - .cpu - .frequencies_mhz - .iter() - .flatten() - .copied() - .collect(); - let frequency = if frequencies.is_empty() || inner.width < 60 { - String::new() - } else { - let average = frequencies.iter().sum::() / frequencies.len() as u64; - format!(" {}", format_frequency(average, &view.config.freq_mode)) - }; - let load = format!(" Load avg {one:.1} {five:.1} {fifteen:.1}{frequency}"); - let load_width = if inner.width >= 40 { - load.chars().count() as u16 - } else { - 0 - }; - let x = chrome::text(frame.buffer_mut(), inner.x, y, 4, "CPU ", main); - let meter_width = inner.width.saturating_sub(4 + PCT + load_width); - frame.render_widget( - crate::ui::plot::Meter::new( - total as f32, - &chrome::plot_gradient(theme.cpu), - theme.meter_bg, - ), - Rect::new(x, y, meter_width, 1), - ); - let buffer = frame.buffer_mut(); - let x = chrome::text( - buffer, - x + meter_width, - y, - PCT, - &format!("{:>4.0}%", total), - Style::default().fg(chrome::shade(&theme.cpu, total)), - ); - chrome::text(buffer, x, y, load_width, &load, main); -} - -fn battery_spans(theme: &ResourcesTheme, percent: f32) -> Vec> { - let percent = f64::from(percent.clamp(0.0, 100.0)); - let filled = (percent / 10.0).round() as usize; - let mut spans = vec![Span::styled( - format!("BAT {percent:.0}% "), - Style::default().fg(theme.title), - )]; - for cell in 0..10 { - let color = if cell < filled { - chrome::shade(&theme.cpu, 100.0 - percent) - } else { - theme.meter_bg - }; - spans.push(Span::styled("■", Style::default().fg(color))); - } - spans -} - -/// Drop vendor boilerplate from a CPU brand string so it fits a tag. -fn shorten_model(model: &str, room: usize) -> String { - let mut short = model.to_owned(); - for noise in [ - "(R)", - "(TM)", - "(tm)", - "Intel ", - "AMD ", - "Apple ", - "Core ", - "Processor", - "with Radeon Graphics", - ] { - short = short.replace(noise, ""); - } - if let Some(at) = short.find('@') { - short.truncate(at); - short = short.trim_end().trim_end_matches("CPU").to_owned(); - } - let short = short.split_whitespace().collect::>().join(" "); - short.chars().take(room).collect() -} - -pub(super) fn format_frequency(mhz: u64, mode: &str) -> String { - match mode { - "mhz" => format!("{mhz} MHz"), - "ghz" => format!("{:.1} GHz", mhz as f64 / 1000.0), - _ if mhz >= 1000 => format!("{:.1} GHz", mhz as f64 / 1000.0), - _ => format!("{mhz} MHz"), - } -} - -fn format_temp(celsius: f32, scale: &str) -> String { - if scale == "fahrenheit" { - format!("{:.0}°F", celsius * 1.8 + 32.0) - } else { - format!("{celsius:.0}°C") - } -} - -/// `45°` or `113°` without the unit letter, for a core column. -fn format_temp_short(celsius: f32, scale: &str) -> String { - let value = if scale == "fahrenheit" { - celsius * 1.8 + 32.0 - } else { - celsius - }; - format!("{value:>3.0}°") -} - -#[cfg(test)] -mod tests; diff --git a/src/tui/src/ui/app/resources/cpu/tests.rs b/src/tui/src/ui/app/resources/cpu/tests.rs deleted file mode 100644 index 6728c79fb..000000000 --- a/src/tui/src/ui/app/resources/cpu/tests.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! Unit tests for the CPU panel. - -use super::*; - -#[test] -fn core_layout_spreads_many_cores_across_columns() { - let layout = core_layout(Rect::new(0, 0, 168, 13), 18, false).expect("fits"); - assert_eq!((layout.columns, layout.rows), (2, 9)); - assert_eq!(layout.graph, 10); -} - -#[test] -fn core_layout_gives_up_graphs_before_the_box() { - let layout = core_layout(Rect::new(0, 0, 70, 13), 18, true).expect("fits"); - assert!( - !layout.temp, - "temperatures go before the graphs shrink further" - ); - assert_eq!(layout.graph, 6); - assert!(layout.width <= 70 * 55 / 100); -} - -#[test] -fn core_layout_needs_room() { - assert_eq!(core_layout(Rect::new(0, 0, 50, 13), 8, false), None); - assert!(core_layout(Rect::new(0, 0, 120, 13), 0, false).is_some()); - assert_eq!(core_layout(Rect::new(0, 0, 120, 4), 8, false), None); -} - -#[test] -fn model_names_lose_vendor_boilerplate() { - assert_eq!( - shorten_model("Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz", 40), - "i7-9750H" - ); - assert_eq!(shorten_model("Apple M5 Pro", 40), "M5 Pro"); -} diff --git a/src/tui/src/ui/app/resources/disks.rs b/src/tui/src/ui/app/resources/disks.rs deleted file mode 100644 index 4183066ad..000000000 --- a/src/tui/src/ui/app/resources/disks.rs +++ /dev/null @@ -1,276 +0,0 @@ -//! The disks column of the Mem box, laid out as btop lays it out: each disk a -//! divider headed by its name and size, then its IO, then how full it is. - -use super::chrome; -use crate::ui::plot::{Graph, Meter}; -use crate::ui::resources::sampler::{DiskSnapshot, ResourceSnapshot}; -use crate::ui::theme::ResourcesTheme; -use ratatui::{ - layout::Rect, - style::{Modifier, Style}, - Frame, -}; - -/// The disks to list. Swap, when it is shown as a disk, comes straight after -/// the root, where btop puts it. -pub(super) fn disk_list( - snapshot: &ResourceSnapshot, - config: &medulla::config::ResourcesConfig, -) -> Vec { - let mut disks = snapshot.disks.clone(); - if config.swap_disk && config.show_swap && snapshot.swap_total_bytes > 0 { - let at = disks - .iter() - .position(|disk| disk.mount == "/") - .map_or(0, |root| root + 1); - disks.insert( - at, - DiskSnapshot { - device: "swap".into(), - mount: "swap".into(), - total_bytes: snapshot.swap_total_bytes, - used_bytes: snapshot.swap_used_bytes, - read_bytes_per_second: 0.0, - write_bytes_per_second: 0.0, - busy_percent: None, - has_io: false, - }, - ); - } - disks -} - -/// How each disk is drawn: a header and meter, or a single packed line when -/// even that does not fit every disk. -#[derive(Clone, Copy, PartialEq)] -enum Fit { - Header, - Line, -} - -pub(super) fn draw( - frame: &mut Frame, - area: Rect, - snapshot: &ResourceSnapshot, - disks: &[DiskSnapshot], - config: &medulla::config::ResourcesConfig, - theme: &ResourcesTheme, -) { - if area.is_empty() || disks.is_empty() { - return; - } - let count = disks.len() as u16; - let fit = if area.height >= count * 2 { - Fit::Header - } else { - Fit::Line - }; - // Every disk is listed before any gets an IO row; the rows left over go - // to the disks with IO counters in list order, so the root keeps its graph - // even when a Mac's dozen system volumes fill the column. - let mut spare_io_rows = area.height.saturating_sub(count * 2); - let main = Style::default().fg(theme.main_fg); - let used_gradient = chrome::plot_gradient(theme.used); - let mut y = area.y; - for disk in disks { - let io_row = fit == Fit::Header && disk.has_io && spare_io_rows > 0; - if io_row { - spare_io_rows -= 1; - } - let rows = match fit { - Fit::Header => 2 + u16::from(io_row), - Fit::Line => 1, - }; - if y + rows > area.bottom() { - break; - } - let percent = if disk.total_bytes == 0 { - 0.0 - } else { - disk.used_bytes as f64 * 100.0 / disk.total_bytes as f64 - }; - let name = disk_name(&disk.mount); - let pct_style = Style::default().fg(chrome::shade(&theme.used, percent)); - if fit == Fit::Line { - // `root 55% ■■■■■■■■ 1.0T` - let title = Style::default() - .fg(theme.title) - .add_modifier(Modifier::BOLD); - let buffer = frame.buffer_mut(); - let name_width = 9.min(area.width); - chrome::text(buffer, area.x + 1, y, name_width, &name, title); - let x = area.x + 1 + name_width; - chrome::text(buffer, x, y, 5, &format!("{percent:>3.0}%"), pct_style); - let size = format!("{:>5}", chrome::bytes_short(disk.used_bytes as f64)); - let meter_x = x + 5; - let meter_width = area.right().saturating_sub(meter_x + size.len() as u16 + 2); - chrome::text_right( - buffer, - area.right().saturating_sub(1), - y, - meter_x, - &size, - main, - ); - frame.render_widget( - Meter::new(percent as f32, &used_gradient, theme.meter_bg), - Rect::new(meter_x, y, meter_width, 1), - ); - y += 1; - continue; - } - header( - frame, - area, - y, - &name, - &chrome::bytes(disk.total_bytes as f64), - theme, - ); - let mut row = y + 1; - if io_row { - draw_disk_io(frame, area, row, snapshot, disk, config, theme); - row += 1; - } - // ` Used: 55% ■■■■■■■■■■ 1013 GiB` - let used = chrome::bytes(disk.used_bytes as f64); - let buffer = frame.buffer_mut(); - let x = chrome::text(buffer, area.x + 1, row, 6, "Used:", main); - let x = chrome::text(buffer, x, row, 5, &format!("{percent:>3.0}% "), pct_style); - let meter_width = area.right().saturating_sub(x + used.len() as u16 + 2); - chrome::text_right(buffer, area.right().saturating_sub(1), row, x, &used, main); - frame.render_widget( - Meter::new(percent as f32, &used_gradient, theme.meter_bg), - Rect::new(x, row, meter_width, 1), - ); - y += rows; - } -} - -/// `├─root──────────1.81 TiB─┤`: a divider across the column, joined to the -/// borders either side, carrying the disk's name and size. -fn header(frame: &mut Frame, area: Rect, y: u16, name: &str, size: &str, theme: &ResourcesTheme) { - let line = Style::default().fg(theme.div_line); - let title = Style::default() - .fg(theme.title) - .add_modifier(Modifier::BOLD); - let main = Style::default().fg(theme.main_fg); - let buffer = frame.buffer_mut(); - let left = area.x.saturating_sub(1); - let right = area.right(); - if left < area.x { - buffer.set_string(left, y, "├", line); - } - for x in area.x..right { - buffer.set_string(x, y, "─", line); - } - if right < buffer.area.right() { - buffer.set_string(right, y, "┤", line); - } - let name_end = chrome::text( - buffer, - area.x + 1, - y, - area.width.saturating_sub(2), - name, - title, - ); - chrome::text_right(buffer, right.saturating_sub(1), y, name_end + 1, size, main); -} - -/// One IO row under a disk: its busy percentage history, or with `io_mode` -/// its read and write rates against the configured device speed. -fn draw_disk_io( - frame: &mut Frame, - area: Rect, - y: u16, - snapshot: &ResourceSnapshot, - disk: &DiskSnapshot, - config: &medulla::config::ResourcesConfig, - theme: &ResourcesTheme, -) { - let main = Style::default().fg(theme.main_fg); - let entries = || { - snapshot - .history - .disk_io - .iter() - .filter_map(|sample| sample.iter().find(|entry| entry.device == disk.device)) - }; - let limit = super::io_graph_speed(config, &disk.mount) * 1024.0 * 1024.0; - let x = area.x + 1; - let width = area.width.saturating_sub(2); - if config.io_mode { - let read: Vec = entries() - .map(|entry| (entry.read_bytes_per_second * 100.0 / limit) as f32) - .collect(); - let write: Vec = entries() - .map(|entry| (entry.write_bytes_per_second * 100.0 / limit) as f32) - .collect(); - let rates = format!( - "▲{} ▼{}", - chrome::bytes_short(disk.read_bytes_per_second), - chrome::bytes_short(disk.write_bytes_per_second) - ); - let graph_width = width.saturating_sub(rates.chars().count() as u16 + 1); - if config.io_graph_combined { - let combined: Vec = read.iter().zip(&write).map(|(r, w)| r + w).collect(); - frame.render_widget( - Graph::new(&combined) - .no_zero(true) - .gradient(&chrome::plot_gradient(theme.available)), - Rect::new(x, y, graph_width, 1), - ); - } else { - let half = graph_width / 2; - frame.render_widget( - Graph::new(&read) - .no_zero(true) - .gradient(&chrome::plot_gradient(theme.free)), - Rect::new(x, y, half, 1), - ); - frame.render_widget( - Graph::new(&write) - .no_zero(true) - .gradient(&chrome::plot_gradient(theme.used)), - Rect::new(x + half, y, graph_width - half, 1), - ); - } - chrome::text_right(frame.buffer_mut(), area.right() - 1, y, x, &rates, main); - } else { - let busy: Vec = entries() - .map(|entry| match entry.busy_percent { - Some(busy) => busy as f32, - None => { - ((entry.read_bytes_per_second + entry.write_bytes_per_second) * 100.0 / limit) - as f32 - } - }) - .collect(); - let x = chrome::text(frame.buffer_mut(), x, y, 4, "IO%", main) + 1; - frame.render_widget( - Graph::new(&busy) - .no_zero(true) - .gradient(&chrome::plot_gradient(theme.available)), - Rect::new(x, y, area.right().saturating_sub(x + 1), 1), - ); - } -} - -/// btop names the root mount `root` and the rest by their last component. -fn disk_name(mount: &str) -> String { - if mount == "/" { - return "root".into(); - } - mount - .trim_end_matches('/') - .rsplit('/') - .next() - .filter(|name| !name.is_empty()) - .unwrap_or(mount) - .to_owned() -} - -#[cfg(test)] -#[path = "disks_tests.rs"] -mod tests; diff --git a/src/tui/src/ui/app/resources/disks_tests.rs b/src/tui/src/ui/app/resources/disks_tests.rs deleted file mode 100644 index 4d1214606..000000000 --- a/src/tui/src/ui/app/resources/disks_tests.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! Unit tests for `disks`. - -use super::disk_name; - -#[test] -fn disk_names_follow_btop() { - assert_eq!(disk_name("/"), "root"); - assert_eq!(disk_name("/System/Volumes/Data"), "Data"); - assert_eq!(disk_name("/mnt/backup/"), "backup"); - assert_eq!(disk_name("C:\\"), "C:\\"); -} diff --git a/src/tui/src/ui/app/resources/input.rs b/src/tui/src/ui/app/resources/input.rs deleted file mode 100644 index 2e6ec1260..000000000 --- a/src/tui/src/ui/app/resources/input.rs +++ /dev/null @@ -1,187 +0,0 @@ -//! The Resources tab's keys and clicks, outside the Agents box. - -use crate::ui::app::types::App; - -impl App { - pub(in crate::ui::app) fn resources_key(&mut self, key: crossterm::event::KeyCode) -> bool { - // An open filter prompt takes every key, letters that are shortcuts - // elsewhere in the tab included. - if self.resources.agent_filter_editing && self.resources.shown.agents { - return self.agent_key(key); - } - if key == crossterm::event::KeyCode::Char('o') { - self.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Settings") - .unwrap_or(0); - self.settings_index = crate::ui::app::types::SP_RESOURCES; - self.settings_focused = true; - self.set_status("Settings · Resources"); - return true; - } - if key == crossterm::event::KeyCode::Char('m') { - self.resources.menu_open = !self.resources.menu_open; - return true; - } - if key == crossterm::event::KeyCode::Char('?') { - self.resources.help_open = !self.resources.help_open; - return true; - } - if self.resources.help_open { - if key == crossterm::event::KeyCode::Esc { - self.resources.help_open = false; - } - return true; - } - if self.agent_key(key) { - return true; - } - if !self.resources.key(key) { - return false; - } - if key == crossterm::event::KeyCode::Char('z') { - let current = self.resources.net_iface.as_deref().or_else(|| { - crate::ui::resources::net::default_interface(&self.resource_snapshot.networks) - }); - if let Some(interface) = current.and_then(|name| { - self.resource_snapshot - .networks - .iter() - .find(|entry| entry.interface == name) - }) { - self.resources.net_zero_offsets.insert( - interface.interface.clone(), - ( - interface.total_received_bytes, - interface.total_transmitted_bytes, - ), - ); - self.resources.net_iface = Some(interface.interface.clone()); - } - } - if matches!(key, crossterm::event::KeyCode::Char('b' | 'n')) { - let current = self.resources.net_iface.as_deref().or_else(|| { - crate::ui::resources::net::default_interface(&self.resource_snapshot.networks) - }); - let interfaces: Vec<_> = self - .resource_snapshot - .networks - .iter() - .map(|interface| (interface.interface.as_str(), interface.up)) - .collect(); - self.resources.net_iface = crate::ui::resources::net::cycle_interface( - current, - &interfaces, - key == crossterm::event::KeyCode::Char('n'), - ); - } - let state = &self.resources; - let shown = [ - (state.shown.cpu, "cpu"), - (state.shown.mem, "mem"), - (state.shown.net, "net"), - (state.shown.agents, "agents"), - ] - .into_iter() - .filter_map(|(shown, name)| shown.then_some(name)) - .collect::>() - .join(","); - let config = &mut self.loaded.config.resources; - config.update_ms = state.interval_ms; - config.shown_boxes = shown; - config.preset = state.preset; - config.cpu_bottom = Some(state.opts.cpu_bottom); - config.mem_below_net = Some(state.opts.mem_below_net); - config.agents_left = Some(state.opts.agents_left); - config.show_disks = state.show_disks; - config.io_mode = state.io_mode; - config.net_auto = state.net_auto; - config.net_sync = state.net_sync; - config.net_download = state.net_download; - config.net_upload = state.net_upload; - config.net_iface = state.net_iface.clone(); - config.swap_upload_download = state.swap_upload_download; - if let Some(path) = self.config_path.as_deref() { - let settings = [ - ("updateMs", ratatui_toml_value_u64(config.update_ms)), - ( - "shownBoxes", - toml::Value::String(config.shown_boxes.clone()), - ), - ("preset", toml::Value::Integer(config.preset as i64)), - ( - "cpuBottom", - toml::Value::Boolean(config.cpu_bottom.unwrap_or(false)), - ), - ( - "memBelowNet", - toml::Value::Boolean(config.mem_below_net.unwrap_or(false)), - ), - ( - "agentsLeft", - toml::Value::Boolean(config.agents_left.unwrap_or(false)), - ), - ("showDisks", toml::Value::Boolean(config.show_disks)), - ("ioMode", toml::Value::Boolean(config.io_mode)), - ("netAuto", toml::Value::Boolean(config.net_auto)), - ("netSync", toml::Value::Boolean(config.net_sync)), - ("netDownload", ratatui_toml_value_u64(config.net_download)), - ("netUpload", ratatui_toml_value_u64(config.net_upload)), - ( - "netIface", - config - .net_iface - .clone() - .map_or(toml::Value::String(String::new()), toml::Value::String), - ), - ( - "swapUploadDownload", - toml::Value::Boolean(config.swap_upload_download), - ), - ]; - for (key, value) in settings { - if let Err(error) = medulla::config::persist_setting(path, "resources", key, value) - { - self.set_status(format!("Resources save failed: {error}")); - return true; - } - } - self.set_status("Resources settings saved"); - } else { - self.set_status("Resources settings changed (not persisted)"); - } - true - } - - pub(in crate::ui::app) fn resources_click(&mut self, x: u16, y: u16) -> bool { - let hits = self.resources.hits; - if hits.menu.contains((x, y).into()) { - self.resources.menu_open = !self.resources.menu_open; - return true; - } - let key = [ - (hits.cpu_toggle, '1'), - (hits.mem_toggle, '2'), - (hits.net_toggle, '3'), - (hits.agents_toggle, '4'), - (hits.disks_toggle, 'd'), - (hits.io_toggle, 'i'), - (hits.net_prev, 'b'), - (hits.net_next, 'n'), - (hits.net_zero, 'z'), - (hits.net_auto, 'a'), - (hits.net_sync, 'y'), - (hits.preset_prev, 'p'), - (hits.preset_next, 'P'), - (hits.interval_down, '-'), - (hits.interval_up, '+'), - ] - .into_iter() - .find_map(|(rect, key)| rect.contains((x, y).into()).then_some(key)); - key.is_some_and(|key| self.resources_key(crossterm::event::KeyCode::Char(key))) - } -} - -fn ratatui_toml_value_u64(value: u64) -> toml::Value { - toml::Value::Integer(value.min(i64::MAX as u64) as i64) -} diff --git a/src/tui/src/ui/app/resources/keys.rs b/src/tui/src/ui/app/resources/keys.rs deleted file mode 100644 index 26e5518d2..000000000 --- a/src/tui/src/ui/app/resources/keys.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Key handling for the Resources tab. - -use super::types::ResourcesState; -use crossterm::event::KeyCode; - -impl ResourcesState { - pub(in crate::ui::app) fn key(&mut self, key: KeyCode) -> bool { - match key { - KeyCode::Char('1') => self.shown.cpu = !self.shown.cpu, - KeyCode::Char('2') => self.shown.mem = !self.shown.mem, - KeyCode::Char('3') => self.shown.net = !self.shown.net, - KeyCode::Char('4') => { - self.shown.agents = !self.shown.agents; - if !self.shown.agents { - self.agent_signal_armed = None; - } - } - KeyCode::Char('d') => self.show_disks = !self.show_disks, - KeyCode::Char('i') => self.io_mode = !self.io_mode, - KeyCode::Char('z') => self.net_zeroed = true, - KeyCode::Char('a') => self.net_auto = !self.net_auto, - KeyCode::Char('y') => self.net_sync = !self.net_sync, - KeyCode::Char('b') | KeyCode::Char('n') => return true, - KeyCode::Char('p') => self.preset = self.preset.saturating_sub(1), - KeyCode::Char('P') => self.preset = (self.preset + 1) % self.presets.len().max(1), - KeyCode::Char('+') | KeyCode::Char('=') => { - self.interval_ms = (self.interval_ms + 100).min(10_000) - } - KeyCode::Char('-') => self.interval_ms = self.interval_ms.saturating_sub(100).max(100), - _ => return false, - } - if matches!(key, KeyCode::Char('p') | KeyCode::Char('P')) { - // An interactive preset choice replaces the loaded placement - // overrides. The caller persists this resulting layout alongside - // the selected preset, so reload preserves what the operator saw. - self.apply_preset(); - } - true - } -} diff --git a/src/tui/src/ui/app/resources/layout.rs b/src/tui/src/ui/app/resources/layout.rs deleted file mode 100644 index 533a6636c..000000000 --- a/src/tui/src/ui/app/resources/layout.rs +++ /dev/null @@ -1,142 +0,0 @@ -//! Btop-style panel layout for the Resources tab. - -use super::types::{BoxRects, LayoutOptions, ShownBoxes}; -use ratatui::layout::Rect; - -/// Calculate btop-style panel rectangles within the content area. -pub(super) fn calc_sizes(area: Rect, shown: ShownBoxes, opts: &LayoutOptions) -> BoxRects { - let mut out = BoxRects::default(); - if shown.cpu && (area.width < 60 || area.height < 8) { - out.too_small = Some(60); - return out; - } - if shown.cpu && !shown.mem && !shown.net && !shown.agents { - out.cpu = area; - return out; - } - let rest = if shown.cpu { - let h = (u32::from(area.height) * 32) - .div_ceil(100) - .max(8) - .min(u32::from(area.height)) as u16; - let cpu_y = if opts.cpu_bottom { - area.bottom() - h - } else { - area.y - }; - out.cpu = Rect::new(area.x, cpu_y, area.width, h); - if opts.cpu_bottom { - Rect::new(area.x, area.y, area.width, area.height - h) - } else { - Rect::new(area.x, area.y + h, area.width, area.height - h) - } - } else { - area - }; - if shown.agents && (rest.width < 44 || rest.height < 16) { - if rest.width >= 44 && rest.height >= 16 { - out.agents = rest; - return out; - } - out.too_small = Some(44); - return out; - } - if shown.agents && (u32::from(rest.width) * 55 / 100 < 44 || rest.height < 16) { - // Agents has priority over Mem and Net. When the normal split would - // make its panel unusable, retain it and suppress the lower-priority - // panels as complete boxes. - out.agents = rest; - return out; - } - if shown.agents && shown.mem && shown.net { - let left_w = (u32::from(rest.width) * 45).div_ceil(100) as u16; - let right_w = rest.width.saturating_sub(left_w); - let mem_h = if shown.cpu { - u32::from(area.height) * 40 / 100 - } else { - u32::from(rest.height) * 72 / 100 - } - // CPU takes at least 8 rows, so on a short area 40% of the whole height - // can exceed what is left; never ask for more than remains. - .min(u32::from(rest.height)) as u16; - let net_h = rest.height.saturating_sub(mem_h); - if opts.agents_left { - out.agents = Rect::new(rest.x, rest.y, right_w, rest.height); - out.mem = Rect::new( - rest.x + right_w, - if opts.mem_below_net { - rest.y + net_h - } else { - rest.y - }, - left_w, - mem_h, - ); - out.net = if opts.mem_below_net { - Rect::new(rest.x + right_w, rest.y, left_w, net_h) - } else { - Rect::new(rest.x + right_w, rest.y + mem_h, left_w, net_h) - }; - } else { - out.mem = Rect::new( - rest.x, - if opts.mem_below_net { - rest.y + net_h - } else { - rest.y - }, - left_w, - mem_h, - ); - out.net = if opts.mem_below_net { - Rect::new(rest.x, rest.y, left_w, net_h) - } else { - Rect::new(rest.x, rest.y + mem_h, left_w, net_h) - }; - out.agents = Rect::new(rest.x + left_w, rest.y, right_w, rest.height); - } - } else if shown.agents { - if shown.mem || shown.net { - let left_w = (u32::from(rest.width) * 45).div_ceil(100) as u16; - let right_w = rest.width.saturating_sub(left_w); - let (panel_x, agent_x) = if opts.agents_left { - (rest.x + right_w, rest.x) - } else { - (rest.x, rest.x + left_w) - }; - out.agents = Rect::new(agent_x, rest.y, right_w, rest.height); - if shown.mem { - out.mem = Rect::new(panel_x, rest.y, left_w, rest.height); - } - if shown.net { - out.net = Rect::new(panel_x, rest.y, left_w, rest.height); - } - } else { - out.agents = rest; - } - } else if shown.mem && shown.net { - let mh = if shown.cpu { - u32::from(area.height) * 40 / 100 - } else { - u32::from(rest.height) * 72 / 100 - } - // CPU takes at least 8 rows, so on a short area 40% of the whole height - // can exceed what is left; never ask for more than remains. - .min(u32::from(rest.height)) as u16; - out.mem = if opts.mem_below_net { - Rect::new(rest.x, rest.y + rest.height - mh, rest.width, mh) - } else { - Rect::new(rest.x, rest.y, rest.width, mh) - }; - out.net = if opts.mem_below_net { - Rect::new(rest.x, rest.y, rest.width, rest.height - mh) - } else { - Rect::new(rest.x, rest.y + mh, rest.width, rest.height - mh) - }; - } else if shown.mem { - out.mem = rest; - } else if shown.net { - out.net = rest; - } - out -} diff --git a/src/tui/src/ui/app/resources/mem.rs b/src/tui/src/ui/app/resources/mem.rs deleted file mode 100644 index e1d00337a..000000000 --- a/src/tui/src/ui/app/resources/mem.rs +++ /dev/null @@ -1,251 +0,0 @@ -//! The Mem box: memory stats on the left and, beside a divider, the disks. - -use super::chrome::{self, Bar}; -use super::disks::{self, disk_list}; -use super::types::ResourceHits; -use crate::ui::plot::{Graph, Meter}; -use crate::ui::resources::sampler::{History, ResourceSnapshot}; -use crate::ui::theme::{Gradient, ResourcesTheme}; -use ratatui::{ - layout::Rect, - style::{Modifier, Style}, - Frame, -}; - -/// One memory statistic and the gradient it is drawn in. -struct Stat<'a> { - label: &'static str, - value: u64, - total: u64, - history: &'a History, - gradient: Gradient, -} - -pub(super) fn draw( - frame: &mut Frame, - rect: Rect, - snapshot: &ResourceSnapshot, - config: &medulla::config::ResourcesConfig, - theme: &ResourcesTheme, - hits: &mut ResourceHits, -) { - let buffer = frame.buffer_mut(); - let inner = chrome::frame(buffer, rect, theme.mem_box); - let disks = disk_list(snapshot, config); - let split = config.show_disks && !disks.is_empty() && inner.width >= 50 && inner.height >= 3; - let mem_width = if split { inner.width / 2 } else { inner.width }; - let mut top = Bar::top(rect, theme.mem_box); - hits.mem_toggle = top.left(buffer, &chrome::numbered(theme, 2, "mem")); - let mut disk_bar = if split { - let divider = inner.x + mem_width; - let line = Style::default().fg(theme.mem_box); - buffer.set_string(divider, rect.y, "┬", line); - buffer.set_string(divider, rect.bottom() - 1, "┴", line); - for y in inner.y..inner.bottom() { - buffer.set_string(divider, y, "│", line); - } - Bar::top( - Rect::new(divider, rect.y, rect.right() - divider, 1), - theme.mem_box, - ) - } else { - top - }; - hits.disks_toggle = disk_bar.left( - buffer, - &chrome::keyed(theme, "disks", 'd', config.show_disks), - ); - hits.io_toggle = disk_bar.right(buffer, &chrome::keyed(theme, "io", 'i', config.io_mode)); - if inner.is_empty() { - return; - } - - let mem_area = Rect::new(inner.x, inner.y, mem_width, inner.height); - let used_rows = draw_memory(frame, mem_area, snapshot, config, theme); - if !config.show_disks { - return; - } - let disk_area = if split { - Rect::new( - inner.x + mem_width + 1, - inner.y, - inner.width - mem_width - 1, - inner.height, - ) - } else { - Rect::new( - inner.x, - inner.y + used_rows, - inner.width, - inner.height.saturating_sub(used_rows), - ) - }; - disks::draw(frame, disk_area, snapshot, &disks, config, theme); -} - -/// Draw the memory column and return how many rows it used. -fn draw_memory( - frame: &mut Frame, - area: Rect, - snapshot: &ResourceSnapshot, - config: &medulla::config::ResourcesConfig, - theme: &ResourcesTheme, -) -> u16 { - let total = snapshot.memory_total_bytes; - let history = &snapshot.history; - let mut stats = vec![ - Stat { - label: "Used", - value: snapshot.memory_used_bytes, - total, - history: &history.memory_used_bytes, - gradient: theme.used, - }, - Stat { - label: "Available", - value: snapshot.memory_available_bytes, - total, - history: &history.memory_available_bytes, - gradient: theme.available, - }, - Stat { - label: "Cached", - value: snapshot.memory_cached_bytes, - total, - history: &history.memory_cached_bytes, - gradient: theme.cached, - }, - Stat { - label: "Free", - value: snapshot.memory_free_bytes, - total, - history: &history.memory_free_bytes, - gradient: theme.free, - }, - ]; - let swap_as_disk = config.swap_disk && config.show_disks; - if config.show_swap && !swap_as_disk && snapshot.swap_total_bytes > 0 { - stats.push(Stat { - label: "Swap", - value: snapshot.swap_used_bytes, - total: snapshot.swap_total_bytes, - history: &history.swap_used_bytes, - gradient: theme.used, - }); - } - - let buffer = frame.buffer_mut(); - let main = Style::default().fg(theme.main_fg); - let value = Style::default().fg(theme.title); - chrome::text(buffer, area.x + 1, area.y, area.width, "Total:", main); - chrome::text_right( - buffer, - area.right().saturating_sub(1), - area.y, - area.x + 8, - &chrome::bytes(total as f64), - value.add_modifier(Modifier::BOLD), - ); - - // Two rows per stat when they fit (a label row, then a percentage and its - // graph), and as many extra graph rows as the box can spare. Otherwise - // each stat collapses onto a single row. - let room = area.height.saturating_sub(1); - let per = (room / stats.len().max(1) as u16).min(4); - let mut y = area.y + 1; - for stat in &stats { - if y >= area.bottom() { - break; - } - let percent = if stat.total == 0 { - 0.0 - } else { - stat.value as f64 * 100.0 / stat.total as f64 - }; - let pct_style = Style::default().fg(chrome::shade(&stat.gradient, percent)); - let gradient = chrome::plot_gradient(stat.gradient); - let samples: Vec = stat - .history - .iter() - .map(|value| { - if stat.total == 0 { - 0.0 - } else { - *value as f32 * 100.0 / stat.total as f32 - } - }) - .collect(); - if per >= 2 { - let buffer = frame.buffer_mut(); - chrome::text( - buffer, - area.x + 1, - y, - area.width, - &format!("{}:", stat.label), - main, - ); - chrome::text_right( - buffer, - area.right().saturating_sub(1), - y, - area.x + 12, - &chrome::bytes(stat.value as f64), - value, - ); - let body = Rect::new( - area.x + 6, - y + 1, - area.width.saturating_sub(7), - (per - 1).min(area.bottom().saturating_sub(y + 1)), - ); - chrome::text( - buffer, - area.x + 1, - y + 1, - 5, - &format!("{percent:>3.0}%"), - pct_style, - ); - if config.mem_graphs { - frame.render_widget(Graph::new(&samples).no_zero(true).gradient(&gradient), body); - } else { - frame.render_widget( - Meter::new(percent as f32, &gradient, theme.meter_bg), - Rect::new(body.x, body.y, body.width, 1), - ); - } - y += per; - } else { - // `Used 37% ⣀⣀⣀⣀⣀ 17.7G` - let buffer = frame.buffer_mut(); - let label = 10.min(area.width); - chrome::text(buffer, area.x + 1, y, label, stat.label, main); - let x = area.x + 1 + label; - chrome::text(buffer, x, y, 5, &format!("{percent:>3.0}%"), pct_style); - // Fixed width so every row's graph starts in the same column. - let size = format!("{:>5}", chrome::bytes_short(stat.value as f64)); - let graph_x = x + 5; - let graph_width = area.right().saturating_sub(graph_x + size.len() as u16 + 2); - chrome::text_right( - buffer, - area.right().saturating_sub(1), - y, - graph_x, - &size, - value, - ); - let graph = Rect::new(graph_x, y, graph_width, 1); - if config.mem_graphs { - frame.render_widget( - Graph::new(&samples).no_zero(true).gradient(&gradient), - graph, - ); - } else { - frame.render_widget(Meter::new(percent as f32, &gradient, theme.meter_bg), graph); - } - y += 1; - } - } - y - area.y -} diff --git a/src/tui/src/ui/app/resources/mod.rs b/src/tui/src/ui/app/resources/mod.rs deleted file mode 100644 index e52586ca1..000000000 --- a/src/tui/src/ui/app/resources/mod.rs +++ /dev/null @@ -1,227 +0,0 @@ -//! State, layout, keys, and rendering for the host Resources tab. - -mod agent_input; -pub(in crate::ui::app) mod chrome; -mod cpu; -mod disks; -mod input; -mod keys; -pub(super) mod layout; -mod mem; -mod net; -#[cfg(test)] -mod tests; -pub(super) mod types; - -pub(super) use types::ResourcesState; - -use ratatui::{ - layout::Rect, - style::{Color, Modifier, Style}, - widgets::Paragraph, - Frame, -}; - -use super::types::App; - -impl App { - pub(super) fn draw_resources(&mut self, f: &mut Frame, area: Rect) { - let remote_agents: Vec<_> = self - .remote_hosts - .iter() - .map(|(host, state)| (host.clone(), state.rows.clone())) - .collect(); - chrome::fill(f.buffer_mut(), area, self.theme.resources.main_bg); - let state = &mut self.resources; - let rects = layout::calc_sizes(area, state.shown, &state.opts); - state.rects = rects; - if let Some(required) = rects.too_small { - if state.shown.agents && area.width >= 44 && area.height >= 10 { - state.rects.agents = area; - crate::ui::app::render::resources::draw_agents( - f, - area, - &self.resource_snapshot, - &remote_agents, - state, - &self.theme.resources, - ); - return; - } - f.render_widget( - Paragraph::new(format!( - "Terminal too small for Resources (minimum {required}x8)" - )) - .alignment(ratatui::layout::Alignment::Center) - .style( - Style::default() - .fg(Color::Yellow) - .add_modifier(Modifier::BOLD), - ), - area, - ); - return; - } - state.hits = types::ResourceHits::default(); - let theme = self.theme.resources; - let config = &self.loaded.config.resources; - let snapshot = &self.resource_snapshot; - if state.shown.cpu && !rects.cpu.is_empty() { - let view = cpu::CpuView { - config, - theme: &theme, - preset: state.preset, - interval_ms: state.interval_ms, - }; - cpu::draw(f, rects.cpu, snapshot, &view, &mut state.hits); - } - if state.shown.mem && !rects.mem.is_empty() { - mem::draw(f, rects.mem, snapshot, config, &theme, &mut state.hits); - } - if state.shown.net && !rects.net.is_empty() { - let selected = state - .net_iface - .as_deref() - .or_else(|| crate::ui::resources::net::default_interface(&snapshot.networks)); - let view = net::NetView { - config, - theme: &theme, - selected, - zero_offsets: state - .net_zero_offsets - .get(selected.unwrap_or_default()) - .copied() - .unwrap_or_default(), - download_max: if state.net_auto { - state.net_download_scaler.max() - } else { - state.net_download as f64 * 1024.0 - }, - upload_max: if state.net_auto { - state.net_upload_scaler.max() - } else { - state.net_upload as f64 * 1024.0 - }, - auto: state.net_auto, - sync: state.net_sync, - }; - net::draw(f, rects.net, snapshot, &view, &mut state.hits); - } - if state.shown.agents && !rects.agents.is_empty() { - crate::ui::app::render::resources::draw_agents( - f, - rects.agents, - snapshot, - &remote_agents, - state, - &theme, - ); - } - if state.menu_open { - overlay( - f, - area, - "menu", - &[ - ("1-4", "show or hide a box"), - ("p P", "previous or next layout preset"), - ("- +", "sample interval"), - ("o", "Resources settings"), - ("Esc", "close"), - ], - &theme, - ); - } - if state.help_open { - overlay( - f, - area, - "help", - &[ - ("1-4", "show or hide boxes"), - ("p P", "change layout preset"), - ("- +", "change sample interval"), - ("a y", "network auto-scale and sync"), - ("b n", "select network interface"), - ("z", "reset network totals"), - ("d i", "disks and disk IO"), - ("o", "open Resources settings"), - ("Esc", "close"), - ], - &theme, - ); - } - } -} - -#[allow(clippy::too_many_arguments)] -/// A centred, rounded key legend drawn over the boxes. -fn overlay( - frame: &mut Frame, - area: Rect, - title: &str, - entries: &[(&str, &str)], - theme: &crate::ui::theme::ResourcesTheme, -) { - let width = entries - .iter() - .map(|(_, text)| text.chars().count() as u16 + 8) - .max() - .unwrap_or(0) - .max(title.len() as u16 + 6) - .min(area.width); - let height = (entries.len() as u16 + 2).min(area.height); - let rect = Rect::new( - area.x + (area.width - width) / 2, - area.y + (area.height - height) / 2, - width, - height, - ); - frame.render_widget(ratatui::widgets::Clear, rect); - let buffer = frame.buffer_mut(); - chrome::fill(buffer, rect, theme.main_bg); - let inner = chrome::frame(buffer, rect, theme.title); - chrome::Bar::top(rect, theme.title).left(buffer, &chrome::plain(theme, title)); - let key = Style::default() - .fg(theme.hi_fg) - .add_modifier(Modifier::BOLD); - let text = Style::default().fg(theme.main_fg); - for (row, (keys, description)) in entries.iter().enumerate() { - let y = inner.y + row as u16; - if y >= inner.bottom() { - break; - } - let x = chrome::text(buffer, inner.x + 1, y, 4, keys, key); - let x = x.max(inner.x + 6); - chrome::text( - buffer, - x, - y, - inner.right().saturating_sub(x), - description, - text, - ); - } -} - -pub(super) fn io_graph_speed(config: &medulla::config::ResourcesConfig, mount: &str) -> f64 { - config - .io_graph_speeds - .split_whitespace() - .find_map(|entry| { - let (target, speed) = entry.split_once(':')?; - if target != mount { - return None; - } - speed - .parse::() - .ok() - .filter(|speed| *speed > 0) - .map(|speed| speed as f64) - }) - .unwrap_or(100.0) -} - -pub(super) fn clock_text() -> String { - chrono::Local::now().format("%X").to_string() -} diff --git a/src/tui/src/ui/app/resources/net.rs b/src/tui/src/ui/app/resources/net.rs deleted file mode 100644 index 70e5d57b4..000000000 --- a/src/tui/src/ui/app/resources/net.rs +++ /dev/null @@ -1,336 +0,0 @@ -//! The Net box: mirrored download and upload graphs beside a stats sub-box. - -use super::chrome::{self, Bar}; -use super::types::ResourceHits; -use crate::ui::plot::Graph; -use crate::ui::resources::sampler::{NetworkSnapshot, ResourceSnapshot}; -use crate::ui::theme::{Gradient, ResourcesTheme}; -use ratatui::{ - layout::Rect, - style::{Modifier, Style}, - Frame, -}; - -/// Everything the Net box draws from besides the snapshot. -pub(super) struct NetView<'a> { - pub config: &'a medulla::config::ResourcesConfig, - pub theme: &'a ResourcesTheme, - pub selected: Option<&'a str>, - pub zero_offsets: (u64, u64), - pub download_max: f64, - pub upload_max: f64, - pub auto: bool, - pub sync: bool, -} - -/// One direction's readings, already swapped when the config asks. -struct Direction { - arrow: &'static str, - name: &'static str, - rate: f64, - top: f64, - total: u64, - history: Vec, - gradient: Gradient, -} - -/// Stats sub-box width, as btop's. -const STATS_WIDTH: u16 = 27; - -pub(super) fn draw( - frame: &mut Frame, - rect: Rect, - snapshot: &ResourceSnapshot, - view: &NetView, - hits: &mut ResourceHits, -) { - let theme = view.theme; - let selected = selected_interface(snapshot, view.selected); - let buffer = frame.buffer_mut(); - let inner = chrome::frame(buffer, rect, theme.net_box); - let mut top = Bar::top(rect, theme.net_box); - hits.net_toggle = top.left(buffer, &chrome::numbered(theme, 3, "net")); - let interface = selected.map_or("no iface", |entry| entry.interface.as_str()); - let iface = top.right(buffer, &chrome::stepper(theme, "←b", interface, "n→")); - (hits.net_prev, hits.net_next) = chrome::stepper_hits(iface, 2, 2); - hits.net_zero = top.right(buffer, &chrome::keyed(theme, "zero", 'z', true)); - hits.net_auto = top.right(buffer, &chrome::keyed(theme, "auto", 'a', view.auto)); - hits.net_sync = top.right(buffer, &chrome::keyed(theme, "sync", 'y', view.sync)); - let address = selected.map_or_else(|| "no IP".to_owned(), display_address); - top.left(buffer, &chrome::plain(theme, &address)); - if inner.is_empty() { - return; - } - let Some(selected) = selected else { - chrome::text( - frame.buffer_mut(), - inner.x + 1, - inner.y, - inner.width, - "No active network interface", - Style::default().fg(theme.inactive_fg), - ); - return; - }; - - let (download, upload) = directions(snapshot, selected, view); - let boxed = inner.width >= 50 && inner.height >= 4; - let graph_area = if boxed { - let stats = Rect::new( - inner.right() - STATS_WIDTH, - inner.y, - STATS_WIDTH, - inner.height.min(9), - ); - let stats = Rect::new( - stats.x, - inner.y + (inner.height - stats.height) / 2, - stats.width, - stats.height, - ); - draw_stats(frame, stats, &download, &upload, theme); - Rect::new( - inner.x, - inner.y, - inner.width - STATS_WIDTH - 1, - inner.height, - ) - } else { - inner - }; - - let (download_max, upload_max) = - crate::ui::resources::net::synced_max(view.download_max, view.upload_max, view.sync); - let half = graph_area.height.div_ceil(2); - let upper = Rect::new(graph_area.x, graph_area.y, graph_area.width, half); - let lower = Rect::new( - graph_area.x, - graph_area.y + half, - graph_area.width, - graph_area.height - half, - ); - frame.render_widget( - Graph::new(&download.history) - .no_zero(true) - .gradient(&chrome::plot_gradient(download.gradient)), - upper, - ); - if !lower.is_empty() { - frame.render_widget( - Graph::new(&upload.history) - .invert(true) - .no_zero(true) - .gradient(&chrome::plot_gradient(upload.gradient)), - lower, - ); - } - - let buffer = frame.buffer_mut(); - let scale = Style::default().fg(theme.graph_text); - chrome::text( - buffer, - graph_area.x, - upper.y, - 8, - &chrome::bytes_short(download_max), - scale, - ); - if !lower.is_empty() && lower.height > 1 { - chrome::text( - buffer, - graph_area.x, - lower.bottom() - 1, - 8, - &chrome::bytes_short(upload_max), - scale, - ); - } - if !boxed { - // No room for the sub-box: put one line per direction over the graphs. - for (direction, y) in [(&download, upper.y), (&upload, graph_area.bottom() - 1)] { - let line = format!( - "{} {}/s Σ {}", - direction.arrow, - chrome::bytes(direction.rate), - chrome::bytes(direction.total as f64) - ); - chrome::text_right( - buffer, - graph_area.right(), - y, - graph_area.x + 6, - &line, - Style::default().fg(chrome::shade(&direction.gradient, 100.0)), - ); - } - } -} - -/// The address to show for an interface: its first IPv4 address, else its -/// first address, without the prefix length. -fn display_address(interface: &NetworkSnapshot) -> String { - let bare = |address: &String| address.split('/').next().unwrap_or_default().to_owned(); - interface - .ip_addresses - .iter() - .find(|address| address.contains('.')) - .or_else(|| interface.ip_addresses.first()) - .map_or_else(|| "no IP".to_owned(), bare) -} - -fn selected_interface<'a>( - snapshot: &'a ResourceSnapshot, - selected: Option<&str>, -) -> Option<&'a NetworkSnapshot> { - let find = |name: &str| { - snapshot - .networks - .iter() - .find(|entry| entry.interface == name) - }; - selected - .and_then(find) - .or_else(|| crate::ui::resources::net::default_interface(&snapshot.networks).and_then(find)) -} - -fn directions( - snapshot: &ResourceSnapshot, - selected: &NetworkSnapshot, - view: &NetView, -) -> (Direction, Direction) { - let swap = view.config.swap_upload_download; - let (zero_received, zero_transmitted) = view.zero_offsets; - let history = |received: bool, max: f64| -> Vec { - snapshot - .history - .network_io - .iter() - .filter_map(|sample| { - sample - .iter() - .find(|entry| entry.interface == selected.interface) - }) - .map(|entry| { - let rate = if received { - entry.received_bytes_per_second - } else { - entry.transmitted_bytes_per_second - }; - (rate * 100.0 / max.max(1.0)) as f32 - }) - .collect() - }; - let (download_max, upload_max) = - crate::ui::resources::net::synced_max(view.download_max, view.upload_max, view.sync); - let (top_received, top_transmitted) = network_top(snapshot, &selected.interface); - let received = |name, arrow, max, gradient| Direction { - arrow, - name, - rate: selected.received_bytes_per_second, - top: top_received, - total: selected.total_received_bytes.saturating_sub(zero_received), - history: history(true, max), - gradient, - }; - let transmitted = |name, arrow, max, gradient| Direction { - arrow, - name, - rate: selected.transmitted_bytes_per_second, - top: top_transmitted, - total: selected - .total_transmitted_bytes - .saturating_sub(zero_transmitted), - history: history(false, max), - gradient, - }; - let theme = view.theme; - if swap { - ( - transmitted("download", "▼", download_max, theme.download), - received("upload", "▲", upload_max, theme.upload), - ) - } else { - ( - received("download", "▼", download_max, theme.download), - transmitted("upload", "▲", upload_max, theme.upload), - ) - } -} - -/// The highest rate in the retained history, each way. -pub(super) fn network_top(snapshot: &ResourceSnapshot, interface: &str) -> (f64, f64) { - snapshot - .history - .network_io - .iter() - .flat_map(|sample| sample.iter()) - .filter(|entry| entry.interface == interface) - .fold((0.0_f64, 0.0_f64), |(rx, tx), entry| { - ( - rx.max(entry.received_bytes_per_second), - tx.max(entry.transmitted_bytes_per_second), - ) - }) -} - -/// The download/upload stats sub-box: rate, peak and total each way, with as -/// many of those rows as its height allows. -fn draw_stats( - frame: &mut Frame, - area: Rect, - download: &Direction, - upload: &Direction, - theme: &ResourcesTheme, -) { - let buffer = frame.buffer_mut(); - let inner = chrome::frame(buffer, area, theme.net_box); - Bar::top(area, theme.net_box).left(buffer, &chrome::plain(theme, download.name)); - Bar::bottom(area, theme.net_box).left(buffer, &chrome::plain(theme, upload.name)); - if inner.is_empty() { - return; - } - let rows = if inner.height >= 7 { - 3 - } else if inner.height >= 4 { - 2 - } else { - 1 - }; - let gap = u16::from(inner.height > rows * 2); - let main = Style::default().fg(theme.main_fg); - for (index, direction) in [download, upload].into_iter().enumerate() { - let arrow = Style::default() - .fg(chrome::shade(&direction.gradient, 100.0)) - .add_modifier(Modifier::BOLD); - let first = inner.y + index as u16 * (rows + gap); - let lines = [ - ( - format!("{}/s", chrome::bytes(direction.rate)), - format!("({})", chrome::bits(direction.rate)), - ), - ( - "Top:".to_owned(), - format!("({})", chrome::bits(direction.top)), - ), - ("Total:".to_owned(), chrome::bytes(direction.total as f64)), - ]; - let lines: Vec<_> = if rows == 2 { - vec![lines[0].clone(), lines[2].clone()] - } else { - lines.into_iter().take(rows as usize).collect() - }; - for (offset, (left, right)) in lines.iter().enumerate() { - let y = first + offset as u16; - if y >= inner.bottom() { - break; - } - let x = chrome::text(buffer, inner.x, y, 2, direction.arrow, arrow) + 1; - let x = chrome::text(buffer, x, y, inner.right().saturating_sub(x), left, main); - chrome::text_right(buffer, inner.right(), y, x + 1, right, main); - } - } -} - -#[cfg(test)] -#[path = "net_tests.rs"] -mod tests; diff --git a/src/tui/src/ui/app/resources/net_tests.rs b/src/tui/src/ui/app/resources/net_tests.rs deleted file mode 100644 index b9c5b01c9..000000000 --- a/src/tui/src/ui/app/resources/net_tests.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Unit tests for `net`. - -use super::*; - -#[test] -fn the_title_address_prefers_ipv4_and_drops_the_prefix() { - let interface = NetworkSnapshot { - interface: "en0".into(), - up: true, - connected: true, - ip_addresses: vec![ - "fe80::1c2b:3cff:fe4d:5e6f/64".into(), - "192.168.8.66/24".into(), - ], - received_bytes_per_second: 0.0, - transmitted_bytes_per_second: 0.0, - total_received_bytes: 0, - total_transmitted_bytes: 0, - }; - assert_eq!(display_address(&interface), "192.168.8.66"); - let v6_only = NetworkSnapshot { - ip_addresses: vec!["2001:db8::1/64".into()], - ..interface.clone() - }; - assert_eq!(display_address(&v6_only), "2001:db8::1"); - let none = NetworkSnapshot { - ip_addresses: Vec::new(), - ..interface - }; - assert_eq!(display_address(&none), "no IP"); -} diff --git a/src/tui/src/ui/app/resources/tests/agent_rows.rs b/src/tui/src/ui/app/resources/tests/agent_rows.rs deleted file mode 100644 index a5a944044..000000000 --- a/src/tui/src/ui/app/resources/tests/agent_rows.rs +++ /dev/null @@ -1,232 +0,0 @@ -//! Selecting, opening, and following agent rows. - -use super::*; - -#[cfg(unix)] -#[test] -fn enter_on_a_registered_session_agent_selects_its_sessions_rail_row() { - use medulla::protocol::HarnessProvider; - - let mut app = crate::ui::app::rail::tests::hosting_app(); - let harnesses = app.local_sessions().expect("test host").clone(); - let choice = harnesses - .choices() - .into_iter() - .find(|choice| choice.provider == HarnessProvider::Codex) - .expect("codex harness is configured"); - let session_id = harnesses - .open_unmanaged_named(&choice, "/", false, Some("agents acceptance".into())) - .expect("a /bin/sh session starts"); - - let pid = 45_001; - let started = 100; - let _registration = medulla::resources::launch::agent_registry().register_at( - medulla::resources::launch::AgentRegistration { - pid, - started_at_secs: started, - task_id: None, - session_id: Some(session_id.clone()), - provider: "claude".into(), - }, - ); - let mut process = test_agent_process(pid, "claude", 10.0); - process.start_time = started; - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default().with_processes(vec![process]), - )); - app.resources.agent_selected = Some(AgentIdentity { - host: None, - pid, - started, - }); - - assert!(app.resources_key(KeyCode::Enter)); - let sessions_tab = crate::ui::app::types::TABS - .iter() - .position(|tab| *tab == "Sessions") - .unwrap(); - assert_eq!(app.tab_index, sessions_tab); - let rows = app.rail_rows(); - let selected_row = rows - .iter() - .position(|row| row.session_id() == Some(session_id.as_str())) - .expect("registered session is on the rail"); - assert_eq!(app.rail_cursor(), selected_row); - harnesses.sessions.shutdown(); -} - -#[test] -fn remote_agent_rows_participate_in_selection_and_enter_opens_the_host_session() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let mut host = crate::ui::app::remote_hosts::RemoteHostState::default(); - host.rows.push(medulla::protocol::RemoteSessionRow { - id: "w_remote".into(), - label: "remote agent".into(), - provider: "claude".into(), - preset: None, - state: medulla::protocol::RemoteSessionState::Running, - cwd: "/remote/work".into(), - name: None, - thread_name: None, - started_at: 1_700_000_000_000, - last_output_at: 1_700_000_000_000, - busy: true, - working: true, - attention: None, - bracketed_paste: false, - last_error: None, - usage: Some(medulla::protocol::AgentUsage { - kind: "Claude".into(), - pid: 77, - cpu: 2.0, - rss: 1024, - threads: 2, - started_at: 1_700_000_000, - cpu_history: vec![1.0, 2.0], - }), - }); - app.remote_hosts.insert("tower".into(), host); - - assert!(app.resources_key(KeyCode::Down)); - assert_eq!( - app.resources.agent_selected, - Some(AgentIdentity { - host: Some("tower".into()), - pid: 77, - started: 1_700_000_000, - }) - ); - assert!(app.resources_key(KeyCode::Enter)); - let sessions_tab = crate::ui::app::types::TABS - .iter() - .position(|tab| *tab == "Sessions") - .unwrap(); - assert_eq!(app.tab_index, sessions_tab); - let rail_rows = app.rail_rows(); - let selected_row = rail_rows - .iter() - .position(|row| row.session_id() == Some("tower/w_remote")) - .expect("remote agent session is available on the Sessions rail"); - assert_eq!(app.rail_cursor(), selected_row); -} - -#[test] -fn agent_follow_tracks_identity_through_sorting_and_snapshot_reordering() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let processes: Vec<_> = (100..120) - .map(|pid| test_agent_process(pid, "claude", f64::from(pid))) - .collect(); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(processes.clone()), - )); - app.resources.agent_selected = Some(AgentIdentity { - host: None, - pid: 119, - started: 1, - }); - assert!(app.resources_key(KeyCode::Char('F'))); - assert_eq!( - app.resources.agent_follow, - Some(AgentIdentity { - host: None, - pid: 119, - started: 1 - }) - ); - - let render = |app: &mut App| { - let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 80, 24))) - .unwrap(); - terminal - .backend() - .buffer() - .content() - .iter() - .map(|cell| cell.symbol()) - .collect::() - }; - let first = render(&mut app); - assert_eq!( - app.resources.agent_selected, - Some(AgentIdentity { - host: None, - pid: 119, - started: 1 - }) - ); - assert!(first.contains("┐Follow 119┌"), "{first}"); - assert!( - first.contains("119"), - "followed process should be visible: {first}" - ); - - assert!(app.resources_key(KeyCode::Right)); - assert!(app.resources_key(KeyCode::Right)); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(processes.into_iter().rev().collect()), - )); - let reordered = render(&mut app); - assert_eq!( - app.resources.agent_selected, - Some(AgentIdentity { - host: None, - pid: 119, - started: 1 - }) - ); - assert!(reordered.contains("┐Follow 119┌")); - assert!( - reordered.contains("119"), - "followed process should stay visible: {reordered}" - ); -} - -#[test] -fn the_highlighted_m_in_the_cpu_title_opens_the_menu() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - assert!(app.resources_key(KeyCode::Char('m'))); - assert!(app.resources.menu_open); - let mut terminal = Terminal::new(TestBackend::new(170, 42)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 170, 42))) - .unwrap(); - let text = screen_rows(&terminal).join("\n"); - assert!(text.contains("┐menu┌───"), "menu overlay missing: {text}"); - assert!(text.contains("1-4 show or hide a box"), "{text}"); - assert!(app.resources_key(KeyCode::Char('m'))); - assert!(!app.resources.menu_open); -} - -#[test] -fn letters_typed_into_the_agent_filter_are_not_resources_shortcuts() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let resources_tab = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - app.tab_index = resources_tab; - app.resources.agent_filter_editing = true; - for letter in ['m', 'o', '?'] { - assert!(app.resources_key(KeyCode::Char(letter))); - } - assert_eq!(app.resources.agent_filter.as_deref(), Some("mo?")); - assert!(!app.resources.menu_open); - assert!(!app.resources.help_open); - assert_eq!(app.tab_index, resources_tab); -} diff --git a/src/tui/src/ui/app/resources/tests/agents.rs b/src/tui/src/ui/app/resources/tests/agents.rs deleted file mode 100644 index 50c166d33..000000000 --- a/src/tui/src/ui/app/resources/tests/agents.rs +++ /dev/null @@ -1,283 +0,0 @@ -//! Agent rows and the guarded process signals. - -use super::*; - -#[test] -fn agent_rows_render_with_classification_at_desktop_and_narrow_sizes() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default().with_processes(vec![ - test_agent_process(10, "claude", 12.0), - test_agent_process(20, "codex-acp", 22.0), - test_agent_process(30, "openhuman", 32.0), - test_agent_process(40, "aider", 42.0), - ]), - )); - for (width, height) in [(170, 42), (80, 24)] { - let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, width, height))) - .unwrap(); - let text = terminal - .backend() - .buffer() - .content() - .iter() - .map(|cell| cell.symbol()) - .collect::(); - for expected in [ - "Claude", - "Codex-ACP", - "OpenHuman", - "Aider", - "external", - "Pid:", - ] { - assert!( - text.contains(expected), - "missing {expected} at {width}x{height}: {text}" - ); - } - } -} - -/// Enter on a freshly opened tab acts on row zero without any cursor key having -/// stored it, so the detail pane must be told which row it is showing. -#[test] -fn enter_on_an_external_agent_stores_the_selection_the_detail_pane_reads() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(vec![test_agent_process(10, "claude", 12.0)]), - )); - assert_eq!(app.resources.agent_selected, None); - - assert!(app.resources_key(KeyCode::Enter)); - - assert!(app.resources.agent_detail); - assert_eq!( - app.resources.agent_selected.as_ref().map(|id| id.pid), - Some(10) - ); -} - -static SIGNALS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -static SIGNAL_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); -#[cfg(any(target_os = "linux", target_os = "macos"))] -fn test_process_owned(_pid: u32, _started: u64, uid: Option<&str>) -> bool { - uid == Some("test-user") -} -#[cfg(any(target_os = "linux", target_os = "macos"))] -fn never_owned(_pid: u32, _started: u64, _uid: Option<&str>) -> bool { - false -} -fn test_signal( - _pid: u32, - _started: u64, - _uid: Option<&str>, - _signal: AgentSignal, -) -> std::io::Result<()> { - SIGNALS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(()) -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -#[test] -fn agent_kill_waits_for_confirmation_and_uses_injected_signal_function() { - let _guard = SIGNAL_TEST_LOCK.lock().unwrap(); - SIGNALS.store(0, std::sync::atomic::Ordering::SeqCst); - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(vec![test_agent_process(42, "claude", 10.0)]), - )); - app.resources.agent_signal_fn = test_signal; - app.resources.agent_process_owned_fn = test_process_owned; - assert!(app.resources_key(KeyCode::Char('k'))); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 0); - assert!(app.resources.agent_signal_armed.is_some()); - assert!(app.resources_key(KeyCode::Char('y'))); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 0); - assert!(app.resources.agent_signal_armed.is_some()); - assert!(app.resources_key(KeyCode::Char('Y'))); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 1); - assert!(app.resources.agent_signal_armed.is_none()); -} - -static HIDDEN_SIGNALS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -fn hidden_test_signal( - _pid: u32, - _started: u64, - _uid: Option<&str>, - _signal: AgentSignal, -) -> std::io::Result<()> { - HIDDEN_SIGNALS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(()) -} - -#[test] -fn hidden_agents_box_cannot_arm_or_confirm_a_process_signal() { - HIDDEN_SIGNALS.store(0, std::sync::atomic::Ordering::SeqCst); - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(vec![test_agent_process(43, "claude", 10.0)]), - )); - app.resources.agent_signal_fn = hidden_test_signal; - app.resources.shown.agents = false; - - assert!(!app.resources_key(KeyCode::Char('k'))); - assert!(app.resources.agent_signal_armed.is_none()); - - app.resources.agent_signal_armed = Some(AgentSignalConfirmation { - pid: 43, - started: 1, - signal: AgentSignal::Kill, - stage: AgentSignalConfirmStage::First, - }); - assert!(app.resources_key(KeyCode::Char('y'))); - assert!(app.resources.agent_signal_armed.is_none()); - assert_eq!(HIDDEN_SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 0); -} - -#[test] -fn agent_signal_confirmation_stays_visible_in_detail_view() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let mut process = test_agent_process(44, "aider", 10.0); - process.exe = Some("/usr/bin/aider".into()); - process.cmd = vec![ - "API_TOKEN=envsecret".into(), - "aider".into(), - "--api-key".into(), - "supersecret".into(), - "--workspace".into(), - "/tmp/work".into(), - ]; - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default().with_processes(vec![process]), - )); - app.resources.agent_selected = Some(AgentIdentity { - host: None, - pid: 44, - started: 1, - }); - app.resources.agent_detail = true; - app.resources.shown.cpu = false; - app.resources.shown.mem = false; - app.resources.shown.net = false; - app.resources.agent_signal_armed = Some(AgentSignalConfirmation { - pid: 44, - started: 1, - signal: AgentSignal::Kill, - stage: AgentSignalConfirmStage::First, - }); - - let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 80, 24))) - .unwrap(); - let text = terminal - .backend() - .buffer() - .content() - .iter() - .map(|cell| cell.symbol()) - .collect::(); - assert!(text.contains("EXTERNAL PROCESS")); - for expected in [ - "Kind: Aider", - "PID: 44", - "Command: aider --api-key=[REDACTED] --workspace /tmp/work", - "Origin: external", - "Signal: kill", - "Target host: local", - ] { - assert!(text.contains(expected), "missing {expected} in {text}"); - } - assert!(!text.contains("supersecret")); - assert!(!text.contains("envsecret")); -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -#[test] -fn external_agent_signal_requires_a_second_explicit_confirmation() { - let _guard = SIGNAL_TEST_LOCK.lock().unwrap(); - SIGNALS.store(0, std::sync::atomic::Ordering::SeqCst); - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(vec![test_agent_process(45, "aider", 10.0)]), - )); - app.resources.agent_signal_fn = test_signal; - app.resources.agent_process_owned_fn = test_process_owned; - - assert!(app.resources_key(KeyCode::Char('k'))); - assert!(app.resources_key(KeyCode::Char('y'))); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 0); - assert!(app.resources.agent_signal_armed.is_some()); - assert!(app.resources_key(KeyCode::Char('Y'))); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 1); - assert!(app.resources.agent_signal_armed.is_none()); -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -#[test] -fn unowned_process_never_reaches_the_injected_signal_function() { - let _guard = SIGNAL_TEST_LOCK.lock().unwrap(); - SIGNALS.store(0, std::sync::atomic::Ordering::SeqCst); - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(vec![test_agent_process(46, "claude", 10.0)]), - )); - app.resources.agent_signal_fn = test_signal; - app.resources.agent_process_owned_fn = never_owned; - - assert!(app.resources_key(KeyCode::Char('k'))); - assert!(app.resources_key(KeyCode::Char('y'))); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 0); - assert!(app.resources.agent_signal_armed.is_none()); -} - -#[cfg(not(any(target_os = "linux", target_os = "macos")))] -#[test] -fn process_signals_are_disabled_on_unsupported_platforms() { - let _guard = SIGNAL_TEST_LOCK.lock().unwrap(); - SIGNALS.store(0, std::sync::atomic::Ordering::SeqCst); - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(vec![test_agent_process(47, "claude", 10.0)]), - )); - app.resources.agent_signal_fn = test_signal; - - assert!(app.resources_key(KeyCode::Char('k'))); - assert!(app.resources.agent_signal_armed.is_none()); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 0); - assert!(app.resources_key(KeyCode::Char('y'))); - assert_eq!(SIGNALS.load(std::sync::atomic::Ordering::SeqCst), 0); -} diff --git a/src/tui/src/ui/app/resources/tests/controls.rs b/src/tui/src/ui/app/resources/tests/controls.rs deleted file mode 100644 index f2591fb40..000000000 --- a/src/tui/src/ui/app/resources/tests/controls.rs +++ /dev/null @@ -1,267 +0,0 @@ -//! Clicks on the box titles and their buttons. - -use super::*; - -#[test] -fn clicking_a_panel_title_toggles_that_box() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - app.resources.rects = calc_sizes(Rect::new(0, 5, 170, 42), all(), &LayoutOptions::default()); - let cpu = app.resources.rects.cpu; - app.resources.hits.cpu_toggle = Rect::new(cpu.x + 2, cpu.y, 3, 1); - app.handle_click(cpu.x + 2, cpu.y); - assert!(!app.resources.shown.cpu); -} - -#[test] -fn cpu_title_controls_have_distinct_click_actions() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - let mut terminal = Terminal::new(TestBackend::new(190, 52)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(20, 5, 170, 42))) - .unwrap(); - let menu = app.resources.hits.menu; - let cpu_toggle = app.resources.hits.cpu_toggle; - let cpu = app.resources.rects.cpu; - let buffer = terminal.backend().buffer(); - let right = cpu.right(); - // ╭─┐¹cpu┌┐menu┌┐‹ preset 0 ›┌ … ┐- 2000ms +┌─╮ - for (hit, x, symbol) in [ - (cpu_toggle, cpu.x + 3, "¹"), - (menu, cpu.x + 9, "m"), - (app.resources.hits.preset_prev, cpu.x + 15, "‹"), - (app.resources.hits.preset_next, cpu.x + 26, "›"), - (app.resources.hits.interval_down, right - 13, "-"), - (app.resources.hits.interval_up, right - 4, "+"), - ] { - assert_eq!(buffer[(x, cpu.y)].symbol(), symbol, "at x={x}"); - assert!( - hit.contains((x, cpu.y).into()), - "visible control at x={x} misses hit rect {hit:?}" - ); - } - assert!(menu.width > 0); - assert!(cpu_toggle.width > 0); - assert!(!menu.intersects(cpu_toggle)); - app.handle_click(cpu.x + 10, cpu.y); - assert!(app.resources.menu_open); - assert!(app.resources.shown.cpu); - app.handle_click(cpu.x + 4, cpu.y); - assert!(!app.resources.shown.cpu); -} - -#[test] -fn cpu_panel_renders_sixteen_cores_without_clipping_at_common_sizes() { - let mut cpu = crate::ui::resources::CpuSnapshot { - model: Some("Test CPU".to_owned()), - cores: (0..16) - .map(|index| crate::ui::resources::CpuReading { - total: index as f32, - ..Default::default() - }) - .collect(), - frequencies_mhz: (0..16).map(|index| (index != 0).then_some(2400)).collect(), - load_average: [0.5, 0.25, 0.1], - uptime_seconds: Some(1234), - ..Default::default() - }; - let mut history = crate::ui::resources::sampler::ResourceHistory::default(); - let mut historical_cpu = cpu.clone(); - historical_cpu.core_temperatures_c = (0..16).map(|index| (index, 50.0, 90.0)).collect(); - history.push( - &crate::ui::resources::sampler::ResourceSnapshot::default().with_cpu(historical_cpu), - 20, - ); - let snapshot = crate::ui::resources::sampler::ResourceSnapshot::default() - .with_cpu(std::mem::take(&mut cpu)) - .with_history(Arc::new(history)); - for (width, height) in [(170, 42), (80, 24)] { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new(snapshot.clone())); - let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, width, height))) - .unwrap(); - let cpu_rect = app.resources.rects.cpu; - let buffer = terminal.backend().buffer(); - let text = (cpu_rect.y..cpu_rect.bottom()) - .flat_map(|y| (cpu_rect.x..cpu_rect.right()).map(move |x| buffer[(x, y)].symbol())) - .collect::(); - for core in 0..16 { - assert!( - text.contains(&format!("C{core} ")), - "missing core {core} at {width}x{height}: {text}" - ); - } - assert!(text.contains("2.4 GHz"), "{text}"); - if width >= 100 { - assert!(text.contains("Test CPU")); - assert!(text.contains("Load avg: 0.50 0.25 0.10")); - let first_core_row = (0..buffer.area.height) - .map(|y| { - (cpu_rect.x..cpu_rect.right()) - .map(|x| buffer[(x, y)].symbol()) - .collect::() - }) - .find(|row| row.contains("C0 ")) - .expect("a row for core 0"); - assert!( - first_core_row.chars().any(|c| ('⡀'..='⣿').contains(&c)), - "missing per-core graphs at {width}x{height}: {first_core_row}" - ); - } else { - assert!( - text.contains("Load avg 0.5"), - "missing compact load at {width}x{height}: {text}" - ); - } - assert!(!text.contains("Pkg")); - assert!(!text.contains("°C")); - } -} - -#[test] -fn cpu_panel_shows_zero_load_average_with_required_label() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let snapshot = crate::ui::resources::sampler::ResourceSnapshot::default().with_cpu( - crate::ui::resources::CpuSnapshot { - load_average: [0.0; 3], - ..Default::default() - }, - ); - app.set_resource_snapshot(Arc::new(snapshot)); - let mut terminal = Terminal::new(TestBackend::new(170, 42)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 170, 42))) - .unwrap(); - let cpu = app.resources.rects.cpu; - let buffer = terminal.backend().buffer(); - let text = (cpu.y..cpu.bottom()) - .flat_map(|y| (cpu.x..cpu.right()).map(move |x| buffer[(x, y)].symbol())) - .collect::(); - assert!(text.contains("Load avg: 0.00 0.00 0.00")); -} - -#[test] -fn cpu_frequency_mode_formats_mhz_ghz_and_auto() { - assert_eq!(super::super::cpu::format_frequency(800, "auto"), "800 MHz"); - assert_eq!(super::super::cpu::format_frequency(2400, "auto"), "2.4 GHz"); - assert_eq!(super::super::cpu::format_frequency(2400, "mhz"), "2400 MHz"); - assert_eq!(super::super::cpu::format_frequency(800, "ghz"), "0.8 GHz"); -} - -#[test] -fn each_panel_title_button_toggles_only_its_box() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - let mut terminal = Terminal::new(TestBackend::new(190, 52)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(20, 5, 170, 42))) - .unwrap(); - let buffer = terminal.backend().buffer(); - let targets = [ - ( - app.resources.rects.cpu, - app.resources.hits.cpu_toggle, - 3, - '1', - ), - ( - app.resources.rects.mem, - app.resources.hits.mem_toggle, - 3, - '2', - ), - ( - app.resources.rects.net, - app.resources.hits.net_toggle, - 3, - '3', - ), - ( - app.resources.rects.agents, - app.resources.hits.agents_toggle, - 3, - '4', - ), - ]; - for (panel, hit, offset, key) in targets { - assert!(hit.width > 0); - let x = panel.x + offset; - let superscript = ['¹', '²', '³', '⁴'][key as usize - '1' as usize]; - assert_eq!(buffer[(x, panel.y)].symbol(), superscript.to_string()); - assert!( - hit.contains((x, panel.y).into()), - "visible [{key}] misses hit rect {hit:?}" - ); - app.handle_click(x, panel.y); - let shown = match key { - '1' => app.resources.shown.cpu, - '2' => app.resources.shown.mem, - '3' => app.resources.shown.net, - _ => app.resources.shown.agents, - }; - assert!(!shown, "clicking [{key}] should hide its own box"); - } -} - -#[test] -fn cpu_title_preset_and_interval_buttons_are_clickable() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - app.resources - .presets - .push("cpu:1:block,mem:1:block,net:0:block,agents:0:tty".into()); - let mut terminal = Terminal::new(TestBackend::new(190, 52)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(20, 5, 170, 42))) - .unwrap(); - let hits = app.resources.hits; - for hit in [ - hits.preset_prev, - hits.preset_next, - hits.interval_down, - hits.interval_up, - ] { - assert!(hit.width > 0); - } - app.handle_click(hits.preset_next.x, hits.preset_next.y); - assert_eq!(app.resources.preset, 1); - app.handle_click(hits.preset_prev.x, hits.preset_prev.y); - assert_eq!(app.resources.preset, 0); - app.handle_click(hits.interval_up.x, hits.interval_up.y); - assert_eq!(app.resources.interval_ms, 2_100); - app.handle_click(hits.interval_down.x, hits.interval_down.y); - assert_eq!(app.resources.interval_ms, 2_000); -} diff --git a/src/tui/src/ui/app/resources/tests/mod.rs b/src/tui/src/ui/app/resources/tests/mod.rs deleted file mode 100644 index 13e5dae46..000000000 --- a/src/tui/src/ui/app/resources/tests/mod.rs +++ /dev/null @@ -1,433 +0,0 @@ -//! Unit tests for the Resources tab state, layout, and panels. - -use super::{ - layout::calc_sizes, - types::{ - AgentIdentity, AgentSignal, AgentSignalConfirmStage, AgentSignalConfirmation, - LayoutOptions, ResourcesState, ShownBoxes, - }, -}; -use crate::ui::app::App; -use crossterm::event::KeyCode; -use crossterm::event::{KeyEvent, KeyModifiers}; -use medulla::backend::MockBackend; -use medulla::config::LoadedConfig; -use ratatui::layout::Rect; -use ratatui::style::Color; -use ratatui::{backend::TestBackend, Terminal}; -use std::sync::Arc; - -fn all() -> ShownBoxes { - ShownBoxes { - cpu: true, - mem: true, - net: true, - agents: true, - } -} - -#[test] -fn default_layout_uses_btop_shares_at_common_terminal_sizes() { - for (area, cpu_h, mem_w, mem_h, net_h, agents_w) in [ - (Rect::new(0, 0, 170, 42), 14, 77, 16, 12, 93), - (Rect::new(0, 0, 80, 24), 8, 36, 9, 7, 44), - ] { - let boxes = calc_sizes(area, all(), &LayoutOptions::default()); - assert_eq!(boxes.cpu.height, cpu_h); - assert_eq!(boxes.mem.width, mem_w); - assert_eq!(boxes.mem.height, mem_h); - assert_eq!(boxes.net.height, net_h); - assert_eq!(boxes.agents.width, agents_w); - assert_eq!( - boxes.mem.height + boxes.net.height, - area.height - boxes.cpu.height - ); - } -} - -#[test] -fn hidden_agents_widens_memory_and_network_and_cpu_alone_fills_area() { - let mut shown = all(); - shown.agents = false; - let boxes = calc_sizes(Rect::new(0, 0, 170, 42), shown, &LayoutOptions::default()); - assert_eq!(boxes.mem.width, 170); - assert_eq!(boxes.net.width, 170); - assert_eq!(boxes.mem.height, 16); - assert_eq!(boxes.net.height, 12); - assert_eq!(boxes.mem.height + boxes.net.height, 42 - boxes.cpu.height); - shown = ShownBoxes { - cpu: true, - ..Default::default() - }; - let boxes = calc_sizes(Rect::new(0, 0, 170, 42), shown, &LayoutOptions::default()); - assert_eq!(boxes.cpu, Rect::new(0, 0, 170, 42)); -} - -#[test] -fn every_visible_box_combination_has_a_rect_or_a_too_small_result() { - for area in [Rect::new(0, 0, 170, 42), Rect::new(0, 0, 80, 24)] { - for mask in 0..16 { - let shown = ShownBoxes { - cpu: mask & 1 != 0, - mem: mask & 2 != 0, - net: mask & 4 != 0, - agents: mask & 8 != 0, - }; - let boxes = calc_sizes(area, shown, &LayoutOptions::default()); - let every_visible_box_has_area = [ - (shown.cpu, boxes.cpu), - (shown.mem, boxes.mem), - (shown.net, boxes.net), - (shown.agents, boxes.agents), - ] - .into_iter() - .all(|(shown, rect)| !shown || (rect.width > 0 && rect.height > 0)); - assert!( - boxes.too_small.is_some() || every_visible_box_has_area, - "shown boxes {shown:?} have an unplaced panel at {area:?}: {boxes:?}" - ); - } - } -} - -#[test] -fn cpu_hidden_gives_mem_seventy_two_percent_and_net_the_remaining_share() { - for agents in [false, true] { - let shown = ShownBoxes { - cpu: false, - mem: true, - net: true, - agents, - }; - let boxes = calc_sizes(Rect::new(0, 0, 170, 42), shown, &LayoutOptions::default()); - assert_eq!(boxes.mem.height, 30); - assert_eq!(boxes.net.height, 12); - assert_eq!(boxes.mem.height + boxes.net.height, 42); - if agents { - assert_eq!(boxes.mem.width, 77); - assert_eq!(boxes.agents.width, 93); - } else { - assert_eq!(boxes.mem.width, 170); - assert_eq!(boxes.net.width, 170); - } - } -} - -#[test] -fn undersized_terminal_requests_too_small_message() { - let boxes = calc_sizes(Rect::new(0, 0, 50, 7), all(), &LayoutOptions::default()); - assert_eq!(boxes.too_small, Some(60)); -} - -#[test] -fn agents_take_the_full_remaining_area_before_mem_and_net_are_suppressed() { - let boxes = calc_sizes(Rect::new(0, 0, 70, 24), all(), &LayoutOptions::default()); - assert_eq!(boxes.agents.width, 70); - assert_eq!(boxes.mem.width, 0); - assert_eq!(boxes.net.width, 0); -} - -#[test] -fn resource_keys_toggle_boxes_cycle_presets_and_clamp_interval() { - let mut state = ResourcesState::default(); - for (key, expected) in [ - (KeyCode::Char('1'), false), - (KeyCode::Char('2'), false), - (KeyCode::Char('3'), false), - (KeyCode::Char('4'), false), - ] { - assert!(state.key(key)); - assert_eq!( - [ - state.shown.cpu, - state.shown.mem, - state.shown.net, - state.shown.agents - ]["1234" - .chars() - .position(|c| c - == match key { - KeyCode::Char(c) => c, - _ => ' ', - }) - .unwrap()], - expected - ); - } - state.presets.push("cpu:1:block,agents:0:tty".into()); - assert!(state.key(KeyCode::Char('P'))); - assert_eq!(state.preset, 1); - state.interval_ms = 9_950; - state.key(KeyCode::Char('+')); - assert_eq!(state.interval_ms, 10_000); - state.interval_ms = 150; - state.key(KeyCode::Char('-')); - assert_eq!(state.interval_ms, 100); -} - -#[test] -fn disks_and_io_keys_toggle_the_memory_panel_modes() { - let mut state = ResourcesState::default(); - assert!(state.show_disks && !state.io_mode); - assert!(state.key(KeyCode::Char('d'))); - assert!(!state.show_disks); - assert!(state.key(KeyCode::Char('i'))); - assert!(state.io_mode); - assert!(state.key(KeyCode::Char('i'))); - assert!(!state.io_mode); -} - -#[test] -fn io_graph_speed_limits_override_per_mount_in_mib_per_second() { - let config = medulla::config::ResourcesConfig { - io_graph_speeds: "/mnt/data:1 /boot:4".into(), - ..Default::default() - }; - assert_eq!(super::io_graph_speed(&config, "/mnt/data"), 1.0); - assert_eq!(super::io_graph_speed(&config, "/boot"), 4.0); - assert_eq!(super::io_graph_speed(&config, "/"), 100.0); -} - -#[test] -fn selecting_a_preset_shows_only_the_boxes_named_by_its_entries() { - let mut state = ResourcesState { - presets: vec![ - "cpu:0:default,mem:0:default,net:0:default,agents:1:default".into(), - "cpu:1:block,net:0:tty".into(), - ], - ..ResourcesState::default() - }; - assert!(state.key(KeyCode::Char('P'))); - assert_eq!( - state.shown, - ShownBoxes { - cpu: true, - mem: false, - net: true, - agents: false, - } - ); -} - -/// Control chords are global: with Agents visible, ⌃T must reach the global -/// session-picker chord instead of the table's bare `t` (terminate) binding. -#[test] -fn control_chords_on_the_resources_tab_are_not_agent_shortcuts() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - app.set_resource_snapshot(Arc::new( - crate::ui::resources::sampler::ResourceSnapshot::default() - .with_processes(vec![test_agent_process(10, "claude", 12.0)]), - )); - - app.on_key(KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL)); - - assert!( - app.resources.agent_signal_armed.is_none(), - "⌃T must not arm a terminate signal" - ); -} - -#[test] -fn tab_keys_still_cycle_all_tabs() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - for _ in 0..crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap() - { - app.on_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); - } - assert_eq!(app.tab(), "Resources"); - app.on_key(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - assert!(!app.resources.shown.cpu); - assert_eq!(app.loaded.config.resources.update_ms, 2_000); - app.on_key(KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE)); - assert_eq!(app.loaded.config.resources.update_ms, 2_100); - app.on_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); - let resources_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - assert_eq!( - app.tab(), - crate::ui::app::TABS[(resources_index + 1) % crate::ui::app::TABS.len()] - ); -} - -#[test] -fn resources_keyboard_changes_persist_and_reload() { - let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join("config.toml"); - let mut loaded = LoadedConfig::defaults(path.display().to_string()); - loaded.config.resources.presets = "cpu:0:default,mem:0:default,net:0:default,agents:1:default cpu:1:block,mem:1:block,net:0:block,agents:0:tty".into(); - let mut app = App::new(Arc::new(MockBackend::new()), loaded); - app.set_config_path(path.clone()); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - app.on_key(KeyEvent::new(KeyCode::Char('+'), KeyModifiers::NONE)); - app.on_key(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - app.on_key(KeyEvent::new(KeyCode::Char('P'), KeyModifiers::NONE)); - - let path_text = path.to_str().unwrap().to_owned(); - let loaded = - medulla::config::load_config(Some(&path_text), &Default::default(), temp.path()).unwrap(); - assert_eq!(loaded.config.resources.update_ms, 2_100); - assert_eq!(loaded.config.resources.preset, 1); - assert_eq!(loaded.config.resources.shown_boxes, "cpu,mem,net,agents"); - assert_eq!(loaded.config.resources.cpu_bottom, Some(true)); - assert_eq!(loaded.config.resources.mem_below_net, Some(true)); - assert_eq!(loaded.config.resources.agents_left, Some(true)); -} - -#[test] -fn box_visibility_changes_persist_and_reload_without_a_preset_change() { - let temp = tempfile::tempdir().unwrap(); - let path = temp.path().join("config.toml"); - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults(path.display().to_string()), - ); - app.set_config_path(path.clone()); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - app.on_key(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE)); - - let path_text = path.to_str().unwrap().to_owned(); - let loaded = - medulla::config::load_config(Some(&path_text), &Default::default(), temp.path()).unwrap(); - assert_eq!(loaded.config.resources.shown_boxes, "mem,net,agents"); -} - -#[test] -fn explicit_layout_options_override_preset_zero() { - let config = medulla::config::ResourcesConfig { - preset: 0, - cpu_bottom: Some(true), - mem_below_net: Some(true), - agents_left: Some(true), - ..Default::default() - }; - let state = ResourcesState::from_config(&config); - assert_eq!(state.preset, 0); - assert!(state.opts.cpu_bottom); - assert!(state.opts.mem_below_net); - assert!(state.opts.agents_left); -} - -/// Each buffer row as a string, for assertions about what one line shows. -fn screen_rows(terminal: &Terminal) -> Vec { - let buffer = terminal.backend().buffer(); - (0..buffer.area.height) - .map(|y| { - (0..buffer.area.width) - .map(|x| buffer[(x, y)].symbol()) - .collect::() - }) - .collect() -} - -fn test_agent_process( - pid: u32, - command: &str, - cpu: f64, -) -> crate::ui::resources::sampler::ProcessSnapshot { - crate::ui::resources::sampler::ProcessSnapshot { - pid, - ppid: None, - exe: Some(command.into()), - cmd: vec![command.into()], - cwd: Some(format!("/work/{command}")), - start_time: 1, - owner_uid: Some("test-user".into()), - cpu_percent: cpu, - memory_bytes: 2 * 1024 * 1024, - disk_read_bytes: 0, - disk_written_bytes: 0, - threads: 2, - } -} - -mod agent_rows; -mod agents; -mod controls; -mod panels; - -#[test] -fn short_terminals_without_agents_keep_every_panel_inside_the_area() { - let shown = ShownBoxes { - agents: false, - ..all() - }; - for height in 8..=14 { - let area = Rect::new(0, 0, 100, height); - let boxes = calc_sizes(area, shown, &LayoutOptions::default()); - for rect in [boxes.cpu, boxes.mem, boxes.net] { - assert!(rect.bottom() <= area.bottom(), "height {height}: {rect:?}"); - } - } -} - -#[test] -fn swapped_network_directions_scale_each_graph_by_its_own_samples() { - let mut state = ResourcesState { - swap_upload_download: true, - ..ResourcesState::default() - }; - let mut snapshot = crate::ui::resources::sampler::ResourceSnapshot::default(); - snapshot - .networks - .push(crate::ui::resources::sampler::NetworkSnapshot { - interface: "eth0".into(), - up: true, - connected: true, - ip_addresses: Vec::new(), - received_bytes_per_second: 10.0, - transmitted_bytes_per_second: 50_000_000.0, - total_received_bytes: 0, - total_transmitted_bytes: 0, - }); - state.net_iface = Some("eth0".into()); - for _ in 0..5 { - state.sample_network(&snapshot); - } - assert!( - state.net_download_scaler.max() > state.net_upload_scaler.max(), - "the busy transmitted direction is drawn as download when swapped" - ); -} - -#[test] -fn escape_cancels_an_armed_signal_while_the_menu_is_open() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.tab_index = crate::ui::app::TABS - .iter() - .position(|tab| *tab == "Resources") - .unwrap(); - app.resources.menu_open = true; - app.resources.agent_signal_armed = Some(AgentSignalConfirmation { - pid: 1, - started: 1, - signal: AgentSignal::Kill, - stage: AgentSignalConfirmStage::First, - }); - app.on_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); - assert!(!app.resources.menu_open); - assert!(app.resources.agent_signal_armed.is_none()); -} diff --git a/src/tui/src/ui/app/resources/tests/panels.rs b/src/tui/src/ui/app/resources/tests/panels.rs deleted file mode 100644 index 727425534..000000000 --- a/src/tui/src/ui/app/resources/tests/panels.rs +++ /dev/null @@ -1,450 +0,0 @@ -//! How each box draws at common terminal sizes. - -use super::*; - -#[test] -fn resources_draw_btop_style_titled_boxes() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let backend = TestBackend::new(170, 42); - let mut terminal = Terminal::new(backend).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 170, 42))) - .unwrap(); - let text = screen_rows(&terminal).join("\n"); - assert!(text.contains("╭─┐¹cpu┌┐menu┌┐‹ preset 0 ›┌"), "{text}"); - assert!(text.contains("┐- 2000ms +┌─╮"), "{text}"); - assert!(text.contains("╭─┐²mem┌"), "{text}"); - assert!(text.contains("╭─┐³net┌"), "{text}"); - assert!(text.contains("╭─┐⁴agents┌┐filter┌"), "{text}"); - assert!(text.contains("┘↑ select ↓└"), "{text}"); -} - -#[test] -fn resources_paint_a_solid_black_background_by_default() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let theme = app.theme.resources; - assert_eq!(theme.main_bg, Color::Rgb(0, 0, 0)); - let backend = TestBackend::new(170, 42); - let mut terminal = Terminal::new(backend).unwrap(); - for menu_open in [false, true] { - app.resources.menu_open = menu_open; - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 170, 42))) - .unwrap(); - let buffer = terminal.backend().buffer(); - for y in 0..buffer.area.height { - for x in 0..buffer.area.width { - let bg = buffer[(x, y)].bg; - assert!( - bg == theme.main_bg || bg == theme.selected_bg, - "cell ({x}, {y}) has background {bg:?} with the menu open: {menu_open}" - ); - } - } - } -} - -#[test] -fn network_panel_renders_at_desktop_and_narrow_widths() { - let config = medulla::config::ResourcesConfig::default(); - let theme = crate::ui::theme::ResourcesTheme::default(); - let mut snapshot = crate::ui::resources::sampler::ResourceSnapshot::default(); - snapshot - .networks - .push(crate::ui::resources::sampler::NetworkSnapshot { - interface: "eth0".into(), - up: true, - connected: true, - ip_addresses: vec!["192.0.2.2".into()], - received_bytes_per_second: 4096.0, - transmitted_bytes_per_second: 2048.0, - total_received_bytes: 8192, - total_transmitted_bytes: 4096, - }); - let mut history = crate::ui::resources::sampler::ResourceHistory::default(); - history.push(&snapshot, 8); - let snapshot = snapshot.with_history(Arc::new(history)); - let draw = |terminal: &mut Terminal, - config: &medulla::config::ResourcesConfig, - width: u16| { - let view = super::super::net::NetView { - config, - theme: &theme, - selected: Some("eth0"), - zero_offsets: (0, 0), - download_max: 10_240.0, - upload_max: 10_240.0, - auto: true, - sync: false, - }; - let mut hits = super::super::types::ResourceHits::default(); - terminal - .draw(|frame| { - super::super::net::draw( - frame, - Rect::new(0, 0, width, 11), - &snapshot, - &view, - &mut hits, - ) - }) - .unwrap(); - screen_rows(terminal) - }; - for width in [170, 45] { - let mut terminal = Terminal::new(TestBackend::new(width, 11)).unwrap(); - let rows = draw(&mut terminal, &config, width); - let text = rows.join("\n"); - assert!(text.contains("eth0"), "interface absent at width {width}"); - if width == 45 { - assert!(text.contains("▼ 4.00 KiB/s Σ 8.00 KiB"), "{text}"); - assert!(text.contains("▲ 2.00 KiB/s Σ 4.00 KiB"), "{text}"); - continue; - } - assert!(text.contains("┐192.0.2.2┌"), "address absent: {text}"); - let line = |needle: &str| { - rows.iter() - .find(|row| row.contains(needle)) - .cloned() - .unwrap_or_else(|| panic!("no row containing {needle:?}: {text}")) - }; - assert!(line("▼ 4.00 KiB/s").contains("(32.0 Kibps)"), "{text}"); - assert!(line("▼ Top:").contains("(32.0 Kibps)"), "{text}"); - assert!(line("▼ Total:").contains("8.00 KiB"), "{text}"); - assert!(line("▲ Top:").contains("(16.0 Kibps)"), "{text}"); - assert!(line("▲ Total:").contains("4.00 KiB"), "{text}"); - - let mut swapped = config.clone(); - swapped.swap_upload_download = true; - let rows = draw(&mut terminal, &swapped, width); - let text = rows.join("\n"); - let line = |needle: &str| { - rows.iter() - .find(|row| row.contains(needle)) - .cloned() - .unwrap_or_else(|| panic!("no row containing {needle:?}: {text}")) - }; - assert!( - line("▼ Top:").contains("(16.0 Kibps)") && line("▼ Total:").contains("4.00 KiB"), - "swapped top/totals must follow displayed directions: {text}" - ); - assert!(line("▲ Total:").contains("8.00 KiB"), "{text}"); - } -} - -#[test] -fn network_zero_offsets_totals_and_interface_keys_skip_down_links() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let mut sample = crate::ui::resources::sampler::ResourceSnapshot::default(); - for (interface, up, rx) in [ - ("lo", true, 20), - ("eth0", false, 40), - ("wlan0", true, 100), - ("enp1s0", true, 300), - ] { - sample - .networks - .push(crate::ui::resources::sampler::NetworkSnapshot { - interface: interface.into(), - up, - connected: up && interface != "lo", - ip_addresses: Vec::new(), - received_bytes_per_second: 0.0, - transmitted_bytes_per_second: 0.0, - total_received_bytes: rx, - total_transmitted_bytes: rx * 2, - }); - } - app.set_resource_snapshot(Arc::new(sample.clone())); - app.resources.net_iface = Some("wlan0".into()); - assert!(app.resources_key(KeyCode::Char('z'))); - assert_eq!(app.resources.net_zero_offsets["wlan0"], (100, 200)); - let mut later = sample.clone(); - let wlan = later - .networks - .iter_mut() - .find(|entry| entry.interface == "wlan0") - .unwrap(); - wlan.total_received_bytes += 10; - wlan.total_transmitted_bytes += 20; - app.set_resource_snapshot(Arc::new(later)); - let mut terminal = Terminal::new(TestBackend::new(170, 42)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 170, 42))) - .unwrap(); - let text = terminal - .backend() - .buffer() - .content() - .iter() - .map(|cell| cell.symbol()) - .collect::(); - let rows = screen_rows(&terminal); - let total = |arrow: &str| { - rows.iter() - .find(|row| row.contains(&format!("{arrow} Total:"))) - .cloned() - .unwrap_or_default() - }; - assert!( - total("▼").contains("10 B") && total("▲").contains("20 B"), - "zeroed counters must continue from their offset: {text}" - ); - assert!(app.resources_key(KeyCode::Char('n'))); - assert_eq!(app.resources.net_iface.as_deref(), Some("enp1s0")); - assert!(app.resources_key(KeyCode::Char('z'))); - assert_eq!(app.resources.net_zero_offsets["enp1s0"], (300, 600)); - assert!(app.resources_key(KeyCode::Char('b'))); - assert_eq!(app.resources.net_iface.as_deref(), Some("wlan0")); - assert_eq!(app.resources.net_zero_offsets["wlan0"], (100, 200)); -} - -#[test] -fn network_border_auto_and_sync_controls_are_clickable() { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - let mut terminal = Terminal::new(TestBackend::new(170, 42)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 170, 42))) - .unwrap(); - assert!(app.resources.net_auto); - let auto = app.resources.hits.net_auto; - app.resources_click(auto.x, auto.y); - assert!(!app.resources.net_auto); - let sync = app.resources.hits.net_sync; - app.resources_click(sync.x, sync.y); - assert!(app.resources.net_sync); -} - -#[test] -fn memory_and_disk_panel_renders_at_desktop_and_compact_terminal_sizes() { - let mut loaded = LoadedConfig::defaults("test.json".into()); - loaded.config.resources.shown_boxes = "mem".into(); - let mut history = crate::ui::resources::sampler::ResourceHistory::default(); - let sample = crate::ui::resources::sampler::ResourceSnapshot { - memory_total_bytes: 16_000, - memory_used_bytes: 8_000, - memory_available_bytes: 8_000, - memory_cached_bytes: 2_000, - memory_free_bytes: 1_000, - swap_total_bytes: 4_000, - swap_used_bytes: 500, - disks: vec![crate::ui::resources::sampler::DiskSnapshot { - device: "/dev/sda1".into(), - mount: "/mnt/data".into(), - total_bytes: 10_000, - used_bytes: 2_500, - read_bytes_per_second: (32 * 1024 * 1024) as f64, - write_bytes_per_second: (64 * 1024 * 1024) as f64, - busy_percent: Some(15.0), - has_io: true, - }], - ..Default::default() - }; - history.push(&sample, 8); - let sample = sample.with_history(Arc::new(history)); - for (width, height) in [(170, 42), (80, 24), (60, 16)] { - for (mem_graphs, show_disks, io_mode, combined, speeds) in [ - (true, true, false, false, ""), - (false, true, false, false, ""), - (true, true, true, true, ""), - (true, true, true, false, "/mnt/data:1"), - (true, false, false, false, ""), - (true, false, true, false, ""), - ] { - let mut configured = loaded.clone(); - configured.config.resources.mem_graphs = mem_graphs; - configured.config.resources.show_disks = show_disks; - configured.config.resources.io_mode = io_mode; - configured.config.resources.io_graph_combined = combined; - configured.config.resources.io_graph_speeds = speeds.into(); - configured.config.resources.swap_disk = true; - let mut app = App::new(Arc::new(MockBackend::new()), configured); - app.set_resource_snapshot(Arc::new(sample.clone())); - let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, width, height))) - .unwrap(); - let text = terminal - .backend() - .buffer() - .content() - .iter() - .map(|cell| cell.symbol()) - .collect::(); - let mem = app.resources.rects.mem; - let buffer = terminal.backend().buffer(); - let inside = (mem.y + 1..mem.bottom() - 1) - .flat_map(|y| (mem.x + 1..mem.right() - 1).map(move |x| buffer[(x, y)].symbol())) - .collect::(); - assert!( - inside.contains("Total:"), - "total missing at {width}x{height}: {text}" - ); - assert!( - inside.contains("Used"), - "used missing at {width}x{height}: {text}" - ); - assert!( - inside.contains("50%"), - "RAM percentage missing at {width}x{height}: {text}" - ); - assert_eq!( - inside.contains("data"), - show_disks, - "disk visibility at {width}x{height}: {text}" - ); - assert!( - inside.contains("12%"), - "swap missing at {width}x{height}: {text}" - ); - assert_eq!( - inside.contains("swap"), - show_disks, - "swap disk visibility at {width}x{height}: {text}" - ); - if mem_graphs { - assert!( - inside.chars().any(|c| ('⡀'..='⣿').contains(&c)), - "memory history graphs missing at {width}x{height}: {text}" - ); - } else { - assert!( - inside.contains('■'), - "memory meters missing at {width}x{height}: {text}" - ); - } - if show_disks && width == 170 { - if io_mode { - assert!( - inside.contains("▲32M ▼64M"), - "IO rates missing at {width}x{height}: {text}" - ); - } else { - assert!( - inside.contains("IO%"), - "per-disk busy graph missing at {width}x{height}: {text}" - ); - } - } - } - } -} - -/// btop's disks column: every volume headed by a divider carrying its name and -/// size, IO above the used meter, swap second and with no IO row of its own. -#[test] -fn disks_are_listed_btop_style_with_swap_after_root() { - let disk = |device: &str, mount: &str, has_io| crate::ui::resources::sampler::DiskSnapshot { - device: device.into(), - mount: mount.into(), - total_bytes: 2 * 1024 * 1024 * 1024 * 1024, - used_bytes: 1024 * 1024 * 1024 * 1024, - read_bytes_per_second: 0.0, - write_bytes_per_second: 0.0, - busy_percent: None, - has_io, - }; - let snapshot = crate::ui::resources::sampler::ResourceSnapshot { - disks: vec![ - disk("/dev/disk3s1s1", "/", true), - disk("/dev/disk3s6", "/System/Volumes/VM", true), - disk("/dev/disk1s2", "/System/Volumes/xarts", false), - ], - swap_total_bytes: 6 * 1024 * 1024 * 1024, - swap_used_bytes: 3 * 1024 * 1024 * 1024, - ..Default::default() - }; - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new(snapshot)); - let mut terminal = Terminal::new(TestBackend::new(170, 42)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 170, 42))) - .unwrap(); - let rows = screen_rows(&terminal); - let headers: Vec<(usize, &str)> = rows - .iter() - .enumerate() - .filter_map(|(y, row)| { - ["root", "swap", "VM", "xarts"] - .into_iter() - .find(|name| row.contains(&format!("├─{name}─"))) - .map(|name| (y, name)) - }) - .collect(); - assert_eq!( - headers.iter().map(|(_, name)| *name).collect::>(), - ["root", "swap", "VM", "xarts"], - "{}", - rows.join("\n") - ); - let row = |y: usize| rows[y].as_str(); - let (root, swap) = (headers[0].0, headers[1].0); - assert!(row(root).contains("2.00 TiB─┤"), "{}", row(root)); - assert!(row(root + 1).contains("IO%"), "{}", row(root + 1)); - assert!(row(root + 2).contains("Used:"), "{}", row(root + 2)); - assert!(row(swap + 1).contains("Used:"), "{}", row(swap + 1)); - assert_eq!(headers[2].0, swap + 2, "swap has no IO row"); - let xarts = headers[3].0; - assert!( - row(xarts + 1).contains("Used:"), - "a volume with no IO counters has no IO row" - ); -} - -/// More volumes than the column has room to graph: every one is still listed, -/// and the spare rows give IO graphs to the first disks, root first. -#[test] -fn a_crowded_disks_column_lists_every_volume_and_graphs_root_first() { - let disk = |index: usize| crate::ui::resources::sampler::DiskSnapshot { - device: format!("/dev/disk3s{index}"), - mount: if index == 0 { - "/".into() - } else { - format!("/Volumes/v{index}") - }, - total_bytes: 1024, - used_bytes: 512, - read_bytes_per_second: 0.0, - write_bytes_per_second: 0.0, - busy_percent: None, - has_io: true, - }; - let snapshot = crate::ui::resources::sampler::ResourceSnapshot { - disks: (0..10).map(disk).collect(), - ..Default::default() - }; - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.set_resource_snapshot(Arc::new(snapshot)); - let mut terminal = Terminal::new(TestBackend::new(215, 61)).unwrap(); - terminal - .draw(|frame| app.draw_resources(frame, Rect::new(0, 0, 215, 61))) - .unwrap(); - let rows = screen_rows(&terminal); - let text = rows.join("\n"); - for name in std::iter::once("root".to_string()).chain((1..10).map(|i| format!("v{i}"))) { - assert!( - text.contains(&format!("├─{name}─")), - "{name} missing:\n{text}" - ); - } - let root = rows.iter().position(|row| row.contains("├─root─")).unwrap(); - assert!(rows[root + 1].contains("IO%"), "{}", rows[root + 1]); -} diff --git a/src/tui/src/ui/app/resources/types.rs b/src/tui/src/ui/app/resources/types.rs deleted file mode 100644 index f2fbab8dc..000000000 --- a/src/tui/src/ui/app/resources/types.rs +++ /dev/null @@ -1,395 +0,0 @@ -//! State and layout types for the Resources tab. - -use ratatui::layout::Rect; - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub(in crate::ui::app) struct ShownBoxes { - pub cpu: bool, - pub mem: bool, - pub net: bool, - pub agents: bool, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub(in crate::ui::app) struct LayoutOptions { - pub cpu_bottom: bool, - pub mem_below_net: bool, - pub agents_left: bool, -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub(in crate::ui::app) struct BoxRects { - pub cpu: Rect, - pub mem: Rect, - pub net: Rect, - pub agents: Rect, - pub too_small: Option, -} - -#[derive(Debug, Clone)] -pub(in crate::ui::app) struct ResourcesState { - pub shown: ShownBoxes, - pub opts: LayoutOptions, - pub rects: BoxRects, - pub interval_ms: u64, - pub preset: usize, - pub presets: Vec, - pub hits: ResourceHits, - pub menu_open: bool, - pub help_open: bool, - pub show_disks: bool, - pub io_mode: bool, - pub net_auto: bool, - pub net_sync: bool, - pub net_download: u64, - pub net_upload: u64, - pub net_iface: Option, - pub swap_upload_download: bool, - pub net_zeroed: bool, - pub net_zero_offsets: std::collections::HashMap, - pub net_download_scaler: crate::ui::resources::net::NetScaler, - pub net_upload_scaler: crate::ui::resources::net::NetScaler, - pub agent_sort: AgentSort, - pub agent_reverse: bool, - pub agent_tree: bool, - pub agent_filter: Option, - pub agent_filter_editing: bool, - pub agent_selected: Option, - pub agent_follow: Option, - pub agent_detail: bool, - pub agent_signal_armed: Option, - pub agent_process_owned_fn: fn(u32, u64, Option<&str>) -> bool, - pub agent_signal_fn: fn(u32, u64, Option<&str>, AgentSignal) -> std::io::Result<()>, - pub agent_cpu_history: std::collections::HashMap>, - pub agent_last_sample: Option, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub(in crate::ui::app) struct AgentIdentity { - pub host: Option, - pub pid: u32, - pub started: u64, -} - -#[derive(Debug, Clone, Copy, Default)] -pub(in crate::ui::app) struct ResourceHits { - pub cpu_toggle: Rect, - pub mem_toggle: Rect, - pub net_toggle: Rect, - pub agents_toggle: Rect, - pub disks_toggle: Rect, - pub io_toggle: Rect, - pub net_prev: Rect, - pub net_next: Rect, - pub net_zero: Rect, - pub net_auto: Rect, - pub net_sync: Rect, - pub menu: Rect, - pub preset_prev: Rect, - pub preset_next: Rect, - pub interval_down: Rect, - pub interval_up: Rect, -} - -impl Default for ResourcesState { - fn default() -> Self { - Self { - shown: ShownBoxes { - cpu: true, - mem: true, - net: true, - agents: true, - }, - opts: LayoutOptions::default(), - rects: BoxRects::default(), - interval_ms: 2_000, - preset: 0, - presets: vec!["cpu:0:default,mem:0:default,net:0:default,agents:1:default".into()], - hits: ResourceHits::default(), - menu_open: false, - help_open: false, - show_disks: true, - io_mode: false, - net_auto: true, - net_sync: false, - net_download: 100, - net_upload: 100, - net_iface: None, - swap_upload_download: false, - net_zeroed: false, - net_zero_offsets: std::collections::HashMap::new(), - net_download_scaler: Default::default(), - net_upload_scaler: Default::default(), - agent_sort: AgentSort::Cpu, - agent_reverse: false, - agent_tree: false, - agent_filter: None, - agent_filter_editing: false, - agent_selected: None, - agent_follow: None, - agent_detail: false, - agent_signal_armed: None, - agent_process_owned_fn: process_owned_by_current_user, - agent_signal_fn: send_process_signal, - agent_cpu_history: std::collections::HashMap::new(), - agent_last_sample: None, - } - } -} - -impl ResourcesState { - pub fn sample_network(&mut self, snapshot: &crate::ui::resources::sampler::ResourceSnapshot) { - let selected = self - .net_iface - .as_deref() - .and_then(|name| { - snapshot - .networks - .iter() - .find(|entry| entry.interface == name) - }) - .or_else(|| { - crate::ui::resources::net::default_interface(&snapshot.networks).and_then(|name| { - snapshot - .networks - .iter() - .find(|entry| entry.interface == name) - }) - }); - if let Some(selected) = selected { - // The download graph shows transmitted traffic when the directions - // are swapped, so its ceiling must follow the same samples. - let (download, upload) = if self.swap_upload_download { - ( - selected.transmitted_bytes_per_second, - selected.received_bytes_per_second, - ) - } else { - ( - selected.received_bytes_per_second, - selected.transmitted_bytes_per_second, - ) - }; - self.net_download_scaler.sample(download); - self.net_upload_scaler.sample(upload); - } - } - - pub fn from_config(config: &medulla::config::ResourcesConfig) -> Self { - let shown = config - .shown_boxes - .split(',') - .map(str::trim) - .collect::>(); - let parsed = config - .presets - .split_whitespace() - .filter(|preset| valid_preset(preset)) - .map(str::to_owned) - .take(10) - .collect::>(); - let presets = if parsed.is_empty() { - Self::default().presets - } else { - parsed - }; - let mut state = Self { - shown: ShownBoxes { - cpu: shown.contains(&"cpu"), - mem: shown.contains(&"mem"), - net: shown.contains(&"net"), - agents: shown.contains(&"agents"), - }, - opts: LayoutOptions::default(), - interval_ms: config.update_interval_ms(), - show_disks: config.show_disks, - io_mode: config.io_mode, - net_auto: config.net_auto, - net_sync: config.net_sync, - net_download: config.net_download.max(1), - net_upload: config.net_upload.max(1), - net_iface: config.net_iface.clone().filter(|name| !name.is_empty()), - swap_upload_download: config.swap_upload_download, - net_zeroed: false, - presets, - ..Self::default() - }; - state.preset = config.preset.min(state.presets.len().saturating_sub(1)); - state.apply_preset(); - // `shownBoxes` is an explicit startup choice. Interactive preset - // changes replace visibility with the boxes listed by that preset. - state.shown = ShownBoxes { - cpu: shown.contains(&"cpu"), - mem: shown.contains(&"mem"), - net: shown.contains(&"net"), - agents: shown.contains(&"agents"), - }; - if let Some(value) = config.cpu_bottom { - state.opts.cpu_bottom = value; - } - if let Some(value) = config.mem_below_net { - state.opts.mem_below_net = value; - } - if let Some(value) = config.agents_left { - state.opts.agents_left = value; - } - state - } - - pub fn apply_preset(&mut self) { - let Some(preset) = self.presets.get(self.preset) else { - return; - }; - let (mut cpu_bottom, mut mem_below_net, mut agents_left) = (false, false, false); - let mut shown = ShownBoxes::default(); - for item in preset.split(',') { - let mut parts = item.split(':'); - let (Some(name), Some(position), Some(_graph)) = - (parts.next(), parts.next(), parts.next()) - else { - continue; - }; - match name { - "cpu" => { - shown.cpu = true; - cpu_bottom = position == "1"; - } - "mem" => { - shown.mem = true; - mem_below_net = position == "1"; - } - "net" => shown.net = true, - "agents" => agents_left = position == "0", - _ => {} - } - if name == "agents" { - shown.agents = true; - } - } - self.opts = LayoutOptions { - cpu_bottom, - mem_below_net, - agents_left, - }; - self.shown = shown; - } -} - -fn valid_preset(preset: &str) -> bool { - let mut seen = std::collections::HashSet::new(); - let mut any = false; - for item in preset.split(',') { - let mut parts = item.split(':'); - let (Some(name), Some(position), Some(graph)) = (parts.next(), parts.next(), parts.next()) - else { - return false; - }; - if parts.next().is_some() - || !["cpu", "mem", "net", "agents"].contains(&name) - || !seen.insert(name) - || !["0", "1"].contains(&position) - || !["default", "braille", "block", "tty"].contains(&graph) - { - return false; - } - any = true; - } - any -} - -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub(in crate::ui::app) enum AgentSort { - Pid, - Kind, - Origin, - Workspace, - Threads, - Memory, - #[default] - Cpu, - Runtime, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(in crate::ui::app) enum AgentSignal { - Terminate, - Kill, - Stop, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(in crate::ui::app) enum AgentSignalConfirmStage { - First, - ExternalSecond, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(in crate::ui::app) struct AgentSignalConfirmation { - pub pid: u32, - pub started: u64, - pub signal: AgentSignal, - pub stage: AgentSignalConfirmStage, -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -fn current_user_uid() -> String { - // SAFETY: geteuid has no preconditions and returns the current effective uid. - unsafe { libc::geteuid() }.to_string() -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -fn process_owned_by_current_user(pid: u32, started: u64, sampled_uid: Option<&str>) -> bool { - let Some(sampled_uid) = sampled_uid else { - return false; - }; - let Some((current_started, current_uid)) = - medulla::resources::launch::current_process_identity(pid) - else { - return false; - }; - current_started == started && current_uid == sampled_uid && current_uid == current_user_uid() -} - -#[cfg(not(any(target_os = "linux", target_os = "macos")))] -fn process_owned_by_current_user(_pid: u32, _started: u64, _sampled_uid: Option<&str>) -> bool { - false -} - -#[cfg(any(target_os = "linux", target_os = "macos"))] -fn send_process_signal( - pid: u32, - started: u64, - sampled_uid: Option<&str>, - signal: AgentSignal, -) -> std::io::Result<()> { - if !process_owned_by_current_user(pid, started, sampled_uid) { - return Err(std::io::Error::new( - std::io::ErrorKind::PermissionDenied, - "process identity or owner changed before signal", - )); - } - let signal = match signal { - AgentSignal::Terminate => libc::SIGTERM, - AgentSignal::Kill => libc::SIGKILL, - AgentSignal::Stop => libc::SIGSTOP, - }; - // SAFETY: kill only receives the integer pid and signal values validated above. - if unsafe { libc::kill(pid as libc::pid_t, signal) } == 0 { - Ok(()) - } else { - Err(std::io::Error::last_os_error()) - } -} - -#[cfg(not(any(target_os = "linux", target_os = "macos")))] -fn send_process_signal( - _pid: u32, - _started: u64, - _sampled_uid: Option<&str>, - _signal: AgentSignal, -) -> std::io::Result<()> { - Err(std::io::Error::new( - std::io::ErrorKind::Unsupported, - "process signals are unsupported on this platform", - )) -} diff --git a/src/tui/src/ui/app/settings_edit/resources/mod.rs b/src/tui/src/ui/app/settings_edit/resources/mod.rs deleted file mode 100644 index 72d33dbcf..000000000 --- a/src/tui/src/ui/app/settings_edit/resources/mod.rs +++ /dev/null @@ -1,213 +0,0 @@ -//! Btop-style editor for the Resources configuration. -//! -//! [`rows`] lists the editable fields, [`types`] defines a row, [`values`] reads -//! and formats them, and this module wires editing and drawing into `App`. - -use medulla::config::{MAX_RESOURCES_UPDATE_MS, MIN_RESOURCES_UPDATE_MS}; -use ratatui::style::{Modifier, Style}; -use ratatui::text::{Line, Span, Text}; -use ratatui::widgets::{Paragraph, Wrap}; -use ratatui::{layout::Rect, Frame}; - -use crate::ui::app::types::App; - -mod rows; -mod types; -mod values; - -use rows::ROWS; -use types::Kind; -use values::*; - -impl App { - pub(in crate::ui::app) fn draw_resources_settings(&mut self, f: &mut Frame, area: Rect) { - let selected = self.resources_settings_index.min(ROWS.len() - 1); - let cfg = &self.loaded.config.resources; - let mut lines = Vec::new(); - let mut group = ""; - let mut selected_line = 0; - for (index, row) in ROWS.iter().enumerate() { - if row.group != group { - group = row.group; - lines.push(Line::from(Span::styled( - group, - Style::default().add_modifier(Modifier::BOLD), - ))); - } - let value = display(cfg, *row); - if index == selected { - selected_line = lines.len(); - } - let style = if index == selected { - self.theme.selection() - } else { - Style::default() - }; - let control = match row.kind { - Kind::Flag | Kind::OptionalFlag => "toggle".to_owned(), - Kind::Count(min, max, step) => format!("{min}–{max}, step {step}"), - Kind::Choice(values) => format!("{} choices", values.len()), - Kind::OptionalText => "Auto or interface".to_owned(), - }; - lines.push(Line::from(vec![ - Span::styled(if index == selected { "▸ " } else { " " }, style), - Span::styled(format!("{:<25}", row.label), style), - Span::styled(format!("‹ {value} › {} · {control}", row.key), style), - ])); - } - lines.push(Line::from("")); - lines.push(Line::from(ROWS[selected].help)); - lines.push(Line::from( - "↑↓ select · ←→ change · Enter toggle · writes [resources]", - )); - let visible = usize::from(area.height.saturating_sub(4)).max(1); - let scroll = selected_line.saturating_sub(visible.saturating_sub(1)); - f.render_widget( - Paragraph::new(Text::from(lines)) - .wrap(Wrap { trim: false }) - .scroll((scroll.min(u16::MAX as usize) as u16, 0)) - .block(self.content_panel("Resources")), - area, - ); - } - - pub(in crate::ui::app) fn move_resources_settings(&mut self, up: bool) { - self.resources_settings_index = if up { - self.resources_settings_index.saturating_sub(1) - } else { - (self.resources_settings_index + 1).min(ROWS.len() - 1) - }; - } - - /// Toggle the selected resource setting only when it is a flag row. - pub(in crate::ui::app) fn toggle_resources_setting(&mut self) -> String { - let row = ROWS[self.resources_settings_index.min(ROWS.len() - 1)]; - if matches!(row.kind, Kind::Flag | Kind::OptionalFlag) { - self.adjust_resources_setting(0) - } else { - format!("Resources · {} needs ← or → to change", row.label) - } - } - - pub(in crate::ui::app) fn adjust_resources_setting(&mut self, delta: i32) -> String { - let row = ROWS[self.resources_settings_index.min(ROWS.len() - 1)]; - let cfg = &mut self.loaded.config.resources; - match row.key { - "updateMs" => { - cfg.update_ms = step( - cfg.update_ms, - delta, - MIN_RESOURCES_UPDATE_MS, - MAX_RESOURCES_UPDATE_MS, - 100, - ) - } - "shownBoxes" => { - cfg.shown_boxes = cycle(&cfg.shown_boxes, choices(row), delta).to_owned() - } - "presets" => cfg.presets = cycle(&cfg.presets, choices(row), delta).to_owned(), - "preset" => { - let max = cfg - .presets - .split_whitespace() - .count() - .saturating_sub(1) - .min(9) as u64; - cfg.preset = step(cfg.preset as u64, delta, 0, max, 1) as usize; - } - "cpuBottom" => cfg.cpu_bottom = optional_flag(cfg.cpu_bottom, delta), - "memBelowNet" => cfg.mem_below_net = optional_flag(cfg.mem_below_net, delta), - "agentsLeft" => cfg.agents_left = optional_flag(cfg.agents_left, delta), - "cpuGraphUpper" => { - cfg.cpu_graph_upper = cycle(&cfg.cpu_graph_upper, choices(row), delta).into() - } - "cpuGraphLower" => { - cfg.cpu_graph_lower = cycle(&cfg.cpu_graph_lower, choices(row), delta).into() - } - "cpuInvertLower" => cfg.cpu_invert_lower = !cfg.cpu_invert_lower, - "cpuSingleGraph" => cfg.cpu_single_graph = !cfg.cpu_single_graph, - "tempScale" => cfg.temp_scale = cycle(&cfg.temp_scale, choices(row), delta).into(), - "freqMode" => cfg.freq_mode = cycle(&cfg.freq_mode, choices(row), delta).into(), - "showBattery" => cfg.show_battery = !cfg.show_battery, - "memGraphs" => cfg.mem_graphs = !cfg.mem_graphs, - "showDisks" => cfg.show_disks = !cfg.show_disks, - "showSwap" => cfg.show_swap = !cfg.show_swap, - "swapDisk" => cfg.swap_disk = !cfg.swap_disk, - "onlyPhysical" => cfg.only_physical = !cfg.only_physical, - "useFstab" => cfg.use_fstab = !cfg.use_fstab, - "disksFilter" => { - cfg.disks_filter = cycle(&cfg.disks_filter, choices(row), delta).into() - } - "ioMode" => cfg.io_mode = !cfg.io_mode, - "ioGraphCombined" => cfg.io_graph_combined = !cfg.io_graph_combined, - "ioGraphSpeeds" => { - cfg.io_graph_speeds = cycle(&cfg.io_graph_speeds, choices(row), delta).into() - } - "netAuto" => cfg.net_auto = !cfg.net_auto, - "netSync" => cfg.net_sync = !cfg.net_sync, - "netDownload" => cfg.net_download = step(cfg.net_download, delta, 1, 1_000_000, 100), - "netUpload" => cfg.net_upload = step(cfg.net_upload, delta, 1, 1_000_000, 100), - "netIface" => { - let interfaces: Vec<_> = self - .resource_snapshot - .networks - .iter() - .map(|network| network.interface.as_str()) - .collect(); - let current = cfg - .net_iface - .as_deref() - .and_then(|name| interfaces.iter().position(|item| *item == name)) - .map(|index| index + 1) - .unwrap_or(0); - let choices = interfaces.len() + 1; - let next = if delta < 0 { - (current + choices - 1) % choices - } else { - (current + 1) % choices - }; - cfg.net_iface = next - .checked_sub(1) - .and_then(|index| interfaces.get(index)) - .map(|name| (*name).to_owned()); - } - "swapUploadDownload" => cfg.swap_upload_download = !cfg.swap_upload_download, - _ => unreachable!("all resource settings rows are mapped"), - } - let clear_auto = match row.key { - "cpuBottom" => cfg.cpu_bottom.is_none(), - "memBelowNet" => cfg.mem_below_net.is_none(), - "agentsLeft" => cfg.agents_left.is_none(), - _ => false, - }; - let value = persist_value(cfg, row); - if let Some(path) = self.config_path.as_deref() { - let persisted = if clear_auto { - medulla::config::clear_setting(path, "resources", row.key) - } else { - medulla::config::persist_setting(path, "resources", row.key, value) - }; - if let Err(error) = persisted { - return format!("Resources · changed in memory; could not save: {error}"); - } - } - let updated = super::super::resources::ResourcesState::from_config(cfg); - self.resources.shown = updated.shown; - self.resources.opts = updated.opts; - self.resources.interval_ms = updated.interval_ms; - self.resources.preset = updated.preset; - self.resources.presets = updated.presets; - self.resources.show_disks = updated.show_disks; - self.resources.io_mode = updated.io_mode; - self.resources.net_auto = updated.net_auto; - self.resources.net_sync = updated.net_sync; - self.resources.net_download = updated.net_download; - self.resources.net_upload = updated.net_upload; - self.resources.net_iface = updated.net_iface; - self.resources.swap_upload_download = updated.swap_upload_download; - format!("Resources · {} → {}", row.label, display(cfg, row)) - } -} - -#[cfg(test)] -mod tests; diff --git a/src/tui/src/ui/app/settings_edit/resources/rows.rs b/src/tui/src/ui/app/settings_edit/resources/rows.rs deleted file mode 100644 index e4aae2f7a..000000000 --- a/src/tui/src/ui/app/settings_edit/resources/rows.rs +++ /dev/null @@ -1,236 +0,0 @@ -//! The static table of editable Resources settings. - -use medulla::config::{MAX_RESOURCES_UPDATE_MS, MIN_RESOURCES_UPDATE_MS}; - -use super::types::{row, Kind, Row}; - -/// Every editable Resources setting, in display order. -pub(super) const ROWS: &[Row] = &[ - row( - "GENERAL", - "updateMs", - "Sample interval", - "Milliseconds between resource samples.", - Kind::Count(MIN_RESOURCES_UPDATE_MS, MAX_RESOURCES_UPDATE_MS, 100), - ), - row( - "GENERAL", - "shownBoxes", - "Visible boxes", - "Boxes shown when Resources opens.", - Kind::Choice(&[ - "cpu,mem,net,agents", - "cpu,mem,net", - "cpu,mem", - "cpu,net", - "mem,net", - "cpu", - "mem", - "net", - "agents", - ]), - ), - row( - "GENERAL", - "presets", - "Layout presets", - "Whitespace-separated btop-style layout presets.", - Kind::Choice(&[ - "cpu:0:default,mem:0:default,net:0:default,agents:1:default", - "cpu:1:block,mem:1:block,net:0:block,agents:0:tty", - ]), - ), - row( - "GENERAL", - "preset", - "Selected preset", - "Preset selected when Resources opens.", - Kind::Count(0, 9, 1), - ), - row( - "GENERAL", - "cpuBottom", - "CPU below", - "Place CPU below the other boxes; Auto follows the preset.", - Kind::OptionalFlag, - ), - row( - "GENERAL", - "memBelowNet", - "Memory below network", - "Place memory below network; Auto follows the preset.", - Kind::OptionalFlag, - ), - row( - "CPU", - "cpuGraphUpper", - "Upper graph", - "CPU field drawn by the upper graph.", - Kind::Choice(&[ - "total", "user", "system", "nice", "iowait", "irq", "softirq", "steal", - ]), - ), - row( - "CPU", - "cpuGraphLower", - "Lower graph", - "CPU field drawn by the lower graph.", - Kind::Choice(&[ - "iowait", "total", "user", "system", "nice", "irq", "softirq", "steal", - ]), - ), - row( - "CPU", - "cpuInvertLower", - "Invert lower graph", - "Draw the lower CPU graph upside down.", - Kind::Flag, - ), - row( - "CPU", - "cpuSingleGraph", - "Single graph", - "Collapse CPU fields into one graph.", - Kind::Flag, - ), - row( - "CPU", - "tempScale", - "Temperature scale", - "Temperature display units.", - Kind::Choice(&["celsius", "fahrenheit"]), - ), - row( - "CPU", - "freqMode", - "Frequency units", - "CPU frequency presentation.", - Kind::Choice(&["auto", "mhz", "ghz"]), - ), - row( - "CPU", - "showBattery", - "Show battery", - "Show battery percentage when available.", - Kind::Flag, - ), - row( - "MEM", - "memGraphs", - "Memory graphs", - "Draw memory and swap history graphs.", - Kind::Flag, - ), - row( - "MEM", - "showDisks", - "Show disks", - "Show mounted disks in the memory panel.", - Kind::Flag, - ), - row( - "MEM", - "showSwap", - "Show swap", - "Show swap usage in the memory panel.", - Kind::Flag, - ), - row( - "MEM", - "swapDisk", - "Swap device as disk", - "Show a swap device as a disk row when available.", - Kind::Flag, - ), - row( - "MEM", - "onlyPhysical", - "Physical disks only", - "Hide virtual and loop devices.", - Kind::Flag, - ), - row( - "MEM", - "useFstab", - "Use fstab", - "Prefer filesystems listed in /etc/fstab.", - Kind::Flag, - ), - row( - "MEM", - "disksFilter", - "Disk filters", - "Comma-separated mount filters.", - Kind::Choice(&["", "exclude=/boot", "exclude=/boot,exclude=/tmp"]), - ), - row( - "MEM", - "ioMode", - "Disk busy percentage", - "Show disk busy percentage in the disks pane.", - Kind::Flag, - ), - row( - "MEM", - "ioGraphCombined", - "Combined IO graph", - "Combine read and write series.", - Kind::Flag, - ), - row( - "MEM", - "ioGraphSpeeds", - "IO graph ceilings", - "Per-mount IO graph ceilings in MiB/s.", - Kind::Choice(&["", "/:20", "/:100"]), - ), - row( - "NET", - "netAuto", - "Automatic network scale", - "Scale network graphs to recent traffic.", - Kind::Flag, - ), - row( - "NET", - "netSync", - "Synchronized scales", - "Use the larger direction scale for both graphs.", - Kind::Flag, - ), - row( - "NET", - "netDownload", - "Download ceiling", - "Download graph ceiling in KiB/s.", - Kind::Count(1, 1_000_000, 100), - ), - row( - "NET", - "netUpload", - "Upload ceiling", - "Upload graph ceiling in KiB/s.", - Kind::Count(1, 1_000_000, 100), - ), - row( - "NET", - "netIface", - "Network interface", - "Preferred interface; Auto selects the active default.", - Kind::OptionalText, - ), - row( - "NET", - "swapUploadDownload", - "Swap directions", - "Swap displayed download and upload directions.", - Kind::Flag, - ), - row( - "AGENTS", - "agentsLeft", - "Agents on left", - "Place Agents on the left; Auto follows the preset.", - Kind::OptionalFlag, - ), -]; diff --git a/src/tui/src/ui/app/settings_edit/resources/tests.rs b/src/tui/src/ui/app/settings_edit/resources/tests.rs deleted file mode 100644 index 3c8653043..000000000 --- a/src/tui/src/ui/app/settings_edit/resources/tests.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! Unit tests for the Resources settings editor. - -use medulla::config::ResourcesConfig; - -use super::*; - -#[test] -fn every_resources_config_field_has_an_editor_row() { - let config = serde_json::to_value(ResourcesConfig::default()).unwrap(); - let fields = config.as_object().unwrap(); - for field in fields.keys() { - let camel = field.clone(); - assert!( - ROWS.iter().any(|row| row.key == camel), - "no Resources setting for {field}" - ); - } - assert_eq!(ROWS.len(), fields.len()); -} - -#[test] -fn optional_flags_cycle_between_auto_on_and_off_in_both_directions() { - let auto = None; - let on = Some(true); - let off = Some(false); - - assert_eq!(optional_flag(auto, 1), on); - assert_eq!(optional_flag(on, 1), off); - assert_eq!(optional_flag(off, 1), auto); - assert_eq!(optional_flag(auto, -1), off); - assert_eq!(optional_flag(off, -1), on); - assert_eq!(optional_flag(on, -1), auto); -} diff --git a/src/tui/src/ui/app/settings_edit/resources/types.rs b/src/tui/src/ui/app/settings_edit/resources/types.rs deleted file mode 100644 index cd86382ad..000000000 --- a/src/tui/src/ui/app/settings_edit/resources/types.rs +++ /dev/null @@ -1,48 +0,0 @@ -//! Data types for the Resources settings editor: one [`Row`] per editable field. - -/// How a row's value is edited. -#[derive(Clone, Copy)] -pub(super) enum Kind { - /// A plain on/off toggle. - Flag, - /// A bounded integer: `(min, max, step)`. - Count(u64, u64, u64), - /// One of a fixed list of strings. - Choice(&'static [&'static str]), - /// A tri-state toggle: automatic, on, or off. - OptionalFlag, - /// Free text that may be empty, meaning automatic. - OptionalText, -} - -/// One editable Resources setting and its presentation. -#[derive(Clone, Copy)] -pub(super) struct Row { - /// Heading the row is listed under. - pub(super) group: &'static str, - /// Config key the row reads and persists. - pub(super) key: &'static str, - /// Short label shown in the list. - pub(super) label: &'static str, - /// One-line explanation shown beside the value. - pub(super) help: &'static str, - /// How the value is edited. - pub(super) kind: Kind, -} - -/// Builds a [`Row`] in a `const` context so [`super::rows::ROWS`] can be a static table. -pub(super) const fn row( - group: &'static str, - key: &'static str, - label: &'static str, - help: &'static str, - kind: Kind, -) -> Row { - Row { - group, - key, - label, - help, - kind, - } -} diff --git a/src/tui/src/ui/app/settings_edit/resources/values.rs b/src/tui/src/ui/app/settings_edit/resources/values.rs deleted file mode 100644 index 6f006a2f7..000000000 --- a/src/tui/src/ui/app/settings_edit/resources/values.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! Reading, stepping, formatting, and persisting Resources setting values. - -use medulla::config::ResourcesConfig; - -use super::types::{Kind, Row}; - -pub(super) fn step(current: u64, delta: i32, min: u64, max: u64, amount: u64) -> u64 { - if delta == 0 { - return if current < max { current + amount } else { min }; - } - (current as i64 + i64::from(delta) * amount as i64).clamp(min as i64, max as i64) as u64 -} -pub(super) fn optional_flag(value: Option, delta: i32) -> Option { - match (value, delta < 0) { - (None, false) => Some(true), - (Some(true), false) => Some(false), - (Some(false), false) => None, - (None, true) => Some(false), - (Some(false), true) => Some(true), - (Some(true), true) => None, - } -} -pub(super) fn choices(row: Row) -> &'static [&'static str] { - if let Kind::Choice(values) = row.kind { - values - } else { - &[] - } -} -pub(super) fn cycle<'a>(current: &str, values: &'a [&'static str], delta: i32) -> &'a str { - let index = values - .iter() - .position(|value| *value == current) - .unwrap_or(0); - let next = if delta < 0 { - (index + values.len() - 1) % values.len() - } else { - (index + 1) % values.len() - }; - values[next] -} -pub(super) fn display(cfg: &ResourcesConfig, row: Row) -> String { - match row.key { - "updateMs" => cfg.update_ms.to_string(), - "shownBoxes" => cfg.shown_boxes.clone(), - "presets" => cfg.presets.clone(), - "preset" => cfg.preset.to_string(), - "cpuBottom" => opt_flag(cfg.cpu_bottom), - "memBelowNet" => opt_flag(cfg.mem_below_net), - "agentsLeft" => opt_flag(cfg.agents_left), - "cpuGraphUpper" => cfg.cpu_graph_upper.clone(), - "cpuGraphLower" => cfg.cpu_graph_lower.clone(), - "cpuInvertLower" => flag(cfg.cpu_invert_lower), - "cpuSingleGraph" => flag(cfg.cpu_single_graph), - "tempScale" => cfg.temp_scale.clone(), - "freqMode" => cfg.freq_mode.clone(), - "showBattery" => flag(cfg.show_battery), - "memGraphs" => flag(cfg.mem_graphs), - "showDisks" => flag(cfg.show_disks), - "showSwap" => flag(cfg.show_swap), - "swapDisk" => flag(cfg.swap_disk), - "onlyPhysical" => flag(cfg.only_physical), - "useFstab" => flag(cfg.use_fstab), - "disksFilter" => nonempty(&cfg.disks_filter), - "ioMode" => flag(cfg.io_mode), - "ioGraphCombined" => flag(cfg.io_graph_combined), - "ioGraphSpeeds" => nonempty(&cfg.io_graph_speeds), - "netAuto" => flag(cfg.net_auto), - "netSync" => flag(cfg.net_sync), - "netDownload" => cfg.net_download.to_string(), - "netUpload" => cfg.net_upload.to_string(), - "netIface" => cfg - .net_iface - .clone() - .filter(|value| !value.is_empty()) - .unwrap_or_else(|| "Auto".into()), - "swapUploadDownload" => flag(cfg.swap_upload_download), - _ => unreachable!(), - } -} -pub(super) fn flag(value: bool) -> String { - if value { "On" } else { "Off" }.into() -} -pub(super) fn opt_flag(value: Option) -> String { - value.map(flag).unwrap_or_else(|| "Auto".into()) -} -pub(super) fn nonempty(value: &str) -> String { - if value.is_empty() { - "None".into() - } else { - value.into() - } -} -pub(super) fn persist_value(cfg: &ResourcesConfig, row: Row) -> toml::Value { - use toml::Value as V; - match row.key { - "updateMs" => V::Integer(cfg.update_ms as i64), - "shownBoxes" => V::String(cfg.shown_boxes.clone()), - "presets" => V::String(cfg.presets.clone()), - "preset" => V::Integer(cfg.preset as i64), - "cpuBottom" => V::Boolean(cfg.cpu_bottom.unwrap_or(false)), - "memBelowNet" => V::Boolean(cfg.mem_below_net.unwrap_or(false)), - "agentsLeft" => V::Boolean(cfg.agents_left.unwrap_or(false)), - "cpuGraphUpper" => V::String(cfg.cpu_graph_upper.clone()), - "cpuGraphLower" => V::String(cfg.cpu_graph_lower.clone()), - "cpuInvertLower" => V::Boolean(cfg.cpu_invert_lower), - "cpuSingleGraph" => V::Boolean(cfg.cpu_single_graph), - "tempScale" => V::String(cfg.temp_scale.clone()), - "freqMode" => V::String(cfg.freq_mode.clone()), - "showBattery" => V::Boolean(cfg.show_battery), - "memGraphs" => V::Boolean(cfg.mem_graphs), - "showDisks" => V::Boolean(cfg.show_disks), - "showSwap" => V::Boolean(cfg.show_swap), - "swapDisk" => V::Boolean(cfg.swap_disk), - "onlyPhysical" => V::Boolean(cfg.only_physical), - "useFstab" => V::Boolean(cfg.use_fstab), - "disksFilter" => V::String(cfg.disks_filter.clone()), - "ioMode" => V::Boolean(cfg.io_mode), - "ioGraphCombined" => V::Boolean(cfg.io_graph_combined), - "ioGraphSpeeds" => V::String(cfg.io_graph_speeds.clone()), - "netAuto" => V::Boolean(cfg.net_auto), - "netSync" => V::Boolean(cfg.net_sync), - "netDownload" => V::Integer(cfg.net_download as i64), - "netUpload" => V::Integer(cfg.net_upload as i64), - "netIface" => V::String(cfg.net_iface.clone().unwrap_or_default()), - "swapUploadDownload" => V::Boolean(cfg.swap_upload_download), - _ => unreachable!(), - } -} diff --git a/src/tui/src/ui/plot/graph.rs b/src/tui/src/ui/plot/graph.rs deleted file mode 100644 index af3df0792..000000000 --- a/src/tui/src/ui/plot/graph.rs +++ /dev/null @@ -1,150 +0,0 @@ -//! Paired-sample history graph widget. - -use super::{Gradient, Symbol}; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use ratatui::style::Style; -use ratatui::widgets::Widget; - -/// Draw a percentage history, packing two samples into each terminal cell. -/// -/// Values are clamped to `0..=100`. The default symbol set is Braille, matching -/// the resource plot decision in the Resources specification. -pub struct Graph<'a> { - values: &'a [f32], - symbol: Symbol, - invert: bool, - no_zero: bool, - gradient: Option<&'a Gradient>, -} - -impl<'a> Graph<'a> { - /// Create a graph over percentage samples. - pub fn new(values: &'a [f32]) -> Self { - Self { - values, - symbol: Symbol::default(), - invert: false, - no_zero: false, - gradient: None, - } - } - - /// Choose the glyph family. Defaults to [`Symbol::Braille`]. - pub fn symbol(mut self, symbol: Symbol) -> Self { - self.symbol = symbol; - self - } - - /// Draw with the descending btop lookup table. - pub fn invert(mut self, invert: bool) -> Self { - self.invert = invert; - self - } - - /// Keep zero samples visible as a one-dot baseline. - pub fn no_zero(mut self, no_zero: bool) -> Self { - self.no_zero = no_zero; - self - } - - /// Color the graph with this gradient. - pub fn gradient(mut self, gradient: &'a Gradient) -> Self { - self.gradient = Some(gradient); - self - } -} - -impl Widget for Graph<'_> { - fn render(self, area: Rect, buffer: &mut Buffer) { - if area.is_empty() { - return; - } - for y in area.y..area.bottom() { - for x in area.x..area.right() { - // Blank the cell but keep the background painted beneath it. - let bg = buffer[(x, y)].bg; - buffer[(x, y)] = ratatui::buffer::Cell::default() - .set_char(' ') - .set_style(Style::default().bg(bg)) - .clone(); - } - } - if self.values.is_empty() { - return; - } - let width = area.width as usize; - let height = area.height as usize; - let first = self.values.len().saturating_sub(width.saturating_mul(2)); - let values = &self.values[first..]; - let odd = values.len() % 2 == 1; - let cell_count = values.len().div_ceil(2); - let first_column = width - cell_count; - let one_row_bias = if height == 1 { 0.3 } else { 0.1 }; - - for cell_index in 0..cell_count { - let (previous, current) = if odd && cell_index == 0 { - (0.0, values[0]) - } else { - let value_index = cell_index * 2 - usize::from(odd); - (values[value_index], values[value_index + 1]) - }; - let column = first_column + cell_index; - for row in 0..height { - // The percentage band a row shows, counted from the top. An - // inverted graph grows downward from the top edge, so its first - // row holds the lowest band rather than the highest. - let band = if self.invert { height - 1 - row } else { row }; - let high = if height > 1 { - (100.0 * (height - band) as f32 / height as f32).round() - } else { - 100.0 - }; - let low = if height > 1 { - (100.0 * (height - band - 1) as f32 / height as f32).round() - } else { - 0.0 - }; - let bottom = band == height - 1; - let left_no_zero = - self.no_zero && bottom && !(odd && cell_index == 0 && first == 0); - let left_level = level(previous, low, high, one_row_bias, left_no_zero); - let right_level = level(current, low, high, one_row_bias, self.no_zero && bottom); - let glyph = self.symbol.glyph(self.invert, left_level, right_level); - let color_percent = if height == 1 { - previous.max(current).clamp(0.0, 100.0) - } else { - high - }; - let style = self - .gradient - .map(|gradient| Style::default().fg(gradient.at(color_percent))) - .unwrap_or_default(); - buffer[(area.x + column as u16, area.y + row as u16)] = - ratatui::buffer::Cell::default() - .set_char(glyph) - .set_style(style) - .clone(); - } - } - } -} - -fn level(value: f32, low: f32, high: f32, bias: f32, no_zero: bool) -> u8 { - let value = if value.is_finite() { - value.clamp(0.0, 100.0) - } else { - 0.0 - }; - let minimum = u8::from(no_zero); - if high <= low { - minimum - } else if value >= high { - 4 - } else if value <= low { - minimum - } else { - (((value - low) * 4.0 / (high - low) + bias).round() as i32).clamp(i32::from(minimum), 4) - as u8 - } -} diff --git a/src/tui/src/ui/plot/meter.rs b/src/tui/src/ui/plot/meter.rs deleted file mode 100644 index a44ff0d1d..000000000 --- a/src/tui/src/ui/plot/meter.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Gradient filled percentage meter widget. - -use super::Gradient; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use ratatui::style::{Color, Style}; -use ratatui::widgets::Widget; - -/// A width-bounded meter using filled square glyphs. -pub struct Meter<'a> { - value: f32, - gradient: &'a Gradient, - meter_bg: Color, -} - -impl<'a> Meter<'a> { - /// Create a meter for a value in `0..=100`. - pub fn new(value: f32, gradient: &'a Gradient, meter_bg: Color) -> Self { - Self { - value, - gradient, - meter_bg, - } - } -} - -impl Widget for Meter<'_> { - fn render(self, area: Rect, buffer: &mut Buffer) { - if area.is_empty() { - return; - } - let value = if self.value.is_finite() { - self.value.clamp(0.0, 100.0) - } else { - 0.0 - }; - let filled = (value * area.width as f32 / 100.0).floor() as usize; - for column in 0..area.width as usize { - let color = if column < filled { - let position = (column + 1) as f32 * 100.0 / area.width as f32; - self.gradient.at(position) - } else { - self.meter_bg - }; - let cell = &mut buffer[(area.x + column as u16, area.y)]; - let bg = cell.bg; - *cell = ratatui::buffer::Cell::default() - .set_char('■') - .set_style(Style::default().fg(color).bg(bg)) - .clone(); - } - } -} diff --git a/src/tui/src/ui/plot/mod.rs b/src/tui/src/ui/plot/mod.rs deleted file mode 100644 index 07659d6d0..000000000 --- a/src/tui/src/ui/plot/mod.rs +++ /dev/null @@ -1,95 +0,0 @@ -//! Reusable btop-style graph and meter widgets for the terminal UI. - -mod graph; -mod meter; -mod symbols; - -#[cfg(test)] -mod tests; - -pub use graph::Graph; -pub use meter::Meter; -pub use symbols::Symbol; - -use ratatui::style::Color; - -/// A one-row Braille history `width` cells wide, two samples per cell, the -/// newest at the right, as btop draws its per-process CPU graphs. -/// -/// Values are percentages; zero keeps a one-dot baseline so an idle row still -/// reads as a graph. -pub fn sparkline(values: &[f32], width: usize) -> String { - let level = |value: f32| -> u8 { - let value = if value.is_finite() { - value.clamp(0.0, 100.0) - } else { - 0.0 - }; - ((value / 25.0).round() as u8).clamp(1, 4) - }; - let recent = &values[values.len().saturating_sub(width * 2)..]; - let mut levels: Vec = recent.iter().copied().map(level).collect(); - if levels.len() % 2 == 1 { - levels.insert(0, 1); - } - let cells: String = levels - .chunks(2) - .map(|pair| Symbol::Braille.glyph(false, pair[0], pair[1])) - .collect(); - let padding = width.saturating_sub(cells.chars().count()); - format!("{}{cells}", "⣀".repeat(padding)) -} - -/// A color gradient sampled from 0 to 100 inclusive. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Gradient { - stops: Vec, -} - -impl Gradient { - /// Build a gradient from any number of color stops. - /// - /// Stops are spread evenly from 0 through 100. RGB stops are interpolated - /// channel by channel; other Ratatui colors switch at the midpoint between - /// stops. An empty list behaves as a solid white gradient. - pub fn new(stops: impl Into>) -> Self { - Self { - stops: stops.into(), - } - } - - pub(super) fn at(&self, percent: f32) -> Color { - match self.stops.as_slice() { - [] => Color::White, - [color] => *color, - stops => { - let position = percent.clamp(0.0, 100.0) / 100.0 * (stops.len() - 1) as f32; - let low = position.floor() as usize; - let high = (low + 1).min(stops.len() - 1); - let amount = position - low as f32; - blend(stops[low], stops[high], amount) - } - } - } -} - -fn blend(from: Color, to: Color, amount: f32) -> Color { - match (from, to) { - (Color::Rgb(r1, g1, b1), Color::Rgb(r2, g2, b2)) => Color::Rgb( - mix(r1, r2, amount), - mix(g1, g2, amount), - mix(b1, b2, amount), - ), - (from, to) => { - if amount < 0.5 { - from - } else { - to - } - } - } -} - -fn mix(from: u8, to: u8, amount: f32) -> u8 { - (f32::from(from) + (f32::from(to) - f32::from(from)) * amount).round() as u8 -} diff --git a/src/tui/src/ui/plot/symbols.rs b/src/tui/src/ui/plot/symbols.rs deleted file mode 100644 index 2105f372d..000000000 --- a/src/tui/src/ui/plot/symbols.rs +++ /dev/null @@ -1,53 +0,0 @@ -//! Glyph lookup tables used by btop-style plots. - -/// Symbol family used to encode two vertical samples in one terminal cell. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub enum Symbol { - /// Braille patterns, the btop-compatible default. - #[default] - Braille, - /// Unicode block elements. - Block, - /// Shaded blocks for broad terminal compatibility. - Tty, -} - -impl Symbol { - pub(super) fn glyph(self, invert: bool, previous: u8, current: u8) -> char { - let table = match (self, invert) { - (Self::Braille, false) => BRAILLE_UP, - (Self::Braille, true) => BRAILLE_DOWN, - (Self::Block, false) => BLOCK_UP, - (Self::Block, true) => BLOCK_DOWN, - (Self::Tty, false) => TTY_UP, - (Self::Tty, true) => TTY_DOWN, - }; - table[usize::from(previous) * 5 + usize::from(current)] - } -} - -// Copyright (c) 2021 Aristocratos. -// Verbatim glyph tables from btop src/btop_draw.cpp Symbols::graph_symbols, -// lines 89–132 at https://github.com/aristocratos/btop/blob/89fcdf4094e89f8ac215ee6c3ee74aeffb618e86/src/btop_draw.cpp -// btop is licensed under Apache-2.0; see https://github.com/aristocratos/btop/blob/89fcdf4094e89f8ac215ee6c3ee74aeffb618e86/LICENSE -const BRAILLE_UP: [char; 25] = [ - ' ', '⢀', '⢠', '⢰', '⢸', '⡀', '⣀', '⣠', '⣰', '⣸', '⡄', '⣄', '⣤', '⣴', '⣼', '⡆', '⣆', '⣦', '⣶', - '⣾', '⡇', '⣇', '⣧', '⣷', '⣿', -]; -const BRAILLE_DOWN: [char; 25] = [ - ' ', '⠈', '⠘', '⠸', '⢸', '⠁', '⠉', '⠙', '⠹', '⢹', '⠃', '⠋', '⠛', '⠻', '⢻', '⠇', '⠏', '⠟', '⠿', - '⢿', '⡇', '⡏', '⡟', '⡿', '⣿', -]; -const BLOCK_UP: [char; 25] = [ - ' ', '▗', '▗', '▐', '▐', '▖', '▄', '▄', '▟', '▟', '▖', '▄', '▄', '▟', '▟', '▌', '▙', '▙', '█', - '█', '▌', '▙', '▙', '█', '█', -]; -const BLOCK_DOWN: [char; 25] = [ - ' ', '▝', '▝', '▐', '▐', '▘', '▀', '▀', '▜', '▜', '▘', '▀', '▀', '▜', '▜', '▌', '▛', '▛', '█', - '█', '▌', '▛', '▛', '█', '█', -]; -const TTY_UP: [char; 25] = [ - ' ', '░', '░', '▒', '▒', '░', '░', '▒', '▒', '█', '░', '▒', '▒', '▒', '█', '▒', '▒', '▒', '█', - '█', '▒', '█', '█', '█', '█', -]; -const TTY_DOWN: [char; 25] = TTY_UP; diff --git a/src/tui/src/ui/plot/tests.rs b/src/tui/src/ui/plot/tests.rs deleted file mode 100644 index b85c20d68..000000000 --- a/src/tui/src/ui/plot/tests.rs +++ /dev/null @@ -1,136 +0,0 @@ -//! Unit tests for the plot helpers. - -use super::{Gradient, Graph, Meter, Symbol}; -use ratatui::buffer::Buffer; -use ratatui::layout::Rect; -use ratatui::style::Color; -use ratatui::widgets::Widget; -use unicode_width::UnicodeWidthChar; - -fn render_graph(values: &[f32], width: u16, height: u16, symbol: Symbol, invert: bool) -> Buffer { - let area = Rect::new(0, 0, width, height); - let mut buffer = Buffer::empty(area); - Graph::new(values) - .symbol(symbol) - .invert(invert) - .render(area, &mut buffer); - buffer -} - -fn glyph(buffer: &Buffer, x: u16, y: u16) -> char { - buffer[(x, y)].symbol().chars().next().unwrap_or(' ') -} - -#[test] -fn paired_samples_match_btop_glyphs_for_each_symbol_table() { - let expected = [ - (Symbol::Braille, '⣰', '⠹'), - (Symbol::Block, '▟', '▜'), - (Symbol::Tty, '▒', '▒'), - ]; - for (symbol, up, down) in expected { - let graph = render_graph(&[25.0, 75.0], 1, 1, symbol, false); - let inverted = render_graph(&[25.0, 75.0], 1, 1, symbol, true); - assert_eq!(glyph(&graph, 0, 0), up); - assert_eq!(glyph(&inverted, 0, 0), down); - } -} - -#[test] -fn short_histories_right_align_and_odd_histories_start_with_an_empty_half() { - let short = render_graph(&[25.0, 75.0], 3, 1, Symbol::Braille, false); - assert_eq!(glyph(&short, 0, 0), ' '); - assert_eq!(glyph(&short, 1, 0), ' '); - assert_eq!(glyph(&short, 2, 0), '⣰'); - - let odd = render_graph(&[25.0, 75.0, 50.0], 2, 1, Symbol::Braille, false); - assert_eq!(glyph(&odd, 0, 0), '⢀'); - assert_eq!(glyph(&odd, 1, 0), Symbol::Braille.glyph(false, 3, 2)); -} - -#[test] -fn short_and_empty_histories_clear_stale_buffer_cells() { - let area = Rect::new(0, 0, 3, 1); - let mut buffer = Buffer::empty(area); - for x in 0..area.width { - buffer[(x, 0)].set_char('x'); - } - - Graph::new(&[25.0, 75.0]).render(area, &mut buffer); - assert_eq!(glyph(&buffer, 0, 0), ' '); - assert_eq!(glyph(&buffer, 1, 0), ' '); - assert_eq!(glyph(&buffer, 2, 0), '⣰'); - - Graph::new(&[]).render(area, &mut buffer); - assert!(buffer.content().iter().all(|cell| cell.symbol() == " ")); -} - -#[test] -fn percentage_rows_fill_from_the_bottom_and_invert_to_the_top() { - let up = render_graph(&[0.0, 37.5], 1, 4, Symbol::Braille, false); - let down = render_graph(&[0.0, 37.5], 1, 4, Symbol::Braille, true); - - assert_eq!(glyph(&up, 0, 0), ' '); - assert_eq!(glyph(&up, 0, 1), ' '); - assert_eq!(glyph(&up, 0, 2), '⢠'); - assert_eq!(glyph(&up, 0, 3), '⢸'); - // Inverted, the same 37.5% sample grows down from the top edge: the lowest - // band is the first row, and the rows below the sample stay empty. - assert_eq!(glyph(&down, 0, 0), '⢸'); - assert_eq!(glyph(&down, 0, 1), '⠘'); - assert_eq!(glyph(&down, 0, 2), ' '); - assert_eq!(glyph(&down, 0, 3), ' '); - // The lower dot in the up table becomes an upper dot with the down table. - assert_ne!( - Symbol::Braille.glyph(false, 1, 0), - Symbol::Braille.glyph(true, 1, 0) - ); -} - -#[test] -fn no_zero_keeps_a_baseline_mark_for_zero_values() { - let area = Rect::new(0, 0, 1, 4); - let mut graph = Buffer::empty(area); - Graph::new(&[0.0]).no_zero(true).render(area, &mut graph); - assert_eq!(glyph(&graph, 0, 0), ' '); - assert_eq!(glyph(&graph, 0, 1), ' '); - assert_eq!(glyph(&graph, 0, 2), ' '); - assert_eq!(glyph(&graph, 0, 3), '⢀'); -} - -#[test] -fn meter_fills_zero_half_and_all_of_ten_cells() { - let gradient = Gradient::new(vec![Color::Rgb(1, 2, 3)]); - for (value, filled) in [(0.0, 0), (50.0, 5), (100.0, 10)] { - let area = Rect::new(0, 0, 10, 1); - let mut buffer = Buffer::empty(area); - Meter::new(value, &gradient, Color::Rgb(4, 5, 6)).render(area, &mut buffer); - let actual = (0..10) - .filter(|x| buffer[(*x, 0)].style().fg == Some(Color::Rgb(1, 2, 3))) - .count(); - assert_eq!(actual, filled); - assert!(buffer.content().iter().all(|cell| cell.symbol() == "■")); - } -} - -#[test] -fn braille_glyphs_are_single_terminal_cells() { - assert_eq!(UnicodeWidthChar::width('⣿'), Some(1)); - let graph = render_graph(&[0.0, 100.0], 1, 1, Symbol::Braille, false); - assert_eq!(glyph(&graph, 0, 0), '⢸'); -} - -#[test] -fn gradient_interpolates_rgb_stops() { - let gradient = Gradient::new(vec![Color::Rgb(0, 10, 20), Color::Rgb(100, 110, 120)]); - assert_eq!(gradient.at(50.0), Color::Rgb(50, 60, 70)); -} - -#[test] -fn sparkline_packs_two_samples_per_cell_with_an_idle_baseline() { - assert_eq!(super::sparkline(&[], 3), "⣀⣀⣀"); - assert_eq!(super::sparkline(&[0.0, 100.0], 2), "⣀⣸"); - // Only the newest four samples fit in two cells. - assert_eq!(super::sparkline(&[0.0, 100.0, 100.0, 100.0, 50.0], 2), "⣿⣧"); - assert_eq!(super::sparkline(&[50.0], 1), "⣠"); -} diff --git a/src/tui/src/ui/resources/cpu.rs b/src/tui/src/ui/resources/cpu.rs deleted file mode 100644 index 17eaf0b11..000000000 --- a/src/tui/src/ui/resources/cpu.rs +++ /dev/null @@ -1,438 +0,0 @@ -//! Whole-machine CPU sampling, with Linux's `/proc/stat` as the precise source. - -#[cfg(target_os = "linux")] -use std::{ - collections::BTreeMap, - fs, - path::{Path, PathBuf}, -}; - -/// CPU time fields exposed by Linux `/proc/stat` and selectable in graphs. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CpuField { - Total, - User, - Nice, - System, - Idle, - Iowait, - Irq, - Softirq, - Steal, - Guest, - GuestNice, -} - -impl CpuField { - /// Parse a graph field name. - pub fn parse(value: &str) -> Option { - Some(match value { - "total" => Self::Total, - "user" => Self::User, - "nice" => Self::Nice, - "system" => Self::System, - "idle" => Self::Idle, - "iowait" => Self::Iowait, - "irq" => Self::Irq, - "softirq" => Self::Softirq, - "steal" => Self::Steal, - "guest" => Self::Guest, - "guest_nice" => Self::GuestNice, - _ => return None, - }) - } -} - -/// CPU readings for one sample, represented as percentages from 0 to 100. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct CpuReading { - pub total: f32, - pub user: f32, - pub nice: f32, - pub system: f32, - pub idle: f32, - pub iowait: f32, - pub irq: f32, - pub softirq: f32, - pub steal: f32, - pub guest: f32, - pub guest_nice: f32, -} - -impl CpuReading { - /// Return the value for a selectable graph field. - pub fn field(&self, field: CpuField) -> f32 { - match field { - CpuField::Total => self.total, - CpuField::User => self.user, - CpuField::Nice => self.nice, - CpuField::System => self.system, - CpuField::Idle => self.idle, - CpuField::Iowait => self.iowait, - CpuField::Irq => self.irq, - CpuField::Softirq => self.softirq, - CpuField::Steal => self.steal, - CpuField::Guest => self.guest, - CpuField::GuestNice => self.guest_nice, - } - } -} - -/// Immutable whole-machine CPU data. -#[derive(Debug, Clone, Default, PartialEq)] -pub struct CpuSnapshot { - pub model: Option, - pub total: CpuReading, - pub cores: Vec, - pub frequencies_mhz: Vec>, - pub package_temperature_c: Option, - pub package_temperature_crit_c: Option, - pub core_temperatures_c: Vec<(usize, f32, f32)>, - pub load_average: [f64; 3], - pub uptime_seconds: Option, - pub battery_percent: Option, -} - -#[derive(Debug, Clone, Copy, Default)] -#[cfg(target_os = "linux")] -struct Times([u64; 10]); - -#[cfg(target_os = "linux")] -type CoreTemperatureReading = (usize, f32, f32); -#[cfg(target_os = "linux")] -type TemperatureReadings = (Option, Option, Vec); - -/// Stateful CPU sampler. Linux files can be overridden to make it deterministic in tests. -pub struct CpuMonitor { - #[cfg(target_os = "linux")] - root: PathBuf, - #[cfg(target_os = "linux")] - previous: BTreeMap, -} - -// Derivable only where the Linux fields are compiled out; the root default -// is `/`, not an empty path. -#[allow(clippy::derivable_impls)] -impl Default for CpuMonitor { - fn default() -> Self { - Self { - #[cfg(target_os = "linux")] - root: PathBuf::from("/"), - #[cfg(target_os = "linux")] - previous: BTreeMap::new(), - } - } -} - -impl CpuMonitor { - /// Use a filesystem root containing `proc` and `sys`; primarily useful for fixtures. - #[cfg(target_os = "linux")] - pub fn with_root(root: impl Into) -> Self { - Self { - root: root.into(), - previous: BTreeMap::new(), - } - } - - /// Read CPU readings and the Linux-only supplementary data when available. - pub fn sample(&mut self) -> CpuSnapshot { - #[cfg(target_os = "linux")] - { - self.sample_linux() - } - #[cfg(not(target_os = "linux"))] - { - CpuSnapshot::default() - } - } - - #[cfg(target_os = "linux")] - fn sample_linux(&mut self) -> CpuSnapshot { - let root = self.root.clone(); - let stat = fs::read_to_string(root.join("proc/stat")).unwrap_or_default(); - let mut readings = Vec::new(); - for line in stat.lines() { - let mut parts = line.split_whitespace(); - let Some(name) = parts.next().filter(|n| { - *n == "cpu" - || n.strip_prefix("cpu") - .is_some_and(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())) - }) else { - continue; - }; - let values: Vec = parts - .filter_map(|part| part.parse().ok()) - .take(10) - .collect(); - if values.len() < 4 { - continue; - } - let mut raw = [0; 10]; - raw[..values.len()].copy_from_slice(&values); - let current = Times(raw); - let previous = self.previous.insert(name.to_owned(), current); - readings.push(( - name.to_owned(), - previous - .map(|old| cpu_delta(old, current)) - .unwrap_or_default(), - )); - } - let total = readings - .iter() - .find(|(name, _)| name == "cpu") - .map(|(_, reading)| reading.clone()) - .unwrap_or_default(); - let cores = readings - .into_iter() - .filter(|(name, _)| name != "cpu") - .map(|(_, reading)| reading) - .collect(); - let (package_temperature_c, package_temperature_crit_c, core_temperatures_c) = - read_temperatures(&root); - CpuSnapshot { - model: None, - total, - cores, - frequencies_mhz: read_frequencies(&root), - package_temperature_c, - package_temperature_crit_c, - core_temperatures_c, - load_average: read_load(&root), - uptime_seconds: read_uptime(&root), - battery_percent: read_battery(&root), - } - } -} - -#[cfg(target_os = "linux")] -fn cpu_delta(old: Times, new: Times) -> CpuReading { - let mut delta = [0f64; 10]; - for (index, value) in delta.iter_mut().enumerate() { - *value = new.0[index].saturating_sub(old.0[index]) as f64; - } - // Linux reports guest time inside user/nice. Remove it from total and user/nice fields. - let total = delta.iter().sum::() - delta[8] - delta[9]; - let idle = delta[3] + delta[4]; - let pct = |v: f64| { - if total > 0.0 { - (v * 100.0 / total) as f32 - } else { - 0.0 - } - }; - CpuReading { - total: pct(total - idle), - user: pct(delta[0] - delta[8]), - nice: pct(delta[1] - delta[9]), - system: pct(delta[2]), - idle: pct(delta[3]), - iowait: pct(delta[4]), - irq: pct(delta[5]), - softirq: pct(delta[6]), - steal: pct(delta[7]), - guest: pct(delta[8]), - guest_nice: pct(delta[9]), - } -} - -#[cfg(target_os = "linux")] -fn read_frequencies(root: &Path) -> Vec> { - let base = root.join("sys/devices/system/cpu"); - let Ok(entries) = fs::read_dir(base) else { - return Vec::new(); - }; - let mut out = Vec::new(); - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - let Some(index) = name - .strip_prefix("cpu") - .and_then(|s| s.parse::().ok()) - else { - continue; - }; - if out.len() <= index { - out.resize(index + 1, None); - } - out[index] = fs::read_to_string(entry.path().join("cpufreq/scaling_cur_freq")) - .ok() - .and_then(|s| s.trim().parse::().ok()) - .map(|hz| hz / 1000); - } - out -} - -#[cfg(target_os = "linux")] -fn read_temperatures(root: &Path) -> TemperatureReadings { - let mut package = None; - let mut package_crit = None; - let mut cores = Vec::new(); - let topology = read_cpu_topology(root); - let Ok(devices) = fs::read_dir(root.join("sys/class/hwmon")) else { - return (package, package_crit, cores); - }; - for device in devices.flatten() { - let hwmon_path = device.path(); - let path = fs::canonicalize(&hwmon_path).unwrap_or_else(|_| hwmon_path.clone()); - let package_id = [hwmon_path.join("device"), path.join("device")] - .into_iter() - .filter_map(|device| fs::canonicalize(device).ok()) - .chain(std::iter::once(path.clone())) - .flat_map(|device| { - std::iter::successors(Some(device), |path| path.parent().map(Path::to_path_buf)) - }) - .find_map(|device| { - fs::read_to_string(device.join("physical_package_id")) - .ok() - .and_then(|s| s.trim().parse::().ok()) - }); - let Ok(entries) = fs::read_dir(&path) else { - continue; - }; - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - let Some(index) = name - .strip_prefix("temp") - .and_then(|s| s.strip_suffix("_input")) - .and_then(|s| s.parse::().ok()) - else { - continue; - }; - let prefix = format!("temp{index}"); - let label = fs::read_to_string(path.join(format!("{prefix}_label"))) - .unwrap_or_else(|_| prefix.clone()) - .trim() - .to_owned(); - let Ok(milli) = fs::read_to_string(entry.path()) - .ok() - .and_then(|s| s.trim().parse::().ok()) - .ok_or(()) - else { - continue; - }; - let temp = milli as f32 / 1000.0; - let crit = fs::read_to_string(path.join(format!("{prefix}_crit"))) - .ok() - .and_then(|s| s.trim().parse::().ok()) - .map(|v| v / 1000.0) - .unwrap_or(90.0); - let lower = label.to_ascii_lowercase(); - if lower.starts_with("package id") - || lower.starts_with("tdie") - || lower.starts_with("soc temperature") - { - if package.is_none() { - package = Some(temp); - package_crit = Some(crit); - } - } else if let Some(core_id) = lower - .strip_prefix("core") - .and_then(|s| s.trim().parse::().ok()) - { - let logical = package_id - .and_then(|package| topology.get(&(package, core_id)).copied()) - .or_else(|| { - let matches: Vec<_> = topology - .iter() - .filter_map(|(&(package, core), &logical)| { - (core == core_id).then_some((package, logical)) - }) - .collect(); - (matches.len() == 1).then(|| matches[0].1) - }); - if let Some(logical) = logical { - cores.push((logical, temp, crit)); - } - } - } - } - cores.sort_by_key(|(core, _, _)| *core); - (package, package_crit, cores) -} - -#[cfg(target_os = "linux")] -fn read_cpu_topology(root: &Path) -> BTreeMap<(usize, usize), usize> { - let Ok(cpuinfo) = fs::read_to_string(root.join("proc/cpuinfo")) else { - return BTreeMap::new(); - }; - let mut topology = BTreeMap::new(); - for processor in cpuinfo.split("\n\n") { - let fields: BTreeMap<_, _> = processor - .lines() - .filter_map(|line| line.split_once(':')) - .map(|(key, value)| (key.trim(), value.trim())) - .collect(); - let (Some(logical), Some(package), Some(core)) = ( - fields.get("processor").and_then(|value| value.parse().ok()), - fields - .get("physical id") - .and_then(|value| value.parse().ok()), - fields.get("core id").and_then(|value| value.parse().ok()), - ) else { - continue; - }; - topology.entry((package, core)).or_insert(logical); - } - topology -} - -#[cfg(target_os = "linux")] -fn read_load(root: &Path) -> [f64; 3] { - let s = fs::read_to_string(root.join("proc/loadavg")).unwrap_or_default(); - let mut p = s.split_whitespace().filter_map(|s| s.parse().ok()); - [ - p.next().unwrap_or(0.0), - p.next().unwrap_or(0.0), - p.next().unwrap_or(0.0), - ] -} -#[cfg(target_os = "linux")] -fn read_uptime(root: &Path) -> Option { - fs::read_to_string(root.join("proc/uptime")) - .ok()? - .split_whitespace() - .next()? - .parse::() - .ok() - .map(|v| v as u64) -} -#[cfg(target_os = "linux")] -fn read_battery(root: &Path) -> Option { - for entry in fs::read_dir(root.join("sys/class/power_supply")) - .ok()? - .flatten() - { - let path = entry.path(); - if fs::read_to_string(path.join("type")) - .ok() - .as_deref() - .map(str::trim) - != Some("Battery") - { - continue; - } - if let Ok(capacity) = fs::read_to_string(path.join("capacity")) { - return capacity.trim().parse().ok(); - } - let now = fs::read_to_string(path.join("energy_now")) - .or_else(|_| fs::read_to_string(path.join("charge_now"))) - .ok()? - .trim() - .parse::() - .ok()?; - let full = fs::read_to_string(path.join("energy_full")) - .or_else(|_| fs::read_to_string(path.join("charge_full"))) - .ok()? - .trim() - .parse::() - .ok()?; - if full > 0.0 { - return Some((now * 100.0 / full).clamp(0.0, 100.0)); - } - } - None -} - -#[cfg(all(test, target_os = "linux"))] -#[path = "cpu_tests.rs"] -mod tests; diff --git a/src/tui/src/ui/resources/cpu_tests.rs b/src/tui/src/ui/resources/cpu_tests.rs deleted file mode 100644 index 2215c2782..000000000 --- a/src/tui/src/ui/resources/cpu_tests.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! Unit tests for `cpu`. - -use super::*; -#[test] -fn linux_cpu_percent_uses_guest_adjusted_totals_and_field_deltas() { - let reading = cpu_delta( - Times([10, 0, 10, 60, 0, 0, 0, 0, 0, 0]), - Times([30, 0, 20, 110, 10, 0, 0, 0, 5, 0]), - ); - assert!((reading.total - 33.333_332).abs() < 0.001); - assert!((reading.user - 16.666_666).abs() < 0.001); - assert!((reading.system - 11.111_111).abs() < 0.001); - assert!((reading.idle - 55.555_557).abs() < 0.001); - assert!((reading.iowait - 11.111_111).abs() < 0.001); - assert!((reading.guest - 5.555_556).abs() < 0.001); -} - -#[test] -fn missing_cpu_frequency_keeps_logical_cpu_slot() { - let temp = tempfile::tempdir().unwrap(); - let cpu1 = temp.path().join("sys/devices/system/cpu/cpu1/cpufreq"); - fs::create_dir_all(&cpu1).unwrap(); - fs::write(cpu1.join("scaling_cur_freq"), "1200000\n").unwrap(); - - assert_eq!(read_frequencies(temp.path()), [None, Some(1200)]); -} - -#[test] -fn repeated_core_labels_map_to_distinct_packages() { - let temp = tempfile::tempdir().unwrap(); - let write = |path: &str, value: &str| { - let path = temp.path().join(path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, value).unwrap(); - }; - write("proc/cpuinfo", "processor : 0\nphysical id : 0\ncore id : 0\n\nprocessor : 1\nphysical id : 0\ncore id : 1\n\nprocessor : 2\nphysical id : 1\ncore id : 0\n\nprocessor : 3\nphysical id : 1\ncore id : 1\n"); - for (hwmon, package, temp_c) in [(0, 0, 51), (1, 1, 61)] { - let device = temp - .path() - .join(format!("sys/devices/platform/coretemp.{hwmon}")); - fs::create_dir_all(&device).unwrap(); - fs::write(device.join("physical_package_id"), package.to_string()).unwrap(); - let hwmon_path = temp.path().join(format!("sys/class/hwmon/hwmon{hwmon}")); - fs::create_dir_all(&hwmon_path).unwrap(); - #[cfg(unix)] - std::os::unix::fs::symlink(&device, hwmon_path.join("device")).unwrap(); - fs::write(hwmon_path.join("temp1_input"), format!("{}000\n", temp_c)).unwrap(); - fs::write(hwmon_path.join("temp1_label"), "Core 0\n").unwrap(); - } - - assert_eq!( - read_temperatures(temp.path()).2, - [(0, 51.0, 90.0), (2, 61.0, 90.0)] - ); -} - -#[cfg(target_os = "linux")] -#[test] -fn linux_cpu_collector_reads_pair_deltas_and_hwmon_labels() { - let temp = tempfile::tempdir().unwrap(); - let write = |path: &str, value: &str| { - let path = temp.path().join(path); - fs::create_dir_all(path.parent().unwrap()).unwrap(); - fs::write(path, value).unwrap(); - }; - write( - "proc/stat", - "cpu 30 0 20 110 10 0 0 0 5 0\ncpu0 20 0 10 50 5 0 0 0 5 0\n", - ); - write( - "proc/cpuinfo", - "processor : 0\nphysical id : 0\ncore id : 0\n", - ); - write("proc/loadavg", "0.50 0.25 0.10 1/20 100\n"); - write("proc/uptime", "1234.5 0\n"); - let hwmon = temp.path().join("sys/class/hwmon/hwmon0"); - fs::create_dir_all(&hwmon).unwrap(); - fs::write(hwmon.join("temp1_input"), "65000\n").unwrap(); - fs::write(hwmon.join("temp1_label"), "Package id 0\n").unwrap(); - fs::write(hwmon.join("temp1_crit"), "100000\n").unwrap(); - fs::write(hwmon.join("temp2_input"), "60000\n").unwrap(); - fs::write(hwmon.join("temp2_label"), "Core 0\n").unwrap(); - let mut monitor = CpuMonitor::with_root(temp.path()); - let first = monitor.sample(); - assert_eq!(first.total, CpuReading::default()); - write( - "proc/stat", - "cpu 50 0 30 160 20 0 0 0 10 0\ncpu0 30 0 20 70 10 0 0 0 10 0\n", - ); - let second = monitor.sample(); - assert!((second.total.total - 33.333_332).abs() < 0.001); - assert_eq!(second.cores.len(), 1); - assert_eq!(second.package_temperature_c, Some(65.0)); - assert_eq!(second.package_temperature_crit_c, Some(100.0)); - assert_eq!(second.core_temperatures_c, [(0, 60.0, 90.0)]); - assert_eq!(second.load_average, [0.5, 0.25, 0.1]); - assert_eq!(second.uptime_seconds, Some(1234)); -} diff --git a/src/tui/src/ui/resources/net.rs b/src/tui/src/ui/resources/net.rs deleted file mode 100644 index f91c04da9..000000000 --- a/src/tui/src/ui/resources/net.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! Network graph autoscaling and interface selection helpers. - -use std::collections::VecDeque; - -/// btop-style adaptive scale for one network direction, in bytes per second. -/// -/// The five most recent rates are retained independently of the up/down -/// counters so a scale change uses the same rolling window as btop. -#[derive(Debug, Clone)] -pub struct NetScaler { - max: f64, - history: VecDeque, - above: u8, - below: u8, -} - -impl Default for NetScaler { - fn default() -> Self { - Self::new(10.0 * 1024.0) - } -} - -impl NetScaler { - /// Create a scaler with its maximum clamped to btop's 10 KiB/s floor. - pub fn new(max: f64) -> Self { - Self { - max: max.max(10.0 * 1024.0), - history: VecDeque::with_capacity(5), - above: 0, - below: 0, - } - } - - /// Current graph ceiling in bytes per second. - pub fn max(&self) -> f64 { - self.max - } - - /// Incorporate one sample and return the current ceiling. - pub fn sample(&mut self, rate: f64) -> f64 { - let rate = rate.max(0.0); - if self.history.len() == 5 { - self.history.pop_front(); - } - self.history.push_back(rate); - if rate > self.max { - self.above = self.above.saturating_add(1); - self.below = self.below.saturating_sub(1); - } else if self.max > 10.0 * 1024.0 && rate < self.max / 10.0 { - self.below = self.below.saturating_add(1); - self.above = self.above.saturating_sub(1); - } - if self.above >= 5 { - self.max = (self.average().floor() * 1.3).floor().max(10.0 * 1024.0); - self.above = 0; - self.below = 0; - } else if self.below >= 5 { - self.max = (self.average().floor() * 3.0).floor().max(10.0 * 1024.0); - self.above = 0; - self.below = 0; - } - self.max - } - - fn average(&self) -> f64 { - self.history.iter().sum::() / self.history.len().max(1) as f64 - } -} - -/// Return the maximum shared ceiling when sync is enabled. -pub fn synced_max(download: f64, upload: f64, sync: bool) -> (f64, f64) { - if sync { - let max = download.max(upload); - (max, max) - } else { - (download, upload) - } -} - -/// Cycle an interface index forward or backward, ignoring down interfaces. -pub fn cycle_interface( - current: Option<&str>, - interfaces: &[(&str, bool)], - forward: bool, -) -> Option { - let up: Vec<_> = interfaces - .iter() - .filter(|(name, is_up)| *is_up && !is_loopback(name)) - .map(|(name, _)| *name) - .collect(); - if up.is_empty() { - return None; - } - let index = current.and_then(|name| up.iter().position(|candidate| *candidate == name)); - let next = match (index, forward) { - (Some(index), true) => (index + 1) % up.len(), - (Some(index), false) => (index + up.len() - 1) % up.len(), - (None, true) => 0, - (None, false) => up.len() - 1, - }; - Some(up[next].to_owned()) -} - -/// Pick the first up, non-loopback interface with observed traffic, -/// preferring one with a routable address. -/// -/// The preference keeps link-only interfaces such as macOS's `awdl0`, which -/// carry a little traffic but hold only a link-local address, from beating -/// the interface the machine actually uses. -pub fn default_interface( - interfaces: &[crate::ui::resources::sampler::NetworkSnapshot], -) -> Option<&str> { - let candidates = || { - interfaces.iter().filter(|interface| { - interface.up - && !is_loopback(&interface.interface) - && (interface.total_received_bytes > 0 - || interface.total_transmitted_bytes > 0 - || interface.received_bytes_per_second > 0.0 - || interface.transmitted_bytes_per_second > 0.0) - }) - }; - candidates() - .find(|interface| interface.ip_addresses.iter().any(|a| is_routable(a))) - .or_else(|| candidates().next()) - .map(|interface| interface.interface.as_str()) -} - -fn is_loopback(name: &str) -> bool { - name == "lo" - || name.starts_with("lo:") - || name - .strip_prefix("lo") - .is_some_and(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit())) - || name == "Loopback Pseudo-Interface 1" -} - -/// Whether an address, optionally with a `/prefix`, is neither loopback nor -/// link-local. -fn is_routable(address: &str) -> bool { - let address = address.split('/').next().unwrap_or_default(); - match address.parse::() { - Ok(std::net::IpAddr::V4(v4)) => !v4.is_loopback() && !v4.is_link_local(), - Ok(std::net::IpAddr::V6(v6)) => !v6.is_loopback() && (v6.segments()[0] & 0xffc0) != 0xfe80, - Err(_) => false, - } -} - -#[cfg(test)] -#[path = "net_tests.rs"] -mod tests; diff --git a/src/tui/src/ui/resources/net_tests.rs b/src/tui/src/ui/resources/net_tests.rs deleted file mode 100644 index 3825c3c43..000000000 --- a/src/tui/src/ui/resources/net_tests.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Unit tests for `net`. - -use super::*; - -#[test] -fn scaler_tracks_steady_burst_idle_with_five_sample_windows() { - let mut scale = NetScaler::new(10.0 * 1024.0); - let steady = (0..6).map(|_| scale.sample(2_000.0)).collect::>(); - assert_eq!(steady, vec![10_240.0; 6]); - let burst = (0..5).map(|_| scale.sample(20_000.0)).collect::>(); - assert_eq!(burst[..4], [10_240.0; 4]); - assert_eq!(burst[4], 26_000.0); - let idle = (0..5).map(|_| scale.sample(0.0)).collect::>(); - assert_eq!(idle[..4], [26_000.0; 4]); - assert_eq!(idle[4], 10_240.0); -} - -#[test] -fn scaler_counters_balance_instead_of_resetting_on_neutral_samples() { - let mut scale = NetScaler::default(); - for rate in [20_000.0, 20_000.0, 20_000.0, 20_000.0, 10_240.0, 20_000.0] { - scale.sample(rate); - } - assert_eq!(scale.max(), 23_462.0); -} - -#[test] -fn interface_cycling_skips_down_interfaces() { - let interfaces = [("lo", true), ("eth0", false), ("wlan0", true)]; - assert_eq!( - cycle_interface(Some("lo"), &interfaces, true).as_deref(), - Some("wlan0") - ); - assert_eq!( - cycle_interface(Some("lo"), &interfaces, false).as_deref(), - Some("wlan0") - ); -} - -#[test] -fn default_interface_picks_first_up_non_loopback_with_traffic() { - let samples = vec![ - crate::ui::resources::sampler::NetworkSnapshot { - interface: "lo".into(), - up: true, - connected: true, - ip_addresses: vec![], - received_bytes_per_second: 4.0, - transmitted_bytes_per_second: 0.0, - total_received_bytes: 4, - total_transmitted_bytes: 0, - }, - crate::ui::resources::sampler::NetworkSnapshot { - interface: "eth0".into(), - up: false, - connected: false, - ip_addresses: vec![], - received_bytes_per_second: 0.0, - transmitted_bytes_per_second: 0.0, - total_received_bytes: 1_000_000, - total_transmitted_bytes: 1_000_000, - }, - crate::ui::resources::sampler::NetworkSnapshot { - interface: "wlan0".into(), - up: true, - connected: true, - ip_addresses: vec![], - received_bytes_per_second: 4.0, - transmitted_bytes_per_second: 0.0, - total_received_bytes: 4, - total_transmitted_bytes: 0, - }, - crate::ui::resources::sampler::NetworkSnapshot { - interface: "enp2s0".into(), - up: true, - connected: true, - ip_addresses: vec![], - received_bytes_per_second: 8.0, - transmitted_bytes_per_second: 0.0, - total_received_bytes: 50, - total_transmitted_bytes: 0, - }, - ]; - assert_eq!(default_interface(&samples), Some("wlan0")); -} - -#[test] -fn default_interface_prefers_a_routable_address_over_link_local_traffic() { - let interface = - |name: &str, addresses: &[&str]| crate::ui::resources::sampler::NetworkSnapshot { - interface: name.into(), - up: true, - connected: true, - ip_addresses: addresses.iter().map(|address| (*address).into()).collect(), - received_bytes_per_second: 0.0, - transmitted_bytes_per_second: 0.0, - total_received_bytes: 1_000, - total_transmitted_bytes: 1_000, - }; - // macOS order: loopback, the AirDrop link with only a link-local - // address, then the Wi-Fi interface that actually carries traffic. - let samples = vec![ - interface("lo0", &["127.0.0.1/8", "::1/128"]), - interface("awdl0", &["fe80::b4ef:e6ff:fed7:6d54/64"]), - interface("en0", &["fe80::1c2b:3cff:fe4d:5e6f/64", "192.168.8.66/24"]), - ]; - assert_eq!(default_interface(&samples), Some("en0")); -} - -#[test] -fn sync_uses_larger_direction_scale() { - assert_eq!(synced_max(10.0, 20.0, true), (20.0, 20.0)); -} diff --git a/src/tui/src/ui/resources/sampler/disks.rs b/src/tui/src/ui/resources/sampler/disks.rs deleted file mode 100644 index 90afb5dad..000000000 --- a/src/tui/src/ui/resources/sampler/disks.rs +++ /dev/null @@ -1,114 +0,0 @@ -//! The disks a sample lists, with each one's IO where the platform has it. - -#[cfg(not(target_os = "linux"))] -use super::source::per_second; -use super::*; - -/// What one sample needs to turn sysinfo's disk counters into rates. Linux -/// reads its rates from `/proc` instead. -#[cfg(not(target_os = "linux"))] -pub(super) struct DiskRates { - pub elapsed: f64, - pub baseline_ready: bool, -} - -/// Build the visible disks, in the order btop lists them. -pub(super) fn disk_snapshots( - disks: &Disks, - options: &DiskOptions, - #[cfg(not(target_os = "linux"))] rates: DiskRates, - #[cfg(target_os = "linux")] io: &std::collections::HashMap, -) -> Vec { - #[cfg(target_os = "macos")] - { - let mounted = macos_disks(disks, options, &rates); - if !mounted.is_empty() { - return mounted; - } - } - disks - .list() - .iter() - .filter(|disk| disk_is_visible(disk, options)) - .map(|disk| { - #[cfg(target_os = "linux")] - let io = io - .get(disk.name().to_string_lossy().trim_start_matches("/dev/")) - .copied(); - DiskSnapshot { - device: disk.name().to_string_lossy().into_owned(), - mount: disk.mount_point().to_string_lossy().into_owned(), - total_bytes: disk.total_space(), - used_bytes: disk.total_space().saturating_sub(disk.available_space()), - #[cfg(target_os = "linux")] - read_bytes_per_second: io.map_or(0.0, |io| io.read_rate), - #[cfg(not(target_os = "linux"))] - read_bytes_per_second: per_second( - disk.usage().read_bytes, - rates.elapsed, - rates.baseline_ready, - ), - #[cfg(target_os = "linux")] - write_bytes_per_second: io.map_or(0.0, |io| io.write_rate), - #[cfg(not(target_os = "linux"))] - write_bytes_per_second: per_second( - disk.usage().written_bytes, - rates.elapsed, - rates.baseline_ready, - ), - #[cfg(target_os = "linux")] - busy_percent: io.map(|io| io.busy), - #[cfg(not(target_os = "linux"))] - busy_percent: None, - #[cfg(target_os = "linux")] - has_io: io.is_some(), - #[cfg(not(target_os = "linux"))] - has_io: true, - } - }) - .collect() -} - -/// Every local volume from the mount table, each with the IO of the physical -/// disk it lives on. sysinfo measures IO per whole disk, so one reading per -/// disk serves every volume on it; a disk sysinfo does not list has none. -#[cfg(target_os = "macos")] -fn macos_disks(disks: &Disks, options: &DiskOptions, rates: &DiskRates) -> Vec { - let mut io = std::collections::HashMap::::new(); - for disk in disks.list() { - let Some(device) = super::macos::device_of(disk.mount_point()) else { - continue; - }; - let Some(whole) = super::macos::whole_disk(&device) else { - continue; - }; - let usage = disk.usage(); - io.entry(whole.to_owned()).or_insert(( - per_second(usage.read_bytes, rates.elapsed, rates.baseline_ready), - per_second(usage.written_bytes, rates.elapsed, rates.baseline_ready), - )); - } - let options = DiskOptions { - use_fstab: false, - ..options.clone() - }; - super::macos::local_mounts() - .into_iter() - .filter(|mount| { - mount_is_visible(&mount.mount, &mount.device, &mount.filesystem, &options, "") - }) - .map(|mount| { - let rates = super::macos::whole_disk(&mount.device).and_then(|disk| io.get(disk)); - DiskSnapshot { - device: mount.device, - mount: mount.mount, - total_bytes: mount.total_bytes, - used_bytes: mount.total_bytes.saturating_sub(mount.available_bytes), - read_bytes_per_second: rates.map_or(0.0, |rates| rates.0), - write_bytes_per_second: rates.map_or(0.0, |rates| rates.1), - busy_percent: None, - has_io: rates.is_some(), - } - }) - .collect() -} diff --git a/src/tui/src/ui/resources/sampler/filters.rs b/src/tui/src/ui/resources/sampler/filters.rs deleted file mode 100644 index 5a822a18c..000000000 --- a/src/tui/src/ui/resources/sampler/filters.rs +++ /dev/null @@ -1,147 +0,0 @@ -//! Which processes get detailed refreshes, and which disks are listed. - -use super::*; - -/// Classify a process from what sysinfo has read of it so far. -#[cfg(target_os = "linux")] -fn agent_kind( - exe: Option<&std::path::Path>, - cmd: &[std::ffi::OsString], -) -> Option { - medulla::resources::agents::classify_process(&medulla::resources::agents::ProcessRecord { - pid: 0, - ppid: None, - exe: exe.map(std::path::Path::to_path_buf), - argv: Some( - cmd.iter() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect(), - ), - cwd: None, - started_at_secs: 0, - usage: Default::default(), - }) -} - -#[cfg(target_os = "linux")] -pub(super) fn should_refresh_task_details( - exe: Option<&std::path::Path>, - cmd: &[std::ffi::OsString], -) -> bool { - agent_kind(exe, cmd).is_some() -} - -#[cfg(target_os = "linux")] -pub(super) fn should_refresh_process_tree( - exe: Option<&std::path::Path>, - cmd: &[std::ffi::OsString], -) -> bool { - agent_kind(exe, cmd).is_some_and(|kind| kind != medulla::resources::agents::AgentKind::Shell) -} - -#[cfg(target_os = "linux")] -pub(super) fn may_be_agent_process(name: &str) -> bool { - medulla::resources::agents::may_be_agent_name(name) -} - -#[cfg(target_os = "linux")] -pub(super) fn pids_in_process_trees( - processes: impl IntoIterator)>, - roots: impl IntoIterator, -) -> Vec { - let mut children = std::collections::HashMap::>::new(); - for (pid, parent) in processes { - if let Some(parent) = parent { - children.entry(parent).or_default().push(pid); - } - } - let mut pending = roots.into_iter().collect::>(); - if pending.is_empty() { - return Vec::new(); - } - let mut included = std::collections::HashSet::new(); - while let Some(pid) = pending.pop() { - if !included.insert(pid) { - continue; - } - if let Some(descendants) = children.get(&pid) { - pending.extend(descendants.iter().copied()); - } - } - included.into_iter().collect() -} - -pub(super) fn disk_is_visible(disk: &sysinfo::Disk, options: &DiskOptions) -> bool { - let mount = disk.mount_point().to_string_lossy(); - let device = disk.name().to_string_lossy(); - let fs = disk.file_system().to_string_lossy(); - #[cfg(target_os = "linux")] - let fstab = if options.use_fstab { - std::fs::read_to_string("/etc/fstab").unwrap_or_default() - } else { - String::new() - }; - #[cfg(not(target_os = "linux"))] - let fstab = String::new(); - #[cfg(not(target_os = "linux"))] - let options = &DiskOptions { - use_fstab: false, - ..options.clone() - }; - mount_is_visible(&mount, &device, &fs, options, &fstab) -} - -pub(super) fn mount_is_visible( - mount: &str, - device: &str, - filesystem: &str, - options: &DiskOptions, - fstab: &str, -) -> bool { - if options.only_physical { - let fs = filesystem.to_ascii_lowercase(); - if [ - "tmpfs", "devtmpfs", "overlay", "squashfs", "proc", "sysfs", "cgroup", - ] - .iter() - .any(|virtual_fs| fs == *virtual_fs) - || device.starts_with("/dev/loop") - || device.starts_with("/dev/ram") - { - return false; - } - } - if options.use_fstab { - let mounts: std::collections::HashSet = fstab - .lines() - .filter_map(|line| { - let line = line.split('#').next()?.trim(); - let fields: Vec<_> = line.split_whitespace().collect(); - (fields.len() >= 2).then(|| fields[1].replace("\\040", " ")) - }) - .collect(); - if !mounts.contains(mount) { - return false; - } - } - let filters: Vec<_> = options - .filter - .split(',') - .map(str::trim) - .filter(|s| !s.is_empty()) - .collect(); - for filter in filters.iter().filter_map(|s| s.strip_prefix("exclude=")) { - if mount == filter || mount.starts_with(&format!("{}/", filter.trim_end_matches('/'))) { - return false; - } - } - let includes: Vec<_> = filters - .iter() - .filter(|s| !s.starts_with("exclude=")) - .copied() - .collect(); - includes.is_empty() - || includes.iter().any(|prefix| { - mount == *prefix || mount.starts_with(&format!("{}/", prefix.trim_end_matches('/'))) - }) -} diff --git a/src/tui/src/ui/resources/sampler/history.rs b/src/tui/src/ui/resources/sampler/history.rs deleted file mode 100644 index b508b2be1..000000000 --- a/src/tui/src/ui/resources/sampler/history.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Bounded, cheaply cloneable sample history. - -use std::collections::VecDeque; -use std::sync::Arc; - -/// A bounded FIFO ring. Clones share storage until either copy is mutated. -#[derive(Debug, Clone)] -pub struct History(Arc>); - -impl Default for History { - fn default() -> Self { - Self(Arc::new(VecDeque::new())) - } -} - -impl History { - /// Create an empty ring retaining at most `capacity` samples. - pub fn new(capacity: usize) -> Self { - Self(Arc::new(VecDeque::with_capacity(capacity))) - } - - /// Append a sample and discard the oldest entries beyond capacity. - pub fn push(&mut self, value: T, capacity: usize) { - let values = Arc::make_mut(&mut self.0); - if capacity == 0 { - values.clear(); - return; - } - values.push_back(value); - while values.len() > capacity { - values.pop_front(); - } - } - - /// Samples oldest first. - pub fn iter(&self) -> impl Iterator { - self.0.iter() - } - - /// Number of retained samples. - pub fn len(&self) -> usize { - self.0.len() - } - - /// Whether this history has no samples. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } -} diff --git a/src/tui/src/ui/resources/sampler/linux.rs b/src/tui/src/ui/resources/sampler/linux.rs deleted file mode 100644 index e561138cd..000000000 --- a/src/tui/src/ui/resources/sampler/linux.rs +++ /dev/null @@ -1,153 +0,0 @@ -//! Linux readings sysinfo does not provide: `/proc` memory and `/sys` block -//! and interface state. - -use super::*; - -#[cfg(target_os = "linux")] -pub(super) fn linux_interface_flags(name: &str) -> Option { - std::fs::read_to_string( - std::path::Path::new("/sys/class/net") - .join(name) - .join("flags"), - ) - .ok() - .and_then(|flags| u32::from_str_radix(flags.trim().trim_start_matches("0x"), 16).ok()) -} - -#[cfg(any(target_os = "linux", test))] -pub(super) fn linux_interface_state(flags: u32) -> (bool, bool) { - (flags & 0x1 != 0, flags & 0x40 != 0) -} - -#[cfg(target_os = "linux")] -pub(super) struct LinuxResourceMonitor { - pub(super) root: std::path::PathBuf, - pub(super) previous: std::collections::HashMap, - pub(super) previous_uptime: Option, -} - -#[cfg(target_os = "linux")] -pub(super) struct LinuxSample { - pub(super) memory: MemoryReading, - pub(super) io: std::collections::HashMap, -} - -#[cfg(target_os = "linux")] -#[derive(Default)] -pub(super) struct MemoryReading { - pub(super) total: u64, - pub(super) available: u64, - pub(super) free: u64, - pub(super) cached: u64, -} - -#[cfg(target_os = "linux")] -#[derive(Clone, Copy)] -pub(super) struct IoReading { - pub(super) read_rate: f64, - pub(super) write_rate: f64, - pub(super) busy: f64, -} - -#[cfg(target_os = "linux")] -impl Default for LinuxResourceMonitor { - fn default() -> Self { - Self { - root: "/".into(), - previous: Default::default(), - previous_uptime: None, - } - } -} - -#[cfg(target_os = "linux")] -impl LinuxResourceMonitor { - pub(super) fn sample(&mut self, disks: &Disks, elapsed: f64) -> LinuxSample { - use std::fs; - let mem = fs::read_to_string(self.root.join("proc/meminfo")).unwrap_or_default(); - let memory = parse_memory(&mem); - let uptime = fs::read_to_string(self.root.join("proc/uptime")) - .ok() - .and_then(|s| s.split_whitespace().next()?.parse::().ok()) - .unwrap_or(0.0); - let seconds = self - .previous_uptime - .replace(uptime) - .map(|old| (uptime - old).max(0.001)) - .unwrap_or(elapsed.max(0.001)); - let mut io = std::collections::HashMap::new(); - for disk in disks.list() { - let name = disk - .name() - .to_string_lossy() - .trim_start_matches("/dev/") - .to_owned(); - let Some(now) = read_block_stat(&self.root, &name) else { - continue; - }; - if let Some(old) = self.previous.insert(name.clone(), now) { - io.insert(name, io_delta(old, now, seconds)); - } - } - LinuxSample { memory, io } - } -} - -#[cfg(target_os = "linux")] -pub(super) fn read_block_stat(root: &std::path::Path, name: &str) -> Option<(u64, u64, u64)> { - use std::fs; - let stat = fs::read_to_string(root.join("sys/class/block").join(name).join("stat")) - .or_else(|_| fs::read_to_string(root.join("sys/block").join(name).join("stat"))) - .ok()?; - parse_block_stat(&stat) -} - -#[cfg(target_os = "linux")] -pub(super) fn parse_memory(contents: &str) -> MemoryReading { - let fields: std::collections::HashMap<&str, u64> = contents - .lines() - .filter_map(|line| { - let mut p = line.split_whitespace(); - let (key, value) = (p.next()?, p.next()?.parse::().ok()?); - Some((key.trim_end_matches(':'), value.saturating_mul(1024))) - }) - .collect(); - let total = fields.get("MemTotal").copied().unwrap_or(0); - let free = fields.get("MemFree").copied().unwrap_or(0); - let cached = fields.get("Cached").copied().unwrap_or(0); - let available = fields - .get("MemAvailable") - .copied() - .unwrap_or_else(|| free.saturating_add(cached)) - .min(total); - MemoryReading { - total, - available, - free, - cached, - } -} - -#[cfg(target_os = "linux")] -pub(super) fn io_delta(old: (u64, u64, u64), new: (u64, u64, u64), seconds: f64) -> IoReading { - let seconds = seconds.max(0.001); - IoReading { - read_rate: new.0.saturating_sub(old.0).saturating_mul(512) as f64 / seconds, - write_rate: new.1.saturating_sub(old.1).saturating_mul(512) as f64 / seconds, - busy: (new.2.saturating_sub(old.2) as f64 / seconds / 10.0).clamp(0.0, 100.0), - } -} - -#[cfg(target_os = "linux")] -pub(super) fn parse_block_stat(contents: &str) -> Option<(u64, u64, u64)> { - let values: Vec = contents - .split_whitespace() - .map(str::parse) - .collect::>() - .ok()?; - (values.len() >= 10).then(|| (values[2], values[6], values[9])) -} - -#[cfg(test)] -#[path = "linux_tests.rs"] -mod tests; diff --git a/src/tui/src/ui/resources/sampler/linux_tests.rs b/src/tui/src/ui/resources/sampler/linux_tests.rs deleted file mode 100644 index 790d00aa6..000000000 --- a/src/tui/src/ui/resources/sampler/linux_tests.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! Unit tests for `linux`. - -#[test] -pub(super) fn linux_flags_distinguish_admin_up_from_running() { - assert_eq!(super::linux_interface_state(0x1), (true, false)); - assert_eq!(super::linux_interface_state(0x40), (false, true)); -} diff --git a/src/tui/src/ui/resources/sampler/macos.rs b/src/tui/src/ui/resources/sampler/macos.rs deleted file mode 100644 index e8ffa75c2..000000000 --- a/src/tui/src/ui/resources/sampler/macos.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! Every local mount on macOS, read from the kernel's mount table. -//! -//! sysinfo lists only the volumes Finder would browse, which on a stock Mac is -//! the root and its Data twin. btop lists the rest of the APFS family too — -//! VM, Preboot, Update, xarts — and so does this. - -/// One mounted local filesystem. -pub(super) struct Mount { - /// The device node, `/dev/disk3s1s1`. - pub device: String, - pub mount: String, - pub filesystem: String, - pub total_bytes: u64, - pub available_bytes: u64, -} - -/// Filesystems the kernel reports as local that hold no data of their own. -const PSEUDO: [&str; 3] = ["devfs", "autofs", "nullfs"]; - -/// The local mounts, in the kernel's mount order. -pub(super) fn local_mounts() -> Vec { - // SAFETY: a null buffer asks only for the count. - let count = unsafe { libc::getfsstat(std::ptr::null_mut(), 0, libc::MNT_NOWAIT) }; - if count < 1 { - return Vec::new(); - } - let mut table: Vec = Vec::with_capacity(count as usize); - let size = (count as usize * std::mem::size_of::()) as libc::c_int; - // SAFETY: `table` has room for `count` entries, which is what `size` says. - let filled = unsafe { libc::getfsstat(table.as_mut_ptr(), size, libc::MNT_NOWAIT) }; - if filled < 1 { - return Vec::new(); - } - // SAFETY: the kernel initialised the first `filled` entries, at most `count`. - unsafe { table.set_len((filled as usize).min(count as usize)) }; - table - .iter() - .filter(|entry| entry.f_flags & libc::MNT_LOCAL as u32 != 0) - .map(|entry| Mount { - device: text(&entry.f_mntfromname), - mount: text(&entry.f_mntonname), - filesystem: text(&entry.f_fstypename), - total_bytes: entry.f_blocks.saturating_mul(u64::from(entry.f_bsize)), - available_bytes: entry.f_bavail.saturating_mul(u64::from(entry.f_bsize)), - }) - .filter(|mount| !PSEUDO.contains(&mount.filesystem.as_str())) - .collect() -} - -/// The whole disk a volume lives on: `/dev/disk3s1s1` is on `disk3`. Every -/// volume of one APFS container shares that disk's IO counters. -pub(super) fn whole_disk(device: &str) -> Option<&str> { - let name = device.strip_prefix("/dev/")?; - let digits = name.strip_prefix("disk")?; - let end = digits - .find(|c: char| !c.is_ascii_digit()) - .unwrap_or(digits.len()); - (end > 0).then(|| &name[..4 + end]) -} - -/// The device a mount point is mounted from. -pub(super) fn device_of(mount: &std::path::Path) -> Option { - use std::os::unix::ffi::OsStrExt; - let path = std::ffi::CString::new(mount.as_os_str().as_bytes()).ok()?; - let mut entry = std::mem::MaybeUninit::::zeroed(); - // SAFETY: `path` is NUL-terminated and `entry` is a writable statfs. - if unsafe { libc::statfs(path.as_ptr(), entry.as_mut_ptr()) } != 0 { - return None; - } - // SAFETY: statfs returned 0, so it filled `entry`. - Some(text(&unsafe { entry.assume_init() }.f_mntfromname)) -} - -fn text(raw: &[libc::c_char]) -> String { - let bytes: Vec = raw - .iter() - .take_while(|byte| **byte != 0) - .map(|byte| *byte as u8) - .collect(); - String::from_utf8_lossy(&bytes).into_owned() -} diff --git a/src/tui/src/ui/resources/sampler/mod.rs b/src/tui/src/ui/resources/sampler/mod.rs deleted file mode 100644 index 59128f08f..000000000 --- a/src/tui/src/ui/resources/sampler/mod.rs +++ /dev/null @@ -1,168 +0,0 @@ -//! Background system resource sampling and immutable snapshots. - -mod history; -mod types; - -pub use history::History; -pub use types::{ - DiskOptions, DiskSnapshot, NetworkSnapshot, ProcessSnapshot, ResourceHistory, ResourceSnapshot, -}; - -mod disks; -mod filters; -#[cfg(target_os = "linux")] -mod linux; -#[cfg(target_os = "macos")] -mod macos; -mod source; -#[cfg(test)] -mod tests; - -use disks::*; -use filters::*; -#[cfg(target_os = "linux")] -use linux::*; -#[cfg(test)] -use source::per_second; -pub use source::SystemResourceSource; - -use std::sync::Arc; -use std::time::{Duration, Instant}; - -#[cfg(target_os = "linux")] -use sysinfo::Pid; -use sysinfo::{Disks, Networks, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind}; -use tokio::sync::watch; - -/// A source of resource snapshots, injectable to test task ordering without -/// depending on the host machine. -pub trait ResourceSource: Send + 'static { - /// Read the next immutable resource snapshot. - fn sample(&mut self) -> ResourceSnapshot; - - /// Apply the current disk collection options when the source supports them. - fn update_disk_options(&mut self, _options: DiskOptions) {} -} - -/// Change the sampler cadence only when its value differs. -/// -/// `watch::Sender::send_replace` wakes receivers even for identical values; -/// repeatedly doing that from the UI loop would keep restarting the timer and -/// could starve samples while input or runtime events arrive continuously. -pub fn update_interval(sender: &watch::Sender>, period: Option) -> bool { - sender.send_if_modified(|current| { - if *current == period { - false - } else { - *current = period; - true - } - }) -} - -/// Update disk collection preferences only when they changed. -pub fn update_disk_options(sender: &watch::Sender, options: DiskOptions) -> bool { - sender.send_if_modified(|current| { - if *current == options { - false - } else { - *current = options; - true - } - }) -} - -/// Spawn a sampler task. Sampling runs on Tokio's blocking pool so a slow -/// process walk cannot hold up the UI/event-loop worker. -pub fn spawn_sampler( - source: S, - interval: watch::Receiver>, - history_capacity: usize, - output: F, -) -> tokio::task::JoinHandle<()> -where - S: ResourceSource, - F: Fn(Arc) -> bool + Send + Sync + 'static, -{ - spawn_sampler_inner(source, interval, None, history_capacity, output) -} - -/// Spawn a sampler whose disk filters can be changed while it is running. -pub fn spawn_sampler_with_disk_options( - source: S, - interval: watch::Receiver>, - disk_options: watch::Receiver, - history_capacity: usize, - output: F, -) -> tokio::task::JoinHandle<()> -where - S: ResourceSource, - F: Fn(Arc) -> bool + Send + Sync + 'static, -{ - spawn_sampler_inner( - source, - interval, - Some(disk_options), - history_capacity, - output, - ) -} - -fn spawn_sampler_inner( - mut source: S, - mut interval: watch::Receiver>, - mut disk_options: Option>, - history_capacity: usize, - output: F, -) -> tokio::task::JoinHandle<()> -where - S: ResourceSource, - F: Fn(Arc) -> bool + Send + Sync + 'static, -{ - tokio::spawn(async move { - let mut history = ResourceHistory::default(); - loop { - if let Some(options) = disk_options.as_mut() { - source.update_disk_options(options.borrow_and_update().clone()); - } - let current_interval = *interval.borrow(); - let period = match current_interval { - Some(period) => period.max(Duration::from_millis(1)), - None => { - if interval.changed().await.is_err() { - break; - } - continue; - } - }; - let mut timer = tokio::time::interval(period); - timer.tick().await; - tokio::select! { - _ = timer.tick() => { - let sampled = tokio::task::spawn_blocking(move || { - let snapshot = source.sample(); - (source, snapshot) - }).await; - let Ok((next_source, mut snapshot)) = sampled else { break }; - source = next_source; - history.push(&snapshot, history_capacity); - snapshot.history = Arc::new(history.clone()); - if !output(Arc::new(snapshot)) { - break; - } - } - changed = interval.changed() => if changed.is_err() { break; }, - changed = wait_for_disk_options(&mut disk_options) => if changed.is_err() { break; }, - } - } - }) -} - -async fn wait_for_disk_options( - receiver: &mut Option>, -) -> Result<(), watch::error::RecvError> { - match receiver { - Some(receiver) => receiver.changed().await, - None => std::future::pending().await, - } -} diff --git a/src/tui/src/ui/resources/sampler/source.rs b/src/tui/src/ui/resources/sampler/source.rs deleted file mode 100644 index 276433930..000000000 --- a/src/tui/src/ui/resources/sampler/source.rs +++ /dev/null @@ -1,467 +0,0 @@ -//! The live, sysinfo-backed [`ResourceSource`]. - -use super::*; - -/// Live source backed by one persistent sysinfo handle. -pub struct SystemResourceSource { - system: System, - disks: Disks, - networks: Networks, - last_sample: Option, - disk_peak_bytes_per_second: f64, - cpu_monitor: crate::ui::resources::CpuMonitor, - disk_options: DiskOptions, - #[cfg(target_os = "linux")] - linux: LinuxResourceMonitor, -} - -impl Default for SystemResourceSource { - fn default() -> Self { - Self { - system: System::new(), - disks: Disks::new(), - networks: Networks::new_with_refreshed_list(), - last_sample: None, - disk_peak_bytes_per_second: 1.0, - cpu_monitor: crate::ui::resources::CpuMonitor::default(), - disk_options: DiskOptions::default(), - #[cfg(target_os = "linux")] - linux: LinuxResourceMonitor::default(), - } - } -} - -impl SystemResourceSource { - /// Set mount filtering used when building each resource snapshot. - pub fn with_disk_options(mut self, options: DiskOptions) -> Self { - self.disk_options = options; - self - } - /// Keep the IO bar scaled to recent activity instead of only this sample. - pub(super) fn update_disk_peak(&mut self, read_rate: f64, write_rate: f64) -> f64 { - self.disk_peak_bytes_per_second = (self.disk_peak_bytes_per_second * 0.9) - .max(read_rate) - .max(write_rate) - .max(1.0); - self.disk_peak_bytes_per_second - } -} - -/// A counter delta as a rate over `elapsed` seconds. -/// -/// Before the first baseline there is no interval: the delta covers however -/// long start-up took, so it is reported as no rate rather than as a spike. -pub(super) fn per_second(delta: u64, elapsed: f64, baseline_ready: bool) -> f64 { - if baseline_ready { - delta as f64 / elapsed.max(0.001) - } else { - 0.0 - } -} - -impl ResourceSource for SystemResourceSource { - fn sample(&mut self) -> ResourceSnapshot { - let now = Instant::now(); - let elapsed = self - .last_sample - .map(|last| now.duration_since(last).as_secs_f64()) - .unwrap_or(0.0); - let baseline_ready = self.last_sample.replace(now).is_some(); - self.system.refresh_cpu_all(); - self.system.refresh_memory(); - let process_refresh = { - let refresh = ProcessRefreshKind::nothing(); - #[cfg(target_os = "linux")] - { - refresh - } - #[cfg(not(target_os = "linux"))] - { - refresh - .with_cpu() - .with_memory() - .with_disk_usage() - .with_exe(UpdateKind::OnlyIfNotSet) - .with_cmd(UpdateKind::OnlyIfNotSet) - .with_cwd(UpdateKind::OnlyIfNotSet) - } - }; - self.system - .refresh_processes_specifics(ProcessesToUpdate::All, true, process_refresh); - #[cfg(target_os = "linux")] - let process_metric_pids = { - let possible_agent_pids: Vec<_> = self - .system - .processes() - .iter() - .filter(|(_, process)| may_be_agent_process(&process.name().to_string_lossy())) - .map(|(pid, _)| *pid) - .collect(); - if !possible_agent_pids.is_empty() { - self.system.refresh_processes_specifics( - ProcessesToUpdate::Some(&possible_agent_pids), - true, - ProcessRefreshKind::nothing() - .with_exe(UpdateKind::OnlyIfNotSet) - .with_cmd(UpdateKind::OnlyIfNotSet) - .with_cwd(UpdateKind::OnlyIfNotSet), - ); - } - let agent_pids: Vec<_> = self - .system - .processes() - .iter() - .filter(|(_, process)| should_refresh_task_details(process.exe(), process.cmd())) - .map(|(pid, _)| *pid) - .collect(); - let agent_tree_roots: Vec<_> = self - .system - .processes() - .iter() - .filter(|(_, process)| should_refresh_process_tree(process.exe(), process.cmd())) - .map(|(pid, _)| *pid) - .collect(); - let mut process_metric_pids = pids_in_process_trees( - self.system - .processes() - .iter() - .map(|(pid, process)| (*pid, process.parent())), - agent_tree_roots, - ); - process_metric_pids.extend(agent_pids.iter().copied()); - if let Ok(current_pid) = sysinfo::get_current_pid() { - process_metric_pids.push(current_pid); - } - process_metric_pids.sort_unstable(); - process_metric_pids.dedup(); - if !process_metric_pids.is_empty() { - self.system.refresh_processes_specifics( - ProcessesToUpdate::Some(&process_metric_pids), - true, - ProcessRefreshKind::nothing() - .with_cpu() - .with_memory() - .with_disk_usage(), - ); - } - if !agent_pids.is_empty() { - self.system.refresh_processes_specifics( - ProcessesToUpdate::Some(&agent_pids), - true, - ProcessRefreshKind::nothing().with_tasks(), - ); - } - process_metric_pids - .into_iter() - .collect::>() - }; - #[cfg(not(target_os = "linux"))] - let process_metric_pids = self - .system - .processes() - .keys() - .copied() - .collect::>(); - self.disks.refresh(true); - self.networks.refresh(true); - let networks = self - .networks - .iter() - .map(|(name, data)| { - let ip_addresses: Vec<_> = - data.ip_networks().iter().map(ToString::to_string).collect(); - #[cfg(target_os = "linux")] - let (up, running) = linux_interface_flags(name) - .map(linux_interface_state) - .unwrap_or((false, false)); - // sysinfo does not expose interface flags on other platforms. - // An assigned address is evidence of a configured interface; - // observed traffic is evidence it is currently connected. - #[cfg(not(target_os = "linux"))] - let (up, running) = (!ip_addresses.is_empty(), false); - let received_bytes_per_second = - per_second(data.received(), elapsed, baseline_ready); - let transmitted_bytes_per_second = - per_second(data.transmitted(), elapsed, baseline_ready); - NetworkSnapshot { - interface: name.clone(), - up, - connected: running - || received_bytes_per_second > 0.0 - || transmitted_bytes_per_second > 0.0, - ip_addresses, - received_bytes_per_second, - transmitted_bytes_per_second, - total_received_bytes: data.total_received(), - total_transmitted_bytes: data.total_transmitted(), - } - }) - .collect::>(); - let mut networks = networks; - networks.sort_by(|left, right| left.interface.cmp(&right.interface)); - let task_pids: std::collections::HashSet = self - .system - .processes() - .values() - .filter_map(|process| process.tasks()) - .flatten() - .map(|pid| pid.as_u32()) - .collect(); - let processes: Vec = self - .system - .processes() - .iter() - .filter(|(pid, _)| !task_pids.contains(&pid.as_u32())) - .map(|(pid, process)| { - let has_metrics = process_metric_pids.contains(pid); - ProcessSnapshot { - pid: pid.as_u32(), - ppid: process.parent().map(|parent| parent.as_u32()), - exe: process - .exe() - .map(|path| path.to_string_lossy().into_owned()), - cmd: process - .cmd() - .iter() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect(), - cwd: process - .cwd() - .map(|path| path.to_string_lossy().into_owned()), - start_time: process.start_time(), - owner_uid: effective_user_id(process), - cpu_percent: if has_metrics { - f64::from(process.cpu_usage()) - } else { - 0.0 - }, - memory_bytes: if has_metrics { process.memory() } else { 0 }, - disk_read_bytes: if baseline_ready && has_metrics { - process.disk_usage().read_bytes - } else { - 0 - }, - disk_written_bytes: if baseline_ready && has_metrics { - process.disk_usage().written_bytes - } else { - 0 - }, - threads: process - .tasks() - .map(|tasks| tasks.len()) - .or_else(|| thread_count(pid.as_u32())) - .unwrap_or(0), - } - }) - .collect(); - let process_index = std::sync::Arc::new( - processes - .iter() - .enumerate() - .map(|(index, process)| (process.pid, index)) - .collect(), - ); - let mut children = std::collections::HashMap::>::new(); - for process in &processes { - if let Some(parent) = process.ppid { - children.entry(parent).or_default().push(process.pid); - } - } - let current_pid = sysinfo::get_current_pid().ok().map(|pid| pid.as_u32()); - let current_process = current_pid.and_then(|pid| { - let process = self - .system - .processes() - .iter() - .find(|(candidate, _)| candidate.as_u32() == pid) - .map(|(_, process)| process)?; - let cores = self.system.cpus().len().max(1) as f64; - let cpu_percent = f64::from(process.cpu_usage()); - let memory_bytes = process.memory(); - let total_memory_bytes = self.system.total_memory(); - let disk = process.disk_usage(); - let seconds = elapsed.max(0.001); - let read_rate = if baseline_ready { - disk.read_bytes as f64 / seconds - } else { - 0.0 - }; - let write_rate = if baseline_ready { - disk.written_bytes as f64 / seconds - } else { - 0.0 - }; - let disk_peak = self.update_disk_peak(read_rate, write_rate); - Some(crate::ui::resources::ResourceSnapshot { - cpu_fraction: (cpu_percent / (cores * 100.0)).clamp(0.0, 1.0), - memory_bytes, - total_memory_bytes, - disk_read_bytes_per_second: read_rate, - disk_write_bytes_per_second: write_rate, - disk_peak_bytes_per_second: disk_peak, - }) - }); - let mut cpu = self.cpu_monitor.sample(); - cpu.model = self - .system - .cpus() - .first() - .map(|cpu| cpu.brand().trim().to_owned()) - .filter(|brand| !brand.is_empty()); - if cpu.cores.is_empty() { - cpu.total.total = self.system.global_cpu_usage(); - cpu.cores = self - .system - .cpus() - .iter() - .map(|cpu| crate::ui::resources::CpuReading { - total: cpu.cpu_usage(), - ..Default::default() - }) - .collect(); - } - if cpu.frequencies_mhz.iter().all(Option::is_none) { - cpu.frequencies_mhz = self - .system - .cpus() - .iter() - .map(|cpu| Some(cpu.frequency())) - .collect(); - } - if cpu.load_average == [0.0; 3] { - let load = System::load_average(); - cpu.load_average = [load.one, load.five, load.fifteen]; - } - if cpu.uptime_seconds.is_none() { - cpu.uptime_seconds = Some(System::uptime()); - } - #[cfg(target_os = "linux")] - let linux = self.linux.sample(&self.disks, elapsed); - ResourceSnapshot { - cpu, - current_process, - history: Default::default(), - process_index, - children_index: std::sync::Arc::new(children), - sample_interval_seconds: elapsed, - cpu_percent: f64::from(self.system.global_cpu_usage()), - cpu_cores_percent: self - .system - .cpus() - .iter() - .map(|cpu| f64::from(cpu.cpu_usage())) - .collect(), - memory_total_bytes: { - #[cfg(target_os = "linux")] - { - linux.memory.total - } - #[cfg(not(target_os = "linux"))] - { - self.system.total_memory() - } - }, - memory_used_bytes: { - #[cfg(target_os = "linux")] - { - linux.memory.total.saturating_sub(linux.memory.available) - } - #[cfg(not(target_os = "linux"))] - { - self.system.used_memory() - } - }, - memory_available_bytes: { - #[cfg(target_os = "linux")] - { - linux.memory.available - } - #[cfg(not(target_os = "linux"))] - { - self.system.available_memory() - } - }, - memory_cached_bytes: { - #[cfg(target_os = "linux")] - { - linux.memory.cached - } - #[cfg(not(target_os = "linux"))] - { - 0 - } - }, - memory_free_bytes: { - #[cfg(target_os = "linux")] - { - linux.memory.free - } - #[cfg(not(target_os = "linux"))] - { - self.system.free_memory() - } - }, - swap_total_bytes: self.system.total_swap(), - swap_used_bytes: self.system.used_swap(), - disks: disk_snapshots( - &self.disks, - &self.disk_options, - #[cfg(not(target_os = "linux"))] - DiskRates { - elapsed, - baseline_ready, - }, - #[cfg(target_os = "linux")] - &linux.io, - ), - networks, - processes, - } - } - - fn update_disk_options(&mut self, options: DiskOptions) { - self.disk_options = options; - } -} - -/// Thread count where sysinfo has none to give: it lists a process's threads -/// only on Linux, so macOS asks the kernel for the task's own count. -#[cfg(target_os = "macos")] -fn thread_count(pid: u32) -> Option { - let mut info = std::mem::MaybeUninit::::zeroed(); - let size = std::mem::size_of::() as libc::c_int; - // SAFETY: `info` is a writable buffer of exactly `size` bytes, which is - // what PROC_PIDTASKINFO fills; a short return means it was not filled. - let written = unsafe { - libc::proc_pidinfo( - pid as libc::c_int, - libc::PROC_PIDTASKINFO, - 0, - info.as_mut_ptr().cast(), - size, - ) - }; - if written != size { - return None; - } - // SAFETY: the kernel wrote the whole struct, checked above. - let info = unsafe { info.assume_init() }; - usize::try_from(info.pti_threadnum).ok() -} - -#[cfg(not(target_os = "macos"))] -fn thread_count(_pid: u32) -> Option { - None -} - -pub(super) fn effective_user_id(process: &sysinfo::Process) -> Option { - #[cfg(unix)] - { - process.effective_user_id().map(|uid| (**uid).to_string()) - } - #[cfg(not(unix))] - { - let _ = process; - None - } -} diff --git a/src/tui/src/ui/resources/sampler/tests/filters.rs b/src/tui/src/ui/resources/sampler/tests/filters.rs deleted file mode 100644 index 81bd35bfc..000000000 --- a/src/tui/src/ui/resources/sampler/tests/filters.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! Which processes get detailed refreshes, which disks are listed, and the -//! Linux `/proc` and `/sys` readings. - -#[cfg(target_os = "linux")] -use super::*; - -#[cfg(target_os = "linux")] -#[test] -fn process_snapshots_skip_executable_and_command_for_unclassified_processes() { - let mut source = super::super::SystemResourceSource::default(); - let snapshot = source.sample(); - let pid = std::process::id(); - let process = snapshot - .processes - .iter() - .find(|process| process.pid == pid) - .unwrap_or_else(|| panic!("sampler omitted its own process {pid}")); - - assert!(process.exe.is_none()); - assert!(process.cmd.is_empty()); -} - -#[cfg(target_os = "linux")] -#[test] -fn process_snapshots_include_executable_and_command_for_agent_candidate_children() { - let mut child = std::process::Command::new("bash") - .args(["-c", "read -r line"]) - .stdin(std::process::Stdio::piped()) - .spawn() - .unwrap(); - let stdin = child.stdin.take(); - let pid = child.id(); - let snapshot = super::super::SystemResourceSource::default().sample(); - let process = snapshot - .processes - .iter() - .find(|process| process.pid == pid) - .cloned(); - let _ = child.kill(); - let _ = child.wait(); - - let process = process.unwrap_or_else(|| panic!("sampler omitted external fixture PID {pid}")); - assert!( - process.exe.as_deref().is_some_and(|exe| { - std::path::Path::new(exe) - .file_name() - .is_some_and(|name| name == "bash") - }), - "agent candidate snapshot must include its executable: {process:?}" - ); - assert!( - process - .cmd - .iter() - .any(|argument| argument == "read -r line"), - "agent candidate snapshot must include argv: {process:?}" - ); - drop(stdin); -} - -#[cfg(target_os = "linux")] -#[test] -fn thread_details_are_refreshed_only_for_agent_candidates() { - use std::ffi::OsString; - use std::path::Path; - - assert!(super::super::should_refresh_task_details( - Some(Path::new("/usr/local/bin/claude")), - &[OsString::from("claude")], - )); - assert!(super::super::should_refresh_task_details( - Some(Path::new("/usr/bin/node")), - &[ - OsString::from("node"), - OsString::from("/opt/@agentclientprotocol/claude-agent-acp"), - ], - )); - assert!(!super::super::should_refresh_task_details( - Some(Path::new("/usr/bin/sleep")), - &[OsString::from("sleep"), OsString::from("120")], - )); -} - -#[cfg(target_os = "linux")] -#[test] -fn process_details_are_refreshed_only_for_possible_agent_processes() { - assert!(super::super::may_be_agent_process("claude")); - assert!(super::super::may_be_agent_process("node")); - assert!(super::super::may_be_agent_process("bash")); - assert!(!super::super::may_be_agent_process("sleep")); - assert!(!super::super::may_be_agent_process("postgres")); -} - -#[cfg(target_os = "linux")] -#[test] -fn agent_metric_refresh_includes_descendants_without_refreshing_unrelated_trees() { - use std::collections::HashSet; - use sysinfo::Pid; - - let processes = [ - (Pid::from_u32(10), None), - (Pid::from_u32(11), Some(Pid::from_u32(10))), - (Pid::from_u32(12), Some(Pid::from_u32(11))), - (Pid::from_u32(20), None), - (Pid::from_u32(21), Some(Pid::from_u32(20))), - ]; - let refreshed = super::super::pids_in_process_trees(processes, [Pid::from_u32(10)]) - .into_iter() - .collect::>(); - - assert_eq!( - refreshed, - [Pid::from_u32(10), Pid::from_u32(11), Pid::from_u32(12)] - .into_iter() - .collect() - ); -} - -#[cfg(target_os = "linux")] -#[test] -fn shell_candidates_do_not_make_every_child_an_agent_metric() { - use std::ffi::OsString; - use std::path::Path; - - assert!(!super::super::should_refresh_process_tree( - Some(Path::new("/usr/bin/bash")), - &[ - OsString::from("bash"), - OsString::from("/app/tests_resources.sh") - ], - )); - assert!(super::super::should_refresh_process_tree( - Some(Path::new("/usr/local/bin/codex")), - &[OsString::from("codex")], - )); -} - -#[test] -fn device_disk_selection_prefers_the_deepest_mount_containing_cwd() { - let disks = [ - super::super::DiskSnapshot { - device: "sda1".into(), - mount: "/".into(), - total_bytes: 10_000, - used_bytes: 9_000, - read_bytes_per_second: 0.0, - write_bytes_per_second: 0.0, - busy_percent: None, - has_io: true, - }, - super::super::DiskSnapshot { - device: "sdb1".into(), - mount: "/mnt/data".into(), - total_bytes: 1_000, - used_bytes: 250, - read_bytes_per_second: 0.0, - write_bytes_per_second: 0.0, - busy_percent: None, - has_io: true, - }, - ]; - - let selected = - super::super::types::most_specific_mount(&disks, std::path::Path::new("/mnt/data/project")) - .unwrap(); - assert_eq!(selected.mount, "/mnt/data"); -} - -#[test] -fn disk_filters_exclude_mount_subtrees_and_virtual_filesystems() { - let options = super::super::DiskOptions { - filter: "exclude=/boot".into(), - ..Default::default() - }; - assert!(!super::super::mount_is_visible( - "/boot", - "/dev/sda1", - "ext4", - &options, - "" - )); - assert!(!super::super::mount_is_visible( - "/boot/efi", - "/dev/sda2", - "vfat", - &options, - "" - )); - assert!(super::super::mount_is_visible( - "/", - "/dev/sda3", - "ext4", - &options, - "" - )); - let physical = super::super::DiskOptions { - only_physical: true, - ..Default::default() - }; - assert!(!super::super::mount_is_visible( - "/run", "tmpfs", "tmpfs", &physical, "" - )); - assert!(!super::super::mount_is_visible( - "/app", "overlay", "overlay", &physical, "" - )); - assert!(super::super::mount_is_visible( - "/", - "/dev/sda3", - "ext4", - &physical, - "" - )); -} - -#[test] -fn fstab_mode_keeps_only_configured_mounts() { - let options = super::super::DiskOptions { - use_fstab: true, - ..Default::default() - }; - let fstab = "/dev/root / ext4 defaults 0 1\n/dev/data /mnt/data\\040drive ext4 defaults 0 2\n"; - assert!(super::super::mount_is_visible( - "/", - "/dev/root", - "ext4", - &options, - fstab - )); - assert!(super::super::mount_is_visible( - "/mnt/data drive", - "/dev/data", - "ext4", - &options, - fstab - )); - assert!(!super::super::mount_is_visible( - "/var", - "/dev/root", - "ext4", - &options, - fstab - )); -} - -#[cfg(target_os = "linux")] -#[test] -fn linux_meminfo_reports_available_and_cached_with_legacy_fallback() { - let memory = super::super::parse_memory("MemTotal: 1000 kB\nMemFree: 100 kB\nCached: 300 kB\nMemAvailable: 700 kB\nSwapTotal: 50 kB\n"); - assert_eq!( - (memory.total, memory.available, memory.cached), - (1_024_000, 716_800, 307_200) - ); - let fallback = - super::super::parse_memory("MemTotal: 1000 kB\nMemFree: 100 kB\nCached: 300 kB\n"); - assert_eq!(fallback.available, 409_600); -} - -#[cfg(target_os = "linux")] -#[test] -fn linux_block_stat_deltas_report_read_write_rates_and_busy_percent() { - let before = super::super::parse_block_stat("8 0 100 500 8 0 200 900 0 300 1400").unwrap(); - let after = super::super::parse_block_stat("8 0 110 700 8 0 220 1300 0 450 2000").unwrap(); - let reading = super::super::io_delta(before, after, 2.0); - assert_eq!(reading.read_rate, 2_560.0); - assert_eq!(reading.write_rate, 5_120.0); - assert_eq!(reading.busy, 7.5); - assert_eq!( - super::super::io_delta((0, 0, 0), (0, 0, 10_000), 1.0).busy, - 100.0 - ); -} - -#[cfg(target_os = "linux")] -#[test] -fn linux_partition_block_stats_are_read_from_class_block() { - let root = tempfile::tempdir().unwrap(); - let partition_stat = root.path().join("sys/class/block/nvme0n1p1/stat"); - std::fs::create_dir_all(partition_stat.parent().unwrap()).unwrap(); - std::fs::write(&partition_stat, "259 1 100 500 259 1 200 900 0 300 1400").unwrap(); - - assert_eq!( - super::super::read_block_stat(root.path(), "nvme0n1p1"), - Some((100, 200, 300)) - ); -} diff --git a/src/tui/src/ui/resources/sampler/tests/mod.rs b/src/tui/src/ui/resources/sampler/tests/mod.rs deleted file mode 100644 index a234eda3d..000000000 --- a/src/tui/src/ui/resources/sampler/tests/mod.rs +++ /dev/null @@ -1,392 +0,0 @@ -//! Unit tests for the resource sampler. - -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; -use std::time::Duration; - -use tokio::sync::{mpsc, watch}; - -use super::{ - spawn_sampler, spawn_sampler_with_disk_options, update_disk_options, update_interval, - DiskOptions, DiskSnapshot, History, ResourceSnapshot, ResourceSource, -}; - -#[derive(Clone)] -struct SequenceSource(Arc); - -impl ResourceSource for SequenceSource { - fn sample(&mut self) -> ResourceSnapshot { - ResourceSnapshot { - cpu_percent: self.0.fetch_add(1, Ordering::Relaxed) as f64, - ..Default::default() - } - } -} - -#[tokio::test] -async fn sampler_posts_injected_samples_in_order() { - let (interval_tx, interval_rx) = watch::channel(Some(Duration::from_millis(5))); - let (output_tx, mut output_rx) = mpsc::unbounded_channel(); - let task = spawn_sampler( - SequenceSource(Arc::new(AtomicUsize::new(0))), - interval_rx, - 2, - move |snapshot| output_tx.send(snapshot).is_ok(), - ); - let first = tokio::time::timeout(Duration::from_secs(1), output_rx.recv()) - .await - .unwrap() - .unwrap(); - let second = tokio::time::timeout(Duration::from_secs(1), output_rx.recv()) - .await - .unwrap() - .unwrap(); - assert_eq!(first.cpu_percent, 0.0); - assert_eq!(second.cpu_percent, 1.0); - assert_eq!( - second - .history - .cpu_percent - .iter() - .copied() - .collect::>(), - [0.0, 1.0] - ); - drop(interval_tx); - task.abort(); -} - -#[tokio::test(start_paused = true)] -async fn changed_interval_controls_the_next_sample_tick() { - let (interval_tx, interval_rx) = watch::channel(Some(Duration::from_secs(5))); - let (output_tx, mut output_rx) = mpsc::unbounded_channel(); - let task = spawn_sampler( - SequenceSource(Arc::new(AtomicUsize::new(0))), - interval_rx, - 2, - move |snapshot| output_tx.send(snapshot).is_ok(), - ); - - for _ in 0..5 { - tokio::task::yield_now().await; - } - tokio::time::advance(Duration::from_secs(4)).await; - for _ in 0..5 { - tokio::task::yield_now().await; - } - assert!(output_rx.try_recv().is_err()); - - interval_tx.send(Some(Duration::from_millis(20))).unwrap(); - for _ in 0..5 { - tokio::task::yield_now().await; - } - tokio::time::advance(Duration::from_millis(19)).await; - for _ in 0..5 { - tokio::task::yield_now().await; - } - assert!(output_rx.try_recv().is_err()); - tokio::time::advance(Duration::from_millis(1)).await; - for _ in 0..100 { - tokio::task::yield_now().await; - if output_rx.try_recv().is_ok() { - task.abort(); - return; - } - std::thread::sleep(Duration::from_millis(1)); - } - task.abort(); - panic!("updated resource interval did not produce a sample"); -} - -#[tokio::test(start_paused = true)] -async fn repeated_unchanged_interval_updates_do_not_starve_samples() { - let period = Duration::from_millis(20); - let (interval_tx, interval_rx) = watch::channel(Some(period)); - let (output_tx, mut output_rx) = mpsc::unbounded_channel(); - let task = spawn_sampler( - SequenceSource(Arc::new(AtomicUsize::new(0))), - interval_rx, - 2, - move |snapshot| output_tx.send(snapshot).is_ok(), - ); - for _ in 0..5 { - tokio::task::yield_now().await; - } - for _ in 0..5 { - assert!(!update_interval(&interval_tx, Some(period))); - tokio::task::yield_now().await; - } - tokio::time::advance(period).await; - for _ in 0..100 { - tokio::task::yield_now().await; - if output_rx.try_recv().is_ok() { - task.abort(); - return; - } - std::thread::sleep(Duration::from_millis(1)); - } - task.abort(); - panic!("unchanged interval updates starved the scheduled sample"); -} - -#[derive(Clone)] -struct DiskOptionsSource(Arc>); - -impl ResourceSource for DiskOptionsSource { - fn sample(&mut self) -> ResourceSnapshot { - let options = self.0.lock().unwrap().clone(); - let disks = [ - ("loop0", "/boot", false, false), - ("sda", "/", true, true), - ("sdb", "/boot", true, true), - ("sdc", "/data", true, false), - ] - .into_iter() - .filter(|(device, mount, physical, in_fstab)| { - (!options.only_physical || *physical) - && (!options.use_fstab || *in_fstab) - && !options - .filter - .split(',') - .filter_map(|filter| filter.strip_prefix("exclude=")) - .any(|excluded| excluded == *mount) - && (*device != "loop0" || !options.only_physical) - }) - .map(|(device, mount, _, _)| DiskSnapshot { - device: device.into(), - mount: mount.into(), - total_bytes: 0, - used_bytes: 0, - read_bytes_per_second: 0.0, - write_bytes_per_second: 0.0, - busy_percent: None, - has_io: true, - }) - .collect(); - ResourceSnapshot { - disks, - ..Default::default() - } - } - - fn update_disk_options(&mut self, options: DiskOptions) { - *self.0.lock().unwrap() = options; - } -} - -#[tokio::test] -async fn disk_options_change_samples_without_restarting_the_sampler() { - let initial = DiskOptions::default(); - let (options_tx, options_rx) = watch::channel(initial.clone()); - let (interval_tx, interval_rx) = watch::channel(Some(Duration::from_millis(5))); - let (output_tx, mut output_rx) = mpsc::unbounded_channel(); - let task = spawn_sampler_with_disk_options( - DiskOptionsSource(Arc::new(std::sync::Mutex::new(initial))), - interval_rx, - options_rx, - 2, - move |snapshot| output_tx.send(snapshot).is_ok(), - ); - - async fn sample_matching( - output_rx: &mut mpsc::UnboundedReceiver>, - matches: impl Fn(&ResourceSnapshot) -> bool, - ) -> Arc { - tokio::time::timeout(Duration::from_secs(1), async { - loop { - let snapshot = output_rx.recv().await.expect("sampler should stay alive"); - if matches(&snapshot) { - return snapshot; - } - } - }) - .await - .expect("sampler should publish a matching snapshot within one second") - } - - assert_eq!( - sample_matching(&mut output_rx, |snapshot| snapshot.disks.len() == 4) - .await - .disks - .len(), - 4 - ); - assert!(update_disk_options( - &options_tx, - DiskOptions { - only_physical: true, - ..Default::default() - } - )); - assert_eq!( - sample_matching(&mut output_rx, |snapshot| snapshot.disks.len() == 3) - .await - .disks - .len(), - 3 - ); - assert!(update_disk_options( - &options_tx, - DiskOptions { - only_physical: true, - use_fstab: true, - ..Default::default() - } - )); - assert_eq!( - sample_matching(&mut output_rx, |snapshot| snapshot.disks.len() == 2) - .await - .disks - .len(), - 2 - ); - assert!(update_disk_options( - &options_tx, - DiskOptions { - only_physical: true, - use_fstab: true, - filter: "exclude=/boot".into(), - } - )); - let final_sample = sample_matching(&mut output_rx, |snapshot| { - snapshot.disks.len() == 1 && snapshot.disks[0].mount == "/" - }) - .await; - assert_eq!(final_sample.disks.len(), 1); - assert_eq!(final_sample.disks[0].mount, "/"); - - drop(interval_tx); - task.abort(); -} - -#[test] -fn history_trims_to_requested_capacity_and_clones_cheaply() { - let mut history = History::new(3); - history.push(1, 2); - history.push(2, 2); - let clone = history.clone(); - history.push(3, 2); - assert_eq!(history.iter().copied().collect::>(), [2, 3]); - assert_eq!(clone.iter().copied().collect::>(), [1, 2]); - history.push(4, 0); - assert!(history.is_empty()); -} - -#[test] -fn resource_history_keeps_each_memory_series_for_graphs() { - let sample = ResourceSnapshot { - memory_used_bytes: 10, - memory_available_bytes: 20, - memory_cached_bytes: 30, - memory_free_bytes: 40, - swap_used_bytes: 50, - ..Default::default() - }; - let mut history = super::ResourceHistory::default(); - history.push(&sample, 8); - - assert_eq!( - history - .memory_used_bytes - .iter() - .copied() - .collect::>(), - [10] - ); - assert_eq!( - history - .memory_available_bytes - .iter() - .copied() - .collect::>(), - [20] - ); - assert_eq!( - history - .memory_cached_bytes - .iter() - .copied() - .collect::>(), - [30] - ); - assert_eq!( - history - .memory_free_bytes - .iter() - .copied() - .collect::>(), - [40] - ); - assert_eq!( - history.swap_used_bytes.iter().copied().collect::>(), - [50] - ); -} - -#[test] -fn process_io_peak_decays_instead_of_resetting_to_each_sample() { - let mut source = super::SystemResourceSource::default(); - assert_eq!(source.update_disk_peak(100.0, 0.0), 100.0); - assert_eq!(source.update_disk_peak(0.0, 0.0), 90.0); -} - -#[test] -fn the_first_sample_reports_no_rate_instead_of_a_startup_spike() { - // Bytes counted between start-up and the first sample have no interval - // to divide by; reporting them over the 1 ms floor made a gigabit spike - // that pinned the network scale and its Top reading. - assert_eq!(super::per_second(4_096, 0.0, false), 0.0); - assert_eq!(super::per_second(4_096, 2.0, true), 2_048.0); - assert_eq!(super::per_second(4_096, 0.0, true), 4_096_000.0); -} - -mod filters; - -/// The agents table reads a process's working directory and thread count from -/// the sample; on macOS neither used to be collected, so every row read `—` -/// and `0`. Linux reads both only for processes that may be agents, which the -/// test runner is not. -#[cfg(not(target_os = "linux"))] -#[test] -fn a_sample_carries_this_processs_working_directory_and_threads() { - let mut source = super::SystemResourceSource::default(); - let snapshot = source.sample(); - let me = snapshot - .processes - .iter() - .find(|process| process.pid == std::process::id()) - .expect("the sampler lists its own process"); - let cwd = std::env::current_dir().unwrap(); - assert_eq!( - me.cwd.as_deref().map(std::path::Path::new), - Some(cwd.as_path()), - "{me:?}" - ); - #[cfg(target_os = "macos")] - assert!(me.threads >= 1, "{me:?}"); -} - -#[cfg(target_os = "macos")] -#[test] -fn macos_volumes_resolve_to_the_disk_they_live_on() { - use super::macos::whole_disk; - assert_eq!(whole_disk("/dev/disk3s1s1"), Some("disk3")); - assert_eq!(whole_disk("/dev/disk12s2"), Some("disk12")); - assert_eq!(whole_disk("devfs"), None); - assert_eq!(whole_disk("map auto_home"), None); -} - -/// sysinfo lists only the volumes Finder browses; the mount table has every -/// local one, as btop shows, without the pseudo filesystems. -#[cfg(target_os = "macos")] -#[test] -fn macos_local_mounts_include_root_and_skip_pseudo_filesystems() { - let mounts = super::macos::local_mounts(); - assert!(mounts.iter().any(|mount| mount.mount == "/"), "no root"); - assert!(mounts - .iter() - .all(|mount| !["devfs", "autofs"].contains(&mount.filesystem.as_str()))); - assert!(mounts - .iter() - .all(|mount| mount.total_bytes > 0 || mount.mount != "/")); -} diff --git a/src/tui/src/ui/resources/sampler/types.rs b/src/tui/src/ui/resources/sampler/types.rs deleted file mode 100644 index 5cdb10c9c..000000000 --- a/src/tui/src/ui/resources/sampler/types.rs +++ /dev/null @@ -1,316 +0,0 @@ -//! Snapshot data returned by the background resource sampler. - -/// Point-in-time disk capacity reading. -#[derive(Debug, Clone, PartialEq)] -pub struct DiskSnapshot { - /// Device name when the platform exposes one. - pub device: String, - /// Mount point or volume name. - pub mount: String, - /// Total capacity in bytes. - pub total_bytes: u64, - /// Capacity in use in bytes. - pub used_bytes: u64, - /// Read throughput from the preceding sample, where supported. - pub read_bytes_per_second: f64, - /// Write throughput from the preceding sample, where supported. - pub write_bytes_per_second: f64, - /// Device busy percentage, unavailable on non-Linux collectors. - pub busy_percent: Option, - /// Whether the read and write rates were measured at all; swap, and a - /// volume on a disk with no IO counters, have none to graph. - pub has_io: bool, -} - -/// Point-in-time counters and addresses for one network interface. -#[derive(Debug, Clone, PartialEq)] -pub struct NetworkSnapshot { - /// Operating-system interface name. - pub interface: String, - /// Whether the interface is administratively up. - pub up: bool, - /// Whether the interface currently has carrier or observed traffic. - pub connected: bool, - /// Assigned IPv4 and IPv6 addresses. - pub ip_addresses: Vec, - /// Received bytes per second from the preceding sample. - pub received_bytes_per_second: f64, - /// Transmitted bytes per second from the preceding sample. - pub transmitted_bytes_per_second: f64, - /// Bytes received since the interface counter was initialized. - pub total_received_bytes: u64, - /// Bytes transmitted since the interface counter was initialized. - pub total_transmitted_bytes: u64, -} - -/// Point-in-time process reading. -#[derive(Debug, Clone, PartialEq)] -pub struct ProcessSnapshot { - /// Process identifier. - pub pid: u32, - /// Parent process identifier when available. - pub ppid: Option, - /// Executable path when available. - pub exe: Option, - /// Command line arguments. - pub cmd: Vec, - /// Current working directory when available. - pub cwd: Option, - /// Start time as seconds since Unix epoch. - pub start_time: u64, - /// Effective user id when the platform exposes it. - pub owner_uid: Option, - /// CPU utilization as a percentage. - pub cpu_percent: f64, - /// Resident memory in bytes. - pub memory_bytes: u64, - /// Bytes read since the previous system refresh. - pub disk_read_bytes: u64, - /// Bytes written since the previous system refresh. - pub disk_written_bytes: u64, - /// Number of threads/tasks reported for this process. - pub threads: usize, -} - -impl ProcessSnapshot { - /// The platform-neutral record the SDK's agent classifier reads. - pub fn to_record(&self) -> medulla::resources::agents::ProcessRecord { - medulla::resources::agents::ProcessRecord { - pid: self.pid, - ppid: self.ppid, - exe: self.exe.as_deref().map(std::path::PathBuf::from), - argv: Some(self.cmd.clone()), - cwd: self.cwd.as_deref().map(std::path::PathBuf::from), - started_at_secs: self.start_time, - usage: medulla::resources::agents::ProcessUsage { - cpu_percent: self.cpu_percent as f32, - rss_bytes: self.memory_bytes, - threads: self.threads as u64, - io: None, - }, - } - } -} - -/// Immutable whole-device readings suitable for sharing with renderers. -#[derive(Debug, Clone, Default)] -pub struct ResourceSnapshot { - /// Whole-machine CPU details and Linux-only hardware readings. - pub cpu: crate::ui::resources::CpuSnapshot, - /// Current process metrics used by the status line. - pub current_process: Option, - /// Recent readings accumulated by the sampler for graph rendering. - pub history: std::sync::Arc, - /// Seconds since the previous sample, used to scale process I/O deltas. - pub sample_interval_seconds: f64, - /// Total CPU utilization as a percentage. - pub cpu_percent: f64, - /// Utilization percentages for each logical CPU. - pub cpu_cores_percent: Vec, - /// Physical memory totals and readings, in bytes. - pub memory_total_bytes: u64, - /// Physical memory currently in use, in bytes. - pub memory_used_bytes: u64, - /// Physical memory available to applications, in bytes. - pub memory_available_bytes: u64, - /// Cached physical memory, in bytes. - pub memory_cached_bytes: u64, - /// Physical memory currently unused, in bytes. - pub memory_free_bytes: u64, - /// Total swap capacity, in bytes. - pub swap_total_bytes: u64, - /// Swap in use, in bytes. - pub swap_used_bytes: u64, - /// Mounted disk readings. - pub disks: Vec, - /// Per-interface traffic, state, and addresses. - pub networks: Vec, - /// Process table in the order sysinfo supplied it. - pub processes: Vec, - /// Lookup prepared off-thread for fast session rollups during rendering. - pub(crate) process_index: std::sync::Arc>, - /// Parent-to-child map prepared off-thread with the process table. - pub(crate) children_index: std::sync::Arc>>, -} - -impl ResourceSnapshot { - /// Attach whole-machine CPU readings to a snapshot. - pub fn with_cpu(mut self, cpu: crate::ui::resources::CpuSnapshot) -> Self { - self.cpu = cpu; - self - } - - /// Attach the history accumulated by a background sampler. - pub fn with_history(mut self, history: std::sync::Arc) -> Self { - self.history = history; - self - } - - /// Adapt whole-device readings for the existing compact footer. - pub fn device_snapshot(&self) -> crate::ui::resources::DeviceSnapshot { - let cwd = std::env::current_dir().ok(); - let disk = cwd - .as_deref() - .and_then(|cwd| most_specific_mount(&self.disks, cwd)); - crate::ui::resources::DeviceSnapshot { - cpu_fraction: Some((self.cpu_percent / 100.0).clamp(0.0, 1.0)), - memory_used_bytes: Some(self.memory_used_bytes), - memory_total_bytes: Some(self.memory_total_bytes), - disk_used_bytes: disk.map(|disk| disk.used_bytes), - disk_total_bytes: disk.map(|disk| disk.total_bytes), - } - } - - /// Return this snapshot with a process table and its render-time indexes. - /// - /// Resource sources can use this builder to publish process readings - /// without depending on the system sampler's implementation details. - pub fn with_processes(mut self, processes: Vec) -> Self { - let process_index = std::sync::Arc::new( - processes - .iter() - .enumerate() - .map(|(index, process)| (process.pid, index)) - .collect(), - ); - let mut children = std::collections::HashMap::>::new(); - for process in &processes { - if let Some(parent) = process.ppid { - children.entry(parent).or_default().push(process.pid); - } - } - self.processes = processes; - self.process_index = process_index; - self.children_index = std::sync::Arc::new(children); - self - } - - /// Aggregate the cached process table for a session, without touching the - /// host from the render path. - pub fn session_snapshot(&self, root_pid: u32) -> Option { - let root = self.processes.get(*self.process_index.get(&root_pid)?)?; - let core_count = self.cpu_cores_percent.len().max(1) as f64; - let mut result = crate::ui::resources::SessionSnapshot { - total_memory_bytes: self.memory_total_bytes, - ..Default::default() - }; - let mut pending = vec![root.pid]; - let mut visited = std::collections::HashSet::new(); - while let Some(pid) = pending.pop() { - if !visited.insert(pid) { - continue; - } - let Some(process) = self - .process_index - .get(&pid) - .and_then(|index| self.processes.get(*index)) - else { - continue; - }; - result.processes += 1; - result.cpu_fraction += process.cpu_percent / (core_count * 100.0); - result.memory_bytes = result.memory_bytes.saturating_add(process.memory_bytes); - result.disk_bytes_per_second += (process.disk_read_bytes + process.disk_written_bytes) - as f64 - / self.sample_interval_seconds.max(0.001); - if let Some(descendants) = self.children_index.get(&pid) { - pending.extend(descendants); - } - } - result.cpu_fraction = result.cpu_fraction.clamp(0.0, 1.0); - Some(result) - } -} - -/// Pick the deepest mount containing `cwd`; ties prefer the larger capacity. -pub(super) fn most_specific_mount<'a>( - disks: &'a [DiskSnapshot], - cwd: &std::path::Path, -) -> Option<&'a DiskSnapshot> { - disks - .iter() - .filter(|disk| cwd.starts_with(std::path::Path::new(&disk.mount))) - .max_by_key(|disk| { - ( - std::path::Path::new(&disk.mount).components().count(), - disk.total_bytes, - ) - }) -} - -/// Recent scalar series shared between the sampler and rendering views. -#[derive(Debug, Clone, Default)] -pub struct ResourceHistory { - /// Whole-device CPU utilization percentages. - pub cpu_percent: super::History, - /// CPU field readings over time. - pub cpu: super::History, - /// Physical memory currently used, in bytes. - pub memory_used_bytes: super::History, - /// Memory available to applications. - pub memory_available_bytes: super::History, - /// Cached memory. - pub memory_cached_bytes: super::History, - /// Unused physical memory, in bytes. - pub memory_free_bytes: super::History, - /// Swap currently used, in bytes. - pub swap_used_bytes: super::History, - /// Combined disk read throughput. - pub disk_read_bytes_per_second: super::History, - /// Combined disk write throughput. - pub disk_write_bytes_per_second: super::History, - /// Per-device read, write, and busy readings for graph rendering. - pub disk_io: super::History>, - /// Per-interface traffic series. - pub network_io: super::History>, - /// Number of visible processes. - pub process_count: super::History, -} - -impl ResourceHistory { - /// Append one snapshot and trim every series to the requested viewport size. - pub fn push(&mut self, snapshot: &ResourceSnapshot, capacity: usize) { - self.cpu_percent.push(snapshot.cpu_percent, capacity); - self.cpu.push(snapshot.cpu.clone(), capacity); - self.memory_used_bytes - .push(snapshot.memory_used_bytes, capacity); - self.memory_available_bytes - .push(snapshot.memory_available_bytes, capacity); - self.memory_cached_bytes - .push(snapshot.memory_cached_bytes, capacity); - self.memory_free_bytes - .push(snapshot.memory_free_bytes, capacity); - self.swap_used_bytes - .push(snapshot.swap_used_bytes, capacity); - self.disk_read_bytes_per_second.push( - snapshot - .disks - .iter() - .map(|disk| disk.read_bytes_per_second) - .sum(), - capacity, - ); - self.disk_write_bytes_per_second.push( - snapshot - .disks - .iter() - .map(|disk| disk.write_bytes_per_second) - .sum(), - capacity, - ); - self.disk_io.push(snapshot.disks.clone(), capacity); - self.network_io.push(snapshot.networks.clone(), capacity); - self.process_count.push(snapshot.processes.len(), capacity); - } -} - -/// Optional disk list filtering, configured by the TUI without coupling this crate to its config type. -#[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct DiskOptions { - /// Keep only disks backed by physical devices. - pub only_physical: bool, - /// Restrict the list to mounts declared in `/etc/fstab`. - pub use_fstab: bool, - /// Comma-separated mount filter; an empty string keeps every mount. - pub filter: String, -} diff --git a/src/tui/src/ui/theme/gradient.rs b/src/tui/src/ui/theme/gradient.rs deleted file mode 100644 index 6b128c024..000000000 --- a/src/tui/src/ui/theme/gradient.rs +++ /dev/null @@ -1,220 +0,0 @@ -//! Precomputed resource gradients and terminal color-depth conversion. - -use ratatui::style::Color; - -/// A linear, inclusive 101-entry gradient, indexed by percentages 0 through 100. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Gradient { - /// Color at 0 percent. - pub start: Color, - /// Optional midpoint at 50 percent. - pub mid: Option, - /// Optional endpoint at 100 percent. Without one the gradient is solid. - pub end: Option, - colors: [Color; 101], -} - -impl Gradient { - /// Construct a solid, two-color, or three-color gradient. - pub fn new(start: Color, mid: Option, end: Option) -> Self { - let colors = std::array::from_fn(|pct| { - let Some(end) = end else { return start }; - match mid { - Some(mid) if pct <= 50 => interpolate(start, mid, pct, 50), - Some(mid) => interpolate(mid, end, pct - 50, 50), - None => interpolate(start, end, pct, 100), - } - }); - Self { - start, - mid, - end, - colors, - } - } - - /// Look up a precomputed color. Values above 100 are clamped to the end. - pub fn at(&self, pct: usize) -> Color { - self.colors[pct.min(100)] - } - - /// Convert every control point and precomputed color to a terminal palette. - pub fn with_depth(self, depth: ColorDepth) -> Self { - let convert = |color| depth.convert(color); - Self { - start: convert(self.start), - mid: self.mid.map(convert), - end: self.end.map(convert), - colors: self.colors.map(convert), - } - } -} - -fn interpolate(a: Color, b: Color, step: usize, steps: usize) -> Color { - if step == 0 { - return a; - } - if step == steps { - return b; - } - let (ar, ag, ab) = rgb(a); - let (br, bg, bb) = rgb(b); - let channel = |from: u8, to: u8| { - (i32::from(from) + (step as i32 * (i32::from(to) - i32::from(from))) / steps as i32) as u8 - }; - Color::Rgb(channel(ar, br), channel(ag, bg), channel(ab, bb)) -} - -fn rgb(color: Color) -> (u8, u8, u8) { - match color { - Color::Rgb(r, g, b) => (r, g, b), - Color::Black => (0, 0, 0), - Color::Red => (205, 0, 0), - Color::Green => (0, 205, 0), - Color::Yellow => (205, 205, 0), - Color::Blue => (0, 0, 238), - Color::Magenta => (205, 0, 205), - Color::Cyan => (0, 205, 205), - Color::Gray => (229, 229, 229), - Color::DarkGray => (127, 127, 127), - Color::LightRed => (255, 0, 0), - Color::LightGreen => (0, 255, 0), - Color::LightYellow => (255, 255, 0), - Color::LightBlue => (92, 92, 255), - Color::LightMagenta => (255, 0, 255), - Color::LightCyan => (0, 255, 255), - Color::White => (255, 255, 255), - Color::Indexed(index @ 0..=15) => rgb(TTY_PALETTE[index as usize]), - Color::Indexed(index @ 16..=231) => { - const LEVELS: [u8; 6] = [0, 95, 135, 175, 215, 255]; - let index = index - 16; - ( - LEVELS[(index / 36) as usize], - LEVELS[((index / 6) % 6) as usize], - LEVELS[(index % 6) as usize], - ) - } - Color::Indexed(index) => { - let gray = 8 + 10 * (index.saturating_sub(232)); - (gray, gray, gray) - } - Color::Reset => (255, 255, 255), - } -} - -/// Terminal palette supported for resource colors. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ColorDepth { - /// 24-bit RGB. - TrueColor, - /// The xterm 256-color palette. - Color256, - /// The ANSI 16-color palette. - Color16, -} - -impl ColorDepth { - /// Detect common terminal capabilities from `COLORTERM` and `TERM`. - pub fn detect() -> Self { - Self::detect_from( - std::env::var("COLORTERM").ok().as_deref(), - std::env::var("TERM").ok().as_deref(), - ) - } - - /// Detect terminal capabilities from explicit environment values. - pub fn detect_from(colorterm: Option<&str>, term: Option<&str>) -> Self { - if colorterm.is_some_and(|value| { - matches!(value.to_ascii_lowercase().as_str(), "truecolor" | "24bit") - }) { - Self::TrueColor - } else if term.is_some_and(|value| value.to_ascii_lowercase().contains("256color")) { - Self::Color256 - } else { - Self::Color16 - } - } - - /// Map an RGB color to the selected terminal palette. - pub fn convert(self, color: Color) -> Color { - match (self, color) { - (Self::TrueColor, color) => color, - (Self::Color256, Color::Rgb(r, g, b)) => truecolor_to_256(Color::Rgb(r, g, b)), - (Self::Color16, Color::Rgb(r, g, b)) => truecolor_to_16(Color::Rgb(r, g, b)), - (_, color) => color, - } - } -} - -/// Convert RGB to btop's xterm 256-color cube or grayscale ramp. -pub fn truecolor_to_256(color: Color) -> Color { - let Color::Rgb(r, g, b) = color else { - return color; - }; - let gray = (f64::from(r) / 11.0).round() as u8; - if gray == (f64::from(g) / 11.0).round() as u8 && gray == (f64::from(b) / 11.0).round() as u8 { - Color::Indexed(232 + gray) - } else { - let cube = |channel: u8| (f64::from(channel) / 51.0).round() as u8; - Color::Indexed(16 + cube(r) * 36 + cube(g) * 6 + cube(b)) - } -} - -/// The conventional ANSI palette, with normal colors first and bright colors second. -pub const TTY_PALETTE: [Color; 16] = [ - Color::Rgb(0, 0, 0), - Color::Rgb(205, 0, 0), - Color::Rgb(0, 205, 0), - Color::Rgb(205, 205, 0), - Color::Rgb(0, 0, 238), - Color::Rgb(205, 0, 205), - Color::Rgb(0, 205, 205), - Color::Rgb(229, 229, 229), - Color::Rgb(127, 127, 127), - Color::Rgb(255, 0, 0), - Color::Rgb(0, 255, 0), - Color::Rgb(255, 255, 0), - Color::Rgb(92, 92, 255), - Color::Rgb(255, 0, 255), - Color::Rgb(0, 255, 255), - Color::Rgb(255, 255, 255), -]; - -/// Convert RGB to the nearest entry in the conventional 16-color TTY palette. -pub fn truecolor_to_16(color: Color) -> Color { - let Color::Rgb(r, g, b) = color else { - return color; - }; - let nearest = TTY_PALETTE - .iter() - .enumerate() - .min_by_key(|(_, candidate)| { - let Color::Rgb(cr, cg, cb) = candidate else { - unreachable!() - }; - let dr = i32::from(r) - i32::from(*cr); - let dg = i32::from(g) - i32::from(*cg); - let db = i32::from(b) - i32::from(*cb); - dr * dr + dg * dg + db * db - }) - .map(|(index, _)| index) - .unwrap_or(0); - [ - Color::Black, - Color::Red, - Color::Green, - Color::Yellow, - Color::Blue, - Color::Magenta, - Color::Cyan, - Color::Gray, - Color::DarkGray, - Color::LightRed, - Color::LightGreen, - Color::LightYellow, - Color::LightBlue, - Color::LightMagenta, - Color::LightCyan, - Color::White, - ][nearest] -} diff --git a/src/tui/tests/feature_resources_tab.rs b/src/tui/tests/feature_resources_tab.rs deleted file mode 100644 index 122c82936..000000000 --- a/src/tui/tests/feature_resources_tab.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! End-to-end behavior of the Resources tab. - -use std::sync::Arc; - -use medulla::backend::MockBackend; -use medulla::config::LoadedConfig; -use medulla_tui::ui::resources::sampler::{ProcessSnapshot, ResourceSnapshot}; -use medulla_tui::ui::{ - app::{App, TABS}, - resources::sampler, -}; -use ratatui::{backend::TestBackend, Terminal}; - -fn process(pid: u32, command: &str, cpu: f64) -> ProcessSnapshot { - ProcessSnapshot { - pid, - ppid: None, - exe: Some(command.into()), - cmd: vec![command.into()], - cwd: Some(format!("/workspace/{command}")), - start_time: 1, - owner_uid: None, - cpu_percent: cpu, - memory_bytes: 2 * 1024 * 1024, - disk_read_bytes: 0, - disk_written_bytes: 0, - threads: 4, - } -} - -#[test] -fn resources_agents_pane_renders_at_common_terminal_sizes() { - for (width, height) in [(170, 42), (80, 24)] { - let mut app = App::new( - Arc::new(MockBackend::new()), - LoadedConfig::defaults("test.json".into()), - ); - app.tab_index = TABS.iter().position(|tab| *tab == "Resources").unwrap(); - app.set_resource_snapshot(Arc::new(ResourceSnapshot::default().with_processes(vec![ - process(101, "claude", 10.0), - process(102, "codex-acp", 20.0), - process(103, "openhuman", 30.0), - process(104, "aider", 40.0), - ]))); - let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap(); - terminal.draw(|frame| app.draw(frame)).unwrap(); - let screen = terminal - .backend() - .buffer() - .content() - .iter() - .map(|cell| cell.symbol()) - .collect::(); - for label in ["Claude", "Codex-ACP", "OpenHuman", "Aider"] { - assert!( - screen.contains(label), - "{label} missing at {width}x{height}: {screen}" - ); - } - } -} - -#[test] -fn process_snapshot_builder_keeps_the_test_injection_path() { - let snapshot = - sampler::ResourceSnapshot::default().with_processes(vec![process(1, "claude", 5.0)]); - assert_eq!(snapshot.processes.len(), 1); - assert_eq!(snapshot.processes[0].pid, 1); -} From cdd91e2430cc24f98b23e14c62a9998dfea9d2da Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:00:29 +0000 Subject: [PATCH 27/60] chore(docs): remove implemented resources tab plan and screenshot The resources tab plan and its overview screenshot have been deleted now that the feature has shipped, and the corresponding module no longer needs the leftover code. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- docs/plans/resources-tab.md | 177 ------------------------ docs/screenshots/resources-overview.svg | 13 -- src/tui/src/ui/resources/mod.rs | 4 - 3 files changed, 194 deletions(-) delete mode 100644 docs/plans/resources-tab.md delete mode 100644 docs/screenshots/resources-overview.svg diff --git a/docs/plans/resources-tab.md b/docs/plans/resources-tab.md deleted file mode 100644 index 329ac8709..000000000 --- a/docs/plans/resources-tab.md +++ /dev/null @@ -1,177 +0,0 @@ -# Plan: Resources tab with a btop-style Agents pane - -> **Status: Implemented.** The UI and shared sampler landed (UI, shared sampler, Windows test follow-up). The user -> guide is [Resources](../../gitbooks/features/resources.md). - -## Problem - -Medulla has resource snippets in the Sessions view, but no host-wide history, no dedicated overview of CPU/memory/network activity, and no inventory of the coding-agent processes running on a host. The Resources tab will bring those views together: familiar btop-shaped resource boxes, with an Agents pane that classifies Medulla sessions and externally started coding agents. The tab must remain honest about platform data gaps and must not block drawing while it samples processes. - -This is a design contract for issues the Resources epic issues, not a claim that every field is available on every OS. `ship` means implement in this epic when the listed source can provide it; `later` means retain a clean model/UI seam but do not fake a value; `never` means intentionally out of product scope. - -## What was verified before writing this - -Code facts were checked at Medulla commit [`080bb3745e4cc0a4fe9a9d14967e2164cdf4e47c`](https://github.com/tinyhumansai/medulla/commit/080bb3745e4cc0a4fe9a9d14967e2164cdf4e47c): - -- `src/tui/src/ui/app/types/model.rs:71-86` has separate full/slim `TABS`; Resources must be added to both. `src/tui/src/ui/app/render/mod.rs:247-293,334-349` owns shortcut hints and tab rendering. `src/tui/src/ui/app/state.rs:576-610` owns tab-entry commands. -- `src/tui/src/ui/app/keys/mod.rs:155-335` dispatches Ctrl-C/O/Y/X/N/T globally before page handlers; Tab/BackTab are global; bare arrows are claimed by Sessions only; PageUp/PageDown have Sessions-only behavior. No global plain `r`, `e`, `f`, `/`, `t`, `k`, `s`, `p`, `1`–`4`, `+`, or `-` binding exists there. An attached harness owns every key (`render/mod.rs:252-267`). -- `src/sdk/src/protocol/frames/types.rs:87-118` defines Claude, Codex, OpenCode, in-process OpenHuman and shell provider kinds. `src/sdk/src/protocol/env.rs:193-204` gives `openhuman-core` and `sh` as their default binaries. `src/sdk/src/daemon/providers/acp/execution.rs:461-490` constructs Claude via `npx -y @agentclientprotocol/claude-agent-acp@latest`, Codex via `npx -y @agentclientprotocol/codex-acp@latest`, and OpenCode via its configured binary plus `acp`; OpenHuman is not an ACP child. -- The existing session sampler is draw-triggered, rate-limited to `REFRESH_INTERVAL`, refreshes memory/process CPU/memory/disk usage, and explicitly skips Linux tasks/threads (`src/tui/src/ui/resources/session/monitor.rs:42-77`). The existing dependency is `sysinfo 0.37.2` with `disk,system` features (`Cargo.toml:87`). -- `RemoteMessage::Sessions` is documented as a latest-wins whole-list update because it changes rarely and is small (`src/sdk/src/protocol/remote/types.rs:208-216`). `RemoteSessionRow` currently carries session identity and state but no process usage (`:53-110`); capabilities are exchanged once in `RemoteCapabilities` (`:133-171`). -- Theme config uses optional camelCase values and defaults missing fields (`src/sdk/src/config/types/presentation.rs:5-38`). Host resource reporting already has a small `HostResources` model (`src/sdk/src/runtime/fleet/mod.rs:62-81`). -- The open issue `tinyhumansai/medulla-src#320` proposes a typed action registry and key overrides, but it is not landed in this checkout; there is no registry API to target yet. - -The btop reference is upstream [`aristocratos/btop` commit `89fcdf4094e89f8ac215ee6c3ee74aeffb618e86`](https://github.com/aristocratos/btop/commit/89fcdf4094e89f8ac215ee6c3ee74aeffb618e86). Its [`calcSizes`](https://github.com/aristocratos/btop/blob/89fcdf4094e89f8ac215ee6c3ee74aeffb618e86/src/btop_draw.cpp#L2217-L2410) supplies the layout reference; its [default config](https://github.com/aristocratos/btop/blob/89fcdf4094e89f8ac215ee6c3ee74aeffb618e86/src/btop_config.cpp) documents preset syntax and defaults. The following adapts the layout and interactions, not btop's process-list purpose or platform-specific collector implementation. - -## Design - -### 1. Parity decisions - -A cell names whether the implementation ships, is deferred, or is excluded on that OS. All values unavailable from a collector are rendered as unavailable/omitted; never substitute zero. GPU is later on every platform. - -| Box | Element | Linux | macOS | Windows | -|---|---|---|---|---| -| CPU | Upper and lower graphs of total CPU usage | ship | ship | ship | -| CPU | Selectable upper/lower fields: total, user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice | ship (`/proc/stat` deltas) | later (sysinfo does not expose this field breakdown) | later (sysinfo does not expose this field breakdown) | -| CPU | Per-core usage rows/mini-graphs | ship (sysinfo) | ship (sysinfo) | ship (sysinfo) | -| CPU | Frequency and CPU brand | ship (sysinfo; Linux frequency where reported) | ship (sysinfo where reported; otherwise omit frequency) | ship (sysinfo where reported; otherwise omit frequency) | -| CPU | Package temperature | ship (hwmon labels and sensors) | later (no verified portable mapping in this spec) | later (no verified portable mapping in this spec) | -| CPU | Per-core temperatures | ship (hwmon label/core mapping; omit unmapped sensors) | later (no verified portable mapping) | later (no verified portable mapping) | -| CPU | Load average | ship (sysinfo) | ship (sysinfo) | later (no portable load-average API verified here) | -| CPU | Uptime | ship (sysinfo) | ship (sysinfo) | ship (sysinfo) | -| CPU | Battery | never (not a host-CPU field; excluded from this tab) | never | never | -| Mem | RAM used / available / cached / free | ship (used, available, free from sysinfo; cached Linux-only) | ship (used, available, free; cached omitted) | ship (used, available, free; cached omitted) | -| Mem | Swap used / available / free | ship (sysinfo) | ship (sysinfo) | ship (sysinfo) | -| Mem | Mounted disks: used / free / total | ship (sysinfo disk list) | ship (sysinfo disk list) | ship (sysinfo disk list) | -| Mem | Per-disk read/write throughput and activity | ship (sysinfo deltas; `/proc/diskstats` if needed) | later (source and semantics need verification) | later (source and semantics need verification) | -| Mem | IO display mode (combined or split read/write) | ship | ship when disk IO ships | ship when disk IO ships | -| Net | Per-interface download/upload rate graphs | ship (sysinfo network deltas) | ship (sysinfo network deltas) | ship (sysinfo network deltas) | -| Net | Autoscale, zero offset, synchronized scales | ship (pure btop-style scaler) | ship | ship | -| Net | Cumulative download/upload totals | ship (sysinfo counters) | ship | ship | -| Net | Interface selection and up/down state | ship (sysinfo interface list; hide unusable interfaces) | ship (same) | ship (same) | -| Net | Interface IP address | ship when sysinfo exposes it; otherwise omit | ship when sysinfo exposes it; otherwise omit | ship when sysinfo exposes it; otherwise omit | -| Agents | Classified process tree, usage and history | ship | ship where OS exposes process metadata; unknown argv stays unclassified | ship where OS exposes process metadata; unknown argv stays unclassified | -| GPU | GPU box/telemetry | later | later | later | - -`ship` in the CPU frequency row means display the reported frequency when present, not promise all machines expose it. Linux CPU field breakdown and hwmon temperatures are Linux-specific implementation paths. A platform gap never makes a row disappear if other supported fields are available. - -### 2. Layout, resize and presets - -Use terminal content area (excluding tab chrome) for percentages, round each percentage up, then clamp against available rects. Reference shares follow btop `calcSizes`: CPU is full width and 32% high (minimum 60×8); with all boxes visible, Mem is 45% wide and 40% high, Net 45% wide and 28% high, Agents 55% wide and 68% high (minimum 44×16). The complementary width belongs to Agents. `cpuBottom`, `memBelowNet`, and `agentsLeft` change only placement. If Agents is hidden, Mem and Net use full width; if only CPU is shown, CPU uses full content height. Keep the requested shares, but give rounding remainder to the right/bottom pane so there are no gaps. - -A shown box below its own minimum is not partially drawn: show a centered `Terminal too small for Resources` message with the current required minimum. When the combined arrangement does not fit, preserve CPU first, then Agents, then Mem/Net; suppress lower-priority boxes as whole panels and include their toggles in the hint. At a terminal smaller than CPU's 60×8 minimum, show only the message. Never panic or create negative rects. Resizing recomputes all rects and retains box visibility, sort/filter, and selected row by stable identity. - -Presets use btop's string shape: whitespace separates presets; commas separate entries; each entry is `::`. Medulla box names are `cpu`, `mem`, `net`, `agents`; position is `0` or `1`; graph is `default`, `braille`, `block`, or `tty`. Example: `cpu:0:default,mem:0:default,net:0:default,agents:1:braille cpu:0:block,agents:0:tty`. Preset 0 is always the default all-box layout; up to 9 user presets follow. Reject unknown boxes, position outside 0/1, graph symbols outside the enum, duplicate box names, or empty presets; keep last valid config on parse failure. - -### 3. Agents pane: identity, rows and actions - -`AgentKind` is `Claude`, `Codex`, `CodexAppServer`, `ClaudeAcp`, `CodexAcp`, `Opencode`, `OpenhumanCore`, `EmbeddedOpenhuman`, or `Shell`. Match only exact executable basenames and conservative argv signatures: - -| Kind | Verified match signature | -|---|---| -| Claude | exe basename `claude` | -| Codex | exe basename `codex`, unless argv has the app-server signature | -| CodexAppServer | exe basename `codex` and argv tokens `app-server` | -| ClaudeAcp | argv contains `@agentclientprotocol/claude-agent-acp` or `claude-agent-acp`; allow `npx` wrapper as ancestor | -| CodexAcp | argv contains `@agentclientprotocol/codex-acp` or `codex-acp`; allow `npx` wrapper as ancestor | -| Opencode | exe basename `opencode` | -| OpenhumanCore | exe basename `openhuman-core` | -| EmbeddedOpenhuman | SDK registry says an OpenHuman turn is executing in-process; never infer it from the medulla process name | -| Shell | exe basename is a recognized shell (`sh`, `bash`, `zsh`, `fish`, `pwsh`, `powershell`) and it is a known Medulla session or an explicitly shown external shell | - -For `env` wrappers and other launchers, walk descendants and classify the deepest verified harness process; collapse the wrapper chain into that row. Do not classify a generic `node` from its executable alone. Preserve raw `exe`/argv for classification only; display a bounded, redacted command line (strip environment assignments and known secret-bearing arguments). If argv is unreadable, report `Unknown` / `external` with unavailable command, never guess a kind. - -Origins are `Session{id}`, `Task{id}`, `Headless`, `Remote{host}`, `External`. Attribution uses registered `(pid, startTime)` roots first, then known PTY session roots with the same start-time guard; a mismatched start time is PID reuse and must not attribute. The nearest matching owned root wins. Collapse each launcher subtree to one agent row; show descendant processes as children only in tree mode, and exclude Medulla itself and its non-agent tool children from External. A direct child belonging to EmbeddedOpenhuman is nested under one synthetic EmbeddedOpenhuman row. De-duplicate remote processes against local ids only within their host namespace. - -Columns are `Pid · Agent (kind) · Origin · Workspace · Threads · Mem · Cpu% · CPU history · Runtime`. On narrow terminals, remove Workspace then Threads then history label (keep the graph); never remove kind/origin. Sort keys are pid, kind/program, origin, workspace, threads, memory, CPU, runtime. Initial sort is CPU descending, stable tie-break by pid then start time. Left/Right cycles sort keys; `r` reverses. `e` toggles tree; `f` opens a literal substring filter; `/` opens a regex filter, with leading `!` negating either filter. Invalid regex leaves the previous filter active and shows an error. Up/Down and PgUp/PgDn move selection; Home/End jump. Preserve selection by `(host,pid,startTime)` across samples. - -Enter on a row attributed to a local/remote Medulla Session focuses that session on Sessions tab; Enter on an external/headless/task/embedded row opens the Agents detail view. `F` follows its owning session when one exists; otherwise show a disabled-action status. `t`, `k`, `s` request SIGTERM, SIGKILL, or SIGSTOP/SIGCONT on supported Unix systems. Every signal opens a confirmation showing kind, PID, command, origin, signal, and target host. External targets require a second explicit confirmation. Never signal a process not owned by the current user; never signal remote processes in this epic; Windows signal actions are disabled. Cancel is the default. This explicit policy avoids a TUI keypress killing an unrelated or remotely owned process. - -### 4. Remote reporting and grouping - -Each remote daemon adds an optional, additive `usage` to each `RemoteSessionRow`: classified kind, remote PID, CPU%, RSS, thread count, start time, and at most 32 CPU history samples. This reports per-session process usage only; do not send host-wide totals or external process inventory. The client groups rows under a non-selectable host heading and labels their origin `Remote{host}`. Older clients ignore the extra serde field; newer clients treat missing usage as unavailable. Do not put argv, environment, command text, or workspace paths beyond the session's existing `cwd` on the wire. - -Send on the existing latest-wins Sessions update, no faster than `updateMs` (default 2000 ms), and only when a row or its usage sample changes. Include usage fields only for sessions with a classified process; cap serialized usage to 1 KiB per session and 16 KiB total per host update, dropping oldest history points first. Do not advertise a new `RemoteCapabilities` flag: the optional field is additive and clients can render its absence. Before implementation, measure actual serialized worst-case lists and host-link datagram fragmentation; if the existing message can exceed the link channel budget, split telemetry into a separate latest-wins channel rather than fragment a datagram. - -### 5. Keys and conflict check - -Bindings are scoped to the Resources tab and are checked against `src/tui/src/ui/app/keys/mod.rs` at the verified commit above. Global Ctrl-C/O/Y/X/N/T and Tab/BackTab retain precedence. No Resources action binds those chords. Sessions-only arrows and page-scroll keys do not conflict off that tab. A Resources handler runs before generic selection handling; it must never capture keys while an interactive harness has focus. - -| Key | Resources action | Conflict result | -|---|---|---| -| `1`–`4` | Toggle CPU, Mem, Net, Agents | Free in global dispatcher; settings numeric navigation is tab-scoped | -| `p` / `P` | Previous / next preset | Free globally; Agents filter captures only while its editor is open | -| `+` / `-` | Increase / decrease update interval by 100 ms | Free globally; clamp 100–10000 ms | -| `←` / `→` | Cycle Agents sort key when Agents list focused | No global binding; use component focus so layout/preset border actions do not steal it | -| `r` | Reverse sort | Free globally; Resources-only | -| `e` | Toggle process tree | Free globally; Sessions rail's Enter behavior is distinct | -| `f` / `/` | Open literal / regex filter editor | Free globally; `/` is literal except this explicit editor action | -| `↑` / `↓`, `PgUp` / `PgDn`, `Home` / `End` | Select Agents row | Global generic movement is only fallback; Resources handler consumes on its focused list | -| `Enter` | Focus owning session or open agent detail | Existing tab entry only changes tabs; selection is page-owned | -| `F` | Follow attributed session | Free globally; uppercase required | -| `t` / `k` / `s` | Confirmed terminate / kill / stop-continue | Free globally in keys/mod.rs; no signal before confirmation | -| `Esc` | Close detail/filter/confirmation, then return to tab | Page-local overlay precedence; never exits app | -| `Tab` / `BackTab` | Change top-level tab | Reserved global; Resources does not intercept | -| `Ctrl-C/O/Y/X/N/T` | Existing global actions | Reserved; never reused | - -Issue medulla-src#320 has not landed at this checkout, so no stable action IDs or registry API can be named yet. When it lands, register each binding with Resources-page scope and its current default; retain registry collision validation as authoritative. If registry scope cannot express focus/overlay precedence, defer configurable overrides for this tab until it can; do not invent a conflicting parallel key system. - -### 6. Configuration and theme - -Add optional `[resources]` with camelCase serde keys. Missing section/keys use these defaults; unknown keys retain normal config behavior. - -| Key | Type | Default | -|---|---|---| -| `updateMs` | integer, clamp 100–10000 | `2000` | -| `shownBoxes` | string | `"cpu,mem,net,agents"` | -| `presets` | string | `"cpu:0:default,mem:0:default,net:0:default,agents:1:default"` | -| `cpuBottom` | bool | `false` | -| `memBelowNet` | bool | `false` | -| `agentsLeft` | bool | `false` | -| `cpuGraphUpper` / `cpuGraphLower` | enum field selector | `"total"` / `"total"` | -| `cpuInvertLower` / `cpuSingleGraph` | bool | `true` / `false` | -| `tempScale` | `"celsius"` / `"fahrenheit"` | `"celsius"` | -| `freqMode` | `"current"` / `"average"` / `"max"` | `"current"` | -| `showBattery` | bool (ignored; field is never) | `false` | -| `memDisks` / `memIo` / `memIoMode` | bool / bool / `"combined"` or `"split"` | `true` / `false` / `"combined"` | -| `netAuto` / `netSync` | bool | `true` / `false` | -| `netDownload` / `netUpload` | bool | `true` / `true` | -| `netIface` | string (`"auto"` or interface name) | `"auto"` | -| `swapUploadDownload` | bool | `false` | -| `agentsTree` | bool | `false` | -| `agentsSort` / `agentsReverse` | enum / bool | `"cpu"` / `true` | -| `agentsShowExternal` | bool | `true` | - -The theme extension is `[theme.resources]`, also camelCase, and every color accepts the existing theme syntax (`#rrggbb` or named ratatui color). Box colors: `cpuBox=#556d59`, `memBox=#6c6c4b`, `netBox=#5c588d`, `agentsBox=#805252`, `divLine`, `meterBg`, `graphText`, `inactiveFg`. Each gradient has `Start`, optional `Mid`, `End`: `cpu`, `temp`, `used`, `free`, `cached`, `available`, `download`, `upload`, `process`. Default CPU gradient stops are `#77ca9b`, `#cbc06c`, `#dc4c4c`; remaining stop colors port btop's pinned default theme and are listed in issue #4's implementation tests. Empty mid means interpolate start-to-end; empty end means solid start. Precompute 101 colors. Respect terminal color depth: truecolor, nearest 256-color cube/gray, then nearest 16-color palette; color depth affects rendering only, never config values. - -### 7. Sampler budget and ownership - -One background sampler owns one `sysinfo::System`; it sends immutable `Arc` values to the event loop at the configured interval. Rendering reads snapshots/history only. Do not create or refresh `sysinfo::System` inside any render module. Build the process parent index once per sample (O(processes + edges)), classify in that pass, and reuse it for session aggregates and Agents rows. Keep history capacity to `maxGraphWidth * 2`, cap retained per-process histories to currently visible agent rows plus a short LRU, and avoid per-process filesystem probes. - -Budget at 2000 ms with 1000 processes: sampler CPU time p95 ≤40 ms per tick and ≤2% of one core averaged over a minute; sampler allocation ≤2 MiB per tick excluding sysinfo-owned buffers; event-loop message delivery and snapshot install ≤5 ms p95. Measure CPU time separately from wall time on a documented Linux fixture and one macOS/Windows smoke host. If over budget, reduce refreshed fields or split platform-specific collectors; never move the walk to drawing. Pause deep process detail work when neither Resources nor a process-usage footer is visible, while keeping any demanded footer cadence. - -### 8. Follow-on research decisions - -These answer every `Research first` prompt in the Resources epic issues; deferred items stay explicit so implementers do not turn an unknown into a compatibility claim. - -| Issue | Decision / evidence | -|---|---| -| #2 sampler | `run_cmd`/`AppMsg` event-loop seams exist (see `event_loop/mod.rs`, anchors in the issue); sampler posts one immutable snapshot message and owns sysinfo off draw path. Keep locked sysinfo 0.37.2 for this epic; no need to accept 0.39 churn to add network/component features. Exact 0.37→0.39 field/API changes, thread/task behavior and `MINIMUM_CPU_UPDATE_INTERVAL` are deferred to the collector implementer, who must check locked crate docs/source before choosing refresh flags. | -| #3 plot | Use btop's paired-sample graph lookup and ship braille/block/tty; default `braille` for parity, with `block`/`tty` user choice. Subconscious's dropped braille comment is a font/terminal concern, not evidence that braille rendering works in every terminal; add a focused width test against ratatui's buffer before enabling it by default. `plot` remains separate from `ui/app/render/graph`. | -| #4 theme | Port gradient behavior and default stops from pinned btop source/theme. The current theme parser has no `COLORTERM` detection (verified by `rg COLORTERM src/tui` returning no matches); implement terminal color-depth selection in the theme layer and test the 16/256/truecolor mappings rather than assume the terminal setting. | -| #5 layout | Port box proportions/minimums above, not incidental btop pixel math. `workflows` is currently a submodule under `ui/app` and provides a state organization precedent; exact files evolve with the tab implementation. | -| #6 CPU | Linux `/proc/stat`, `scaling_cur_freq`, hwmon labels and core mapping are specified for ship. `sysinfo` is the generic source for per-core/load/frequency/uptime; macOS/Windows sensor labels and core mapping are not verified, so temperature detail is later there. Do not promise common sensor names. | -| #7 memory | Linux disk IO can use sysinfo deltas, cross-checked with `/proc/diskstats`; ZFS remains out of scope. Verify `Disk::usage()` as cumulative counters vs delta against the locked crate source before calculating rates. macOS/Windows disk IO source is deferred. | -| #8 network | Use received/transmitted counter differences; rate is delta divided by elapsed sample time. The `NetScaler` follows the described btop thresholds (five over-limit samples, five below one tenth, 10 KiB floor, 1.3/3 multipliers). Interface addresses/state are displayed only when the locked sysinfo API reports them; collector must verify `NetworkData::ip_networks` per platform. | -| #9 process discovery | Matching signatures above follow checked Medulla launch command construction, not a claim that every installed CLI has a fixed process tree. Running all third-party harnesses under `ps --forest` is deferred because those executables/accounts are not guaranteed in this checkout; implementation must capture available launch fixtures and never broaden a match based on generic `node`. On macOS unreadable argv means Unknown/external with no command, not a guessed classification. | -| #10 registry | ACP code constructs `AcpAgentConfig` and passes it into `AcpAgent::new`; it does not expose a child PID at the Medulla call site. Whether ACP 2.x exposes a caller-spawn seam and whether every other spawn API yields PID must be checked against the locked crate/API at implementation time. Until then, do not claim registered attribution; fall back to verified PTY roots and label unowned rows external. | -| #11 pane | `btop_draw.cpp` Proc and `btop_input.cpp` define reference interactions; this spec lists the intended reduced columns/actions and signal safety. Sessions rail APIs can be reused after verifying selection-by-session support. The #320 scroll helpers are unavailable because that issue has not landed; implement local bounded selection scrolling. | -| #12 remote | Sessions is a whole-list, latest-wins message that changes rarely (`remote/types.rs:208-216`). Send optional bounded usage on that stream at no faster than `updateMs`. Do not advertise capability because the field is additive. Exact worst-case encoded payload measurement is deferred to the protocol change; the 16 KiB limit and separate-channel fallback are requirements, not asserted current link guarantees. | - -## Delivery order - -1. Land this decision document before implementation issues #6–#12. -2. Build shared sampler/config and plot/theme foundations (#2–#4). -3. Add Resources shell/layout/presets (#5). -4. Add CPU, memory and network panels (#6–#8) and process classification/registry (#9–#10). -5. Add Agents pane and additive remote usage (#11–#12); validate key behavior against the landed action registry if #320 has merged by then. diff --git a/docs/screenshots/resources-overview.svg b/docs/screenshots/resources-overview.svg deleted file mode 100644 index 4d6a5de03..000000000 --- a/docs/screenshots/resources-overview.svg +++ /dev/null @@ -1,13 +0,0 @@ - - Illustrative Medulla Resources tab - A terminal-style mock screenshot showing CPU, memory, network, and Agents panels with sample values. - - medulla · Sessions Hosts Resources SettingsResources - - CPUTotal 37% - - MemMemory 18.4 / 31.2 GiBSwap 0.3 / 8.0 GiBDisks/ 48% used R 1.2 MiB/s W 0.6 MiB/s/home 72% used R 0.1 MiB/s W 2.8 MiB/s - Neteth0 ↓ 2.4 MiB/s ↑ 0.8 MiB/s↓ total 1.2 GiB↑ total 324 MiB - AgentsPID KIND CPU MEM4211 Claude 82% 1.8G4220 Codex 24% 0.9G6170 Shell 1% 12M↑↓ select · e tree · f filterIllustrative mock screenshot · all telemetry values are sample data - - diff --git a/src/tui/src/ui/resources/mod.rs b/src/tui/src/ui/resources/mod.rs index 77ec0e6a4..44471fb5a 100644 --- a/src/tui/src/ui/resources/mod.rs +++ b/src/tui/src/ui/resources/mod.rs @@ -17,16 +17,12 @@ use medulla::config::{AppearanceConfig, ResourceDisplay}; -pub use cpu::{CpuField, CpuMonitor, CpuReading, CpuSnapshot}; pub use device::{device_lines, device_width_hint, DeviceMonitor}; pub use session::{session_segments, session_usage, SessionMonitor, SessionSnapshot}; pub use types::{DeviceSnapshot, ResourceMonitor, ResourceSnapshot}; -mod cpu; mod device; -pub mod net; mod process_monitor; -pub mod sampler; mod session; mod types; From 7cc34d9e2dd6e2475bf03c4d9f088ee402c09508 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:01:30 +0000 Subject: [PATCH 28/60] feat(tui): add btop-style system monitor view Introduce a new btop-inspired UI module with its own types and renderer to display system resource usage in the TUI. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/btop/mod.rs | 41 ++++++++++++++++++++++++++ src/tui/src/ui/btop/render.rs | 54 +++++++++++++++++++++++++++++++++++ src/tui/src/ui/btop/types.rs | 53 ++++++++++++++++++++++++++++++++++ 3 files changed, 148 insertions(+) create mode 100644 src/tui/src/ui/btop/mod.rs create mode 100644 src/tui/src/ui/btop/render.rs create mode 100644 src/tui/src/ui/btop/types.rs diff --git a/src/tui/src/ui/btop/mod.rs b/src/tui/src/ui/btop/mod.rs new file mode 100644 index 000000000..5fec56952 --- /dev/null +++ b/src/tui/src/ui/btop/mod.rs @@ -0,0 +1,41 @@ +//! The Resources tab's content: btop itself, compiled in and drawn natively. +//! +//! [`medulla_btop`] runs the vendored btop on its own thread with a virtual +//! terminal. This module is the host side of that terminal: a `vt100` emulator +//! that btop's output is drained into, a blit of that emulator's grid into the +//! ratatui frame, the encoding of crossterm keys and mouse events into the +//! bytes btop expects, and the feed that tells btop which processes are coding +//! agents. +//! +//! btop holds its state in process globals and starts at most once per process, +//! so there is exactly one [`BtopPane`], behind [`pane`], shared by every +//! [`App`](crate::ui::app::App) the process builds. +//! +//! - [`types`] — [`BtopPane`] and its lifecycle state. +//! - [`pane`] — starting, showing, hiding and draining btop. +//! - [`render`] — the emulator grid to ratatui cells. +//! - [`input`] — crossterm events to terminal bytes. +//! - [`feed`] — the background agent classification btop's agents box shows. + +use std::sync::{Mutex, MutexGuard, OnceLock}; + +pub mod feed; +pub mod input; +mod pane; +pub mod render; +pub mod types; + +pub use types::BtopPane; + +#[cfg(test)] +mod tests; + +/// The process's one btop pane. A poisoned lock is recovered rather than +/// propagated: the pane holds only a view of btop, never invariants a +/// panicking render could leave half-updated. +pub fn pane() -> MutexGuard<'static, BtopPane> { + static PANE: OnceLock> = OnceLock::new(); + PANE.get_or_init(|| Mutex::new(BtopPane::default())) + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} diff --git a/src/tui/src/ui/btop/render.rs b/src/tui/src/ui/btop/render.rs new file mode 100644 index 000000000..f4b93a0d0 --- /dev/null +++ b/src/tui/src/ui/btop/render.rs @@ -0,0 +1,54 @@ +//! Blit btop's emulated screen into the ratatui frame, cell for cell. +//! +//! btop positions everything absolutely and repaints only what changed, so the +//! emulator holds the authoritative picture and the frame simply copies it. +//! Copying cells (rather than building styled lines) keeps every box border and +//! braille graph glyph exactly where btop put it. + +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::{Modifier, Style}; + +use crate::worker::screen::vt_color; + +/// Copy the top-left `area`-sized region of `screen` into `buf` at `area`. +pub fn blit(screen: &vt100::Screen, buf: &mut Buffer, area: Rect) { + let area = area.intersection(buf.area); + for row in 0..area.height { + for col in 0..area.width { + let Some(cell) = screen.cell(row, col) else { + continue; + }; + let target = &mut buf[(area.x + col, area.y + row)]; + if cell.is_wide_continuation() { + // The wide glyph to the left already covers this column. + target.set_symbol(""); + continue; + } + let contents = cell.contents(); + target.set_symbol(if contents.is_empty() { " " } else { &contents }); + target.set_style(cell_style(cell)); + } + } +} + +/// The ratatui style for one emulator cell. Inverse swaps the colours, for +/// the reason given at [`crate::worker::screen::cell_style`]. +pub fn cell_style(cell: &vt100::Cell) -> Style { + let (fg, bg) = if cell.inverse() { + (cell.bgcolor(), cell.fgcolor()) + } else { + (cell.fgcolor(), cell.bgcolor()) + }; + let mut style = Style::default().fg(vt_color(fg)).bg(vt_color(bg)); + if cell.bold() { + style = style.add_modifier(Modifier::BOLD); + } + if cell.italic() { + style = style.add_modifier(Modifier::ITALIC); + } + if cell.underline() { + style = style.add_modifier(Modifier::UNDERLINED); + } + style +} diff --git a/src/tui/src/ui/btop/types.rs b/src/tui/src/ui/btop/types.rs new file mode 100644 index 000000000..4b9f187d1 --- /dev/null +++ b/src/tui/src/ui/btop/types.rs @@ -0,0 +1,53 @@ +//! The btop pane's state. + +use std::sync::Arc; + +use medulla_btop::Btop; + +use super::feed::AgentFeed; + +/// Wakes the UI loop when btop has drawn something. +pub type Waker = Arc; + +/// Where btop is in its once-per-process life. +#[derive(Default)] +pub enum Lifecycle { + /// Not started yet; the first time the tab is shown starts it. + #[default] + Idle, + /// Running, with the agent feed that keeps its agents box current. + Running { + /// The handle over btop's C ABI. + btop: Btop, + /// The background agent classifier. + feed: AgentFeed, + }, + /// Could not start, or btop's thread died; the message says why. + Failed(String), +} + +/// The host side of btop's virtual terminal. +pub struct BtopPane { + /// Where btop is in its life. + pub lifecycle: Lifecycle, + /// The emulator btop's output is drained into. + pub screen: vt100::Parser, + /// The size last reported to btop and the emulator, as (cols, rows). + pub size: (u16, u16), + /// Whether the tab is on screen; btop pauses while it is not. + pub visible: bool, + /// Called from btop's threads when output is ready. + pub waker: Option, +} + +impl Default for BtopPane { + fn default() -> Self { + Self { + lifecycle: Lifecycle::Idle, + screen: vt100::Parser::new(24, 80, 0), + size: (80, 24), + visible: false, + waker: None, + } + } +} From 50791791aae6480a6552887eaface0d384cf4cdf Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:01:58 +0000 Subject: [PATCH 29/60] feat(tui): add btop feed and input modules Introduce feed and input handling for the btop view so it can consume and respond to data. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/btop/feed.rs | 123 +++++++++++++++++++++++++++++++++++ src/tui/src/ui/btop/input.rs | 90 +++++++++++++++++++++++++ 2 files changed, 213 insertions(+) create mode 100644 src/tui/src/ui/btop/feed.rs create mode 100644 src/tui/src/ui/btop/input.rs diff --git a/src/tui/src/ui/btop/feed.rs b/src/tui/src/ui/btop/feed.rs new file mode 100644 index 000000000..d5ea633d4 --- /dev/null +++ b/src/tui/src/ui/btop/feed.rs @@ -0,0 +1,123 @@ +//! Tell btop which processes are coding agents. +//! +//! btop's agents box shows only the processes the host names. Naming them +//! takes an executable path, the full argv and a start time per process — +//! more than btop's own process list keeps — so a background thread reads +//! those with `sysinfo`, runs the SDK's agent classifier joined to Medulla's +//! launch registry, and hands btop the result. It scans only while the tab is +//! on screen. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use medulla::resources::agents::{ + discover_registered_agents, AgentOrigin, AgentProcess, ProcessRecord, ProcessUsage, +}; +use medulla_btop::AgentTag; +use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind}; + +/// How often the feed re-classifies while the tab is visible. Agents start and +/// stop on a human timescale; btop's own refresh is two seconds. +const PERIOD: Duration = Duration::from_secs(2); + +/// Handle to the background classifier. Dropping it stops the thread. +pub struct AgentFeed { + visible: Arc, + alive: Arc, +} + +impl AgentFeed { + /// Start classifying, handing each result to `publish`. + pub fn spawn(publish: impl Fn(&[AgentTag]) + Send + 'static) -> Self { + let visible = Arc::new(AtomicBool::new(true)); + let alive = Arc::new(AtomicBool::new(true)); + let (thread_visible, thread_alive) = (Arc::clone(&visible), Arc::clone(&alive)); + let spawned = std::thread::Builder::new() + .name("medulla-btop-agents".into()) + .spawn(move || { + let mut system = System::new(); + while thread_alive.load(Ordering::Relaxed) { + if thread_visible.load(Ordering::Relaxed) { + publish(&scan(&mut system)); + } + std::thread::sleep(PERIOD); + } + }); + if spawned.is_err() { + alive.store(false, Ordering::Relaxed); + } + Self { visible, alive } + } + + /// Scan only while the tab is on screen. + pub fn set_visible(&self, visible: bool) { + self.visible.store(visible, Ordering::Relaxed); + } +} + +impl Drop for AgentFeed { + fn drop(&mut self) { + self.alive.store(false, Ordering::Relaxed); + } +} + +/// Read the process table and classify it. +fn scan(system: &mut System) -> Vec { + // `without_tasks`: on Linux a thread is listed as a child process, which + // would only bloat the table the classifier walks. + system.refresh_processes_specifics( + ProcessesToUpdate::All, + true, + ProcessRefreshKind::nothing() + .with_exe(UpdateKind::OnlyIfNotSet) + .with_cmd(UpdateKind::OnlyIfNotSet) + .without_tasks(), + ); + let records: Vec = system + .processes() + .values() + .map(|process| ProcessRecord { + pid: process.pid().as_u32(), + ppid: process.parent().map(|parent| parent.as_u32()), + exe: process.exe().map(std::path::Path::to_path_buf), + argv: (!process.cmd().is_empty()).then(|| { + process + .cmd() + .iter() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect() + }), + cwd: None, + started_at_secs: process.start_time(), + usage: ProcessUsage::default(), + }) + .collect(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_secs()); + let medulla = std::process::id(); + tags( + &discover_registered_agents(&records, medulla, now, Default::default()), + medulla, + ) +} + +/// Turn classified agents into btop's agent table. +/// +/// The embedded OpenHuman runtime has no process of its own — it runs inside +/// Medulla — so it is tagged on Medulla's pid, which makes the processes it +/// spawned show under it. +pub fn tags(agents: &[AgentProcess], medulla_pid: u32) -> Vec { + agents + .iter() + .map(|agent| AgentTag { + pid: agent.pid.unwrap_or(medulla_pid), + label: agent.kind.label().to_string(), + launched: !matches!( + agent.origin, + AgentOrigin::External | AgentOrigin::Remote { .. } + ), + }) + .collect() +} diff --git a/src/tui/src/ui/btop/input.rs b/src/tui/src/ui/btop/input.rs new file mode 100644 index 000000000..fe7f44b04 --- /dev/null +++ b/src/tui/src/ui/btop/input.rs @@ -0,0 +1,90 @@ +//! Encode crossterm events as the bytes a terminal would send btop. +//! +//! btop parses raw terminal input itself (`Input::get` in btop_input.cpp), so +//! the host does not translate keys into btop actions; it reproduces what an +//! xterm would have written. Each event becomes one chunk, which btop reads as +//! one key — tidier than a real terminal, where a burst can arrive glued. + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; +use ratatui::layout::Rect; + +/// The bytes for `key`, or `None` for a key btop has no use for. +pub fn key_bytes(key: KeyEvent) -> Option> { + let ctrl = key.modifiers.contains(KeyModifiers::CONTROL); + let alt = key.modifiers.contains(KeyModifiers::ALT); + let mut bytes = match key.code { + KeyCode::Char(c) if ctrl => { + let lower = c.to_ascii_lowercase(); + if !lower.is_ascii_lowercase() { + return None; + } + vec![(lower as u8) & 0x1f] + } + KeyCode::Char(c) => c.to_string().into_bytes(), + // btop keeps the terminal's ICRNL, so Enter reaches it as a newline. + KeyCode::Enter => b"\n".to_vec(), + KeyCode::Esc => b"\x1b".to_vec(), + KeyCode::Backspace => b"\x7f".to_vec(), + KeyCode::Tab => b"\t".to_vec(), + KeyCode::BackTab => b"\x1b[Z".to_vec(), + KeyCode::Up => b"\x1b[A".to_vec(), + KeyCode::Down => b"\x1b[B".to_vec(), + KeyCode::Right => b"\x1b[C".to_vec(), + KeyCode::Left => b"\x1b[D".to_vec(), + KeyCode::Home => b"\x1b[H".to_vec(), + KeyCode::End => b"\x1b[F".to_vec(), + KeyCode::PageUp => b"\x1b[5~".to_vec(), + KeyCode::PageDown => b"\x1b[6~".to_vec(), + KeyCode::Insert => b"\x1b[2~".to_vec(), + KeyCode::Delete => b"\x1b[3~".to_vec(), + KeyCode::F(n) => function_key(n)?.as_bytes().to_vec(), + _ => return None, + }; + if alt { + bytes.insert(0, 0x1b); + } + Some(bytes) +} + +/// xterm's encoding of F1–F12. +fn function_key(n: u8) -> Option<&'static str> { + Some(match n { + 1 => "\x1bOP", + 2 => "\x1bOQ", + 3 => "\x1bOR", + 4 => "\x1bOS", + 5 => "\x1b[15~", + 6 => "\x1b[17~", + 7 => "\x1b[18~", + 8 => "\x1b[19~", + 9 => "\x1b[20~", + 10 => "\x1b[21~", + 11 => "\x1b[23~", + 12 => "\x1b[24~", + _ => return None, + }) +} + +/// The SGR mouse report for `event`, in coordinates relative to `area` (btop's +/// whole screen), or `None` when the event is outside it or btop ignores it. +pub fn mouse_bytes(event: MouseEvent, area: Rect) -> Option> { + let inside = event.column >= area.x + && event.column < area.x.saturating_add(area.width) + && event.row >= area.y + && event.row < area.y.saturating_add(area.height); + if !inside { + return None; + } + let (button, release) = match event.kind { + MouseEventKind::Down(MouseButton::Left) => (0, false), + MouseEventKind::Up(MouseButton::Left) => (0, true), + MouseEventKind::Drag(MouseButton::Left) => (32, false), + MouseEventKind::ScrollUp => (64, false), + MouseEventKind::ScrollDown => (65, false), + _ => return None, + }; + let col = event.column - area.x + 1; + let row = event.row - area.y + 1; + let end = if release { 'm' } else { 'M' }; + Some(format!("\x1b[<{button};{col};{row}{end}").into_bytes()) +} From d8a99cfbaac0103b30ffee014e8c7be34ecb6c4a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:02:20 +0000 Subject: [PATCH 30/60] feat(tui): add btop-style pane rendering Introduce a new pane module that renders btop-style panes in the TUI, giving the interface a richer, boxed layout for displaying system information. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/btop/pane.rs | 176 ++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 src/tui/src/ui/btop/pane.rs diff --git a/src/tui/src/ui/btop/pane.rs b/src/tui/src/ui/btop/pane.rs new file mode 100644 index 000000000..be856cf8e --- /dev/null +++ b/src/tui/src/ui/btop/pane.rs @@ -0,0 +1,176 @@ +//! Starting, showing, hiding and draining btop. + +use std::path::Path; +use std::time::Duration; + +use crossterm::event::{KeyEvent, MouseEvent}; +use medulla_btop::{Btop, StartError}; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; + +use super::feed::AgentFeed; +use super::input::{key_bytes, mouse_bytes}; +use super::render::blit; +use super::types::{BtopPane, Lifecycle, Waker}; + +/// How long [`BtopPane::shutdown`] waits for btop to save its config. +const STOP_TIMEOUT: Duration = Duration::from_secs(2); + +impl BtopPane { + /// Wake `waker` whenever btop draws. Takes effect at start, so set it + /// before the tab is first shown. + pub fn set_waker(&mut self, waker: Waker) { + self.waker = Some(waker); + } + + /// Show btop in `area`, starting it on first use with its config under + /// `config_dir`. Resizes btop and the emulator when `area` changed. + pub fn show(&mut self, config_dir: &Path, area: Rect) { + let size = (area.width.max(1), area.height.max(1)); + if matches!(self.lifecycle, Lifecycle::Idle) { + self.size = size; + self.screen.set_size(size.1, size.0); + self.start(config_dir); + } + if size != self.size { + self.size = size; + self.screen.set_size(size.1, size.0); + if let Lifecycle::Running { btop, .. } = &self.lifecycle { + btop.resize(size.0, size.1); + } + } + self.set_visible(true); + } + + /// Pause btop while its tab is off screen. + pub fn hide(&mut self) { + self.set_visible(false); + } + + fn set_visible(&mut self, visible: bool) { + if self.visible == visible { + return; + } + self.visible = visible; + if let Lifecycle::Running { btop, feed } = &self.lifecycle { + btop.set_visible(visible); + feed.set_visible(visible); + } + } + + fn start(&mut self, config_dir: &Path) { + let waker = self.waker.clone(); + let started = Btop::start(config_dir, self.size.0, self.size.1, move || { + if let Some(waker) = &waker { + waker(); + } + }); + self.lifecycle = match started { + Ok(btop) => { + let feed = AgentFeed::spawn(|agents| super::pane().publish_agents(agents)); + Lifecycle::Running { btop, feed } + } + Err(error) => Lifecycle::Failed(start_failure(&error)), + }; + // A fresh btop is visible from its first frame. + self.visible = true; + } + + /// Forward the feed's agent table to btop. + fn publish_agents(&self, agents: &[medulla_btop::AgentTag]) { + if let Lifecycle::Running { btop, .. } = &self.lifecycle { + btop.set_agents(agents); + } + } + + /// Move btop's pending output into the emulator. Returns true when the + /// operator asked btop to quit, which the host treats as leaving the tab. + pub fn pump(&mut self) -> bool { + let Lifecycle::Running { btop, .. } = &self.lifecycle else { + return false; + }; + let screen = &mut self.screen; + btop.drain(|bytes| screen.process(bytes)); + let leave = btop.take_leave(); + if let Some(error) = btop.error() { + self.lifecycle = Lifecycle::Failed(format!("btop stopped: {error}")); + } + leave + } + + /// Draw the current picture, or why there is none, into `area`. + pub fn render(&self, buf: &mut Buffer, area: Rect) { + match &self.lifecycle { + Lifecycle::Running { .. } => blit(self.screen.screen(), buf, area), + Lifecycle::Failed(message) => message_lines(buf, area, message), + Lifecycle::Idle => {} + } + } + + /// Send `key` to btop. False when btop is not running or has no use for it. + pub fn key(&self, key: KeyEvent) -> bool { + match (&self.lifecycle, key_bytes(key)) { + (Lifecycle::Running { btop, .. }, Some(bytes)) => { + btop.send(&bytes); + true + } + _ => false, + } + } + + /// Send a mouse event inside `area` (btop's screen) to btop. + pub fn mouse(&self, event: MouseEvent, area: Rect) -> bool { + match (&self.lifecycle, mouse_bytes(event, area)) { + (Lifecycle::Running { btop, .. }, Some(bytes)) => { + btop.send(&bytes); + true + } + _ => false, + } + } + + /// Whether btop is running (as opposed to idle or failed). + pub fn running(&self) -> bool { + matches!(self.lifecycle, Lifecycle::Running { .. }) + } + + /// The text currently on btop's screen, row by row; for tests and logs. + pub fn contents(&self) -> String { + self.screen.screen().contents() + } + + /// Stop btop so it saves its config. Called once as the app exits. + pub fn shutdown(&mut self) { + if let Lifecycle::Running { btop, .. } = &self.lifecycle { + btop.stop(STOP_TIMEOUT); + } + self.lifecycle = Lifecycle::Failed("btop has stopped".into()); + } +} + +/// What the tab says when btop cannot run. +fn start_failure(error: &StartError) -> String { + match error { + StartError::Unsupported => { + "The Resources tab runs btop, which is not available on this platform.".into() + } + other => format!("btop could not start: {other}"), + } +} + +/// Centre `message` in `area`. +fn message_lines(buf: &mut Buffer, area: Rect, message: &str) { + if area.height == 0 || area.width == 0 { + return; + } + let width = message.chars().count().min(usize::from(area.width)) as u16; + let x = area.x + (area.width - width) / 2; + let y = area.y + area.height / 2; + buf.set_stringn( + x, + y, + message, + usize::from(area.width), + ratatui::style::Style::default().fg(ratatui::style::Color::Yellow), + ); +} From b0b359cbae6c9854cd03c204b6640ed92373cf21 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:02:50 +0000 Subject: [PATCH 31/60] feat(tui): add resources module for app ui Introduce a resources module under the TUI app UI to hold shared resource definitions for the interface. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/resources/mod.rs | 66 +++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/tui/src/ui/app/resources/mod.rs diff --git a/src/tui/src/ui/app/resources/mod.rs b/src/tui/src/ui/app/resources/mod.rs new file mode 100644 index 000000000..befacde4d --- /dev/null +++ b/src/tui/src/ui/app/resources/mod.rs @@ -0,0 +1,66 @@ +//! The host Resources tab: btop, embedded, focused on coding agents. +//! +//! The tab is a window onto [`crate::ui::btop`]: drawing shows and drains the +//! shared btop pane, keys and mouse events inside the tab go to btop, and +//! btop's own quit (`q`, or Quit in its menu) returns to the Sessions tab. +//! btop is paused whenever another tab is on screen. + +use std::path::PathBuf; + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent}; +use ratatui::{layout::Rect, Frame}; + +use super::types::{tab_pos, App}; + +#[cfg(test)] +mod tests; + +impl App { + /// Draw btop into `area`, starting it the first time the tab is shown. + pub(super) fn draw_resources(&mut self, f: &mut Frame, area: Rect) { + self.resources_area = area; + let config_dir = self.btop_config_dir(); + let mut pane = crate::ui::btop::pane(); + pane.show(&config_dir, area); + let leave = pane.pump(); + pane.render(f.buffer_mut(), area); + drop(pane); + if leave { + self.tab_index = tab_pos("Sessions"); + self.selected = 0; + } + } + + /// Pause btop when the Resources tab is not the one being drawn. + pub(super) fn hide_resources_unless_shown(&self) { + if self.tab() != "Resources" { + crate::ui::btop::pane().hide(); + } + } + + /// Route `k` to btop. Everything goes to it except tab switching (Tab, + /// Shift-Tab) and the global chords (⌃C quit, ⌃O mouse, ⌃T new session), + /// which stay Medulla's on every tab. Returns whether btop took the key. + pub(super) fn resources_key(&mut self, k: KeyEvent) -> bool { + let ctrl = k.modifiers.contains(KeyModifiers::CONTROL); + let global = matches!(k.code, KeyCode::Tab | KeyCode::BackTab) + || (ctrl && matches!(k.code, KeyCode::Char('c' | 'o' | 't'))); + !global && crate::ui::btop::pane().key(k) + } + + /// Route a mouse event inside the tab's content to btop. + pub(super) fn resources_mouse(&mut self, m: &MouseEvent) -> bool { + crate::ui::btop::pane().mouse(*m, self.resources_area) + } + + /// Where btop keeps `btop.conf` and its log: beside Medulla's own state + /// rather than in the operator's `~/.config/btop`, so Medulla's defaults + /// (the agents box, tree view) never rewrite a standalone btop's config. + fn btop_config_dir(&self) -> PathBuf { + self.medulla_home + .clone() + .or_else(|| dirs::home_dir().map(|home| home.join(".medulla"))) + .unwrap_or_else(std::env::temp_dir) + .join("btop") + } +} From f8eada8a8b37efb8babcd8ace4d279978f36981a Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:03:01 +0000 Subject: [PATCH 32/60] refactor(tui): isolate btop config dir per process when no home is set The btop config directory now falls back to a per-process scratch directory under the temp dir instead of the shared temp dir when no Medulla home is configured, so concurrent test runs no longer collide on the same btop config. The fallback logic was also simplified to a match on the optional home. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/resources/mod.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tui/src/ui/app/resources/mod.rs b/src/tui/src/ui/app/resources/mod.rs index befacde4d..43e8f25b6 100644 --- a/src/tui/src/ui/app/resources/mod.rs +++ b/src/tui/src/ui/app/resources/mod.rs @@ -56,11 +56,11 @@ impl App { /// Where btop keeps `btop.conf` and its log: beside Medulla's own state /// rather than in the operator's `~/.config/btop`, so Medulla's defaults /// (the agents box, tree view) never rewrite a standalone btop's config. + /// An app with no home (a test) gets a per-process scratch directory. fn btop_config_dir(&self) -> PathBuf { - self.medulla_home - .clone() - .or_else(|| dirs::home_dir().map(|home| home.join(".medulla"))) - .unwrap_or_else(std::env::temp_dir) - .join("btop") + match &self.medulla_home { + Some(home) => home.join("btop"), + None => std::env::temp_dir().join(format!("medulla-btop-{}", std::process::id())), + } } } From 5f2c67040fb42631e4080728bb6638b918760f5b Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:03:26 +0000 Subject: [PATCH 33/60] feat(tui): hand the Resources tab over to btop The Resources tab now delegates mouse and keyboard input to the embedded btop view, leaving only tab switching and global chords to the app, and the status hint reflects btop's own bindings. The old in-app resources state, settings subpage, and snapshot plumbing were removed since btop now owns that screen. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/input/mouse.rs | 9 +++++---- src/tui/src/ui/app/keys/mod.rs | 13 +++---------- src/tui/src/ui/app/render/mod.rs | 2 +- src/tui/src/ui/app/state.rs | 13 +------------ src/tui/src/ui/app/types/model.rs | 21 +++++++-------------- 5 files changed, 17 insertions(+), 41 deletions(-) diff --git a/src/tui/src/ui/app/input/mouse.rs b/src/tui/src/ui/app/input/mouse.rs index a613afed8..f7911681e 100644 --- a/src/tui/src/ui/app/input/mouse.rs +++ b/src/tui/src/ui/app/input/mouse.rs @@ -100,6 +100,11 @@ impl App { if self.forward_harness_mouse(&m) { return None; } + // btop draws its own buttons and lists; inside its screen the pointer is + // its, outside (the tab bar) it is ours. + if self.tab() == "Resources" && self.resources_mouse(&m) { + return None; + } match m.kind { MouseEventKind::ScrollUp => self.scroll_at(m.column, m.row, true), MouseEventKind::ScrollDown => self.scroll_at(m.column, m.row, false), @@ -452,10 +457,6 @@ impl App { return None; } let tab = self.tab(); - if tab == "Resources" { - self.resources_click(x, y); - return None; - } // Subpage nav. Clicking a page both selects it and takes focus, which is // what Enter does from the keyboard — a click that only moved the // highlight would leave the arrows driving the menu the pointer just diff --git a/src/tui/src/ui/app/keys/mod.rs b/src/tui/src/ui/app/keys/mod.rs index e6909803d..c376ab871 100644 --- a/src/tui/src/ui/app/keys/mod.rs +++ b/src/tui/src/ui/app/keys/mod.rs @@ -131,16 +131,9 @@ impl App { let tab = self.tab(); - if tab == "Resources" && self.resources.menu_open && k.code == KeyCode::Esc { - // An armed signal promises "Esc cancels"; cancel it with the menu so - // a later `y` cannot confirm a kill the operator backed out of. - self.resources.agent_signal_armed = None; - self.resources.menu_open = false; - return None; - } - // Chorded keys belong to the global handlers below: ⌃T must open the - // session picker, not reach the Agents table's bare `t` binding. - if tab == "Resources" && !ctrl && !alt && self.resources_key(k.code) { + // btop owns the keyboard on its tab, bar tab switching and the global + // chords; see `resources_key` for exactly which keys it leaves alone. + if tab == "Resources" && self.resources_key(k) { return None; } diff --git a/src/tui/src/ui/app/render/mod.rs b/src/tui/src/ui/app/render/mod.rs index 1905ce06f..bba2340a4 100644 --- a/src/tui/src/ui/app/render/mod.rs +++ b/src/tui/src/ui/app/render/mod.rs @@ -261,7 +261,7 @@ impl App { } else if self.tab() == "TokenMaxxxing" { "Tab views · ↑↓ pages · ⏎ open · Esc menu · 1-3 jump" } else if self.tab() == "Resources" { - "Tab views · 1 CPU · 2 Mem · 3 Net · 4 Agents · p/P preset · +/- interval" + "Tab views · btop: A agents/all · e tree · f filter · Esc menu · q back" } else if self.tab() == "Hosts" { "Tab views · ↑↓ hosts · a add · e edit · d remove · i issue key · s ssh · ⏎ connect · u use · H switch host" } else if workflows { diff --git a/src/tui/src/ui/app/state.rs b/src/tui/src/ui/app/state.rs index 50321af1b..c6b56cf60 100644 --- a/src/tui/src/ui/app/state.rs +++ b/src/tui/src/ui/app/state.rs @@ -28,7 +28,6 @@ impl App { /// [`App::new`], sharing the slot the in-process hub fills once it is up. pub fn with_hub(backend: Arc, hub: HubSlot, loaded: LoadedConfig) -> Self { - let resources = super::resources::ResourcesState::from_config(&loaded.config.resources); let theme = Theme::from_config(&loaded.config.theme); let harness_skip_permissions = loaded.config.harness.skip_permissions; let status_line_promotion_pending = loaded.config.status_line.is_none(); @@ -80,7 +79,6 @@ impl App { mouse_capture: true, account_usage: None, settings_index: 0, - resources_settings_index: 0, settings_focused: false, appearance_index: 0, subscriptions_index: 0, @@ -95,8 +93,7 @@ impl App { resource_monitor: Default::default(), device_monitor: Default::default(), session_monitor: Default::default(), - resources, - resource_snapshot: Default::default(), + resources_area: ratatui::layout::Rect::default(), status_line_index: 0, status_line_promotion_pending, config_index: 0, @@ -186,14 +183,6 @@ impl App { self.device_monitor.inject(snapshot); } - /// Replace the cached background resources reading without sampling on the caller. - pub fn set_resource_snapshot( - &mut self, - snapshot: std::sync::Arc, - ) { - self.resources.sample_network(&snapshot); - self.resource_snapshot = snapshot; - } /// Configure Account logout with a testable home; without it, logout reports no writable location. pub fn set_medulla_home(&mut self, home: std::path::PathBuf) { diff --git a/src/tui/src/ui/app/types/model.rs b/src/tui/src/ui/app/types/model.rs index 9b0bec4bb..89b73e078 100644 --- a/src/tui/src/ui/app/types/model.rs +++ b/src/tui/src/ui/app/types/model.rs @@ -98,13 +98,12 @@ pub(in crate::ui::app) const TM_LEADERBOARD: usize = 2; /// /// This is the flat, selectable list [`App::settings_index`] indexes into. /// [`SETTINGS_GROUPS`] overlays the display-only headings. -pub const SETTINGS_SUBPAGES: [&str; 9] = [ +pub const SETTINGS_SUBPAGES: [&str; 8] = [ "Usage", "Appearance", "Subscriptions", "Status line", "Config", - "Resources", "Feedback", "Account", "Help", @@ -123,10 +122,9 @@ pub(in crate::ui::app) const SP_APPEARANCE: usize = 1; pub(in crate::ui::app) const SP_SUBSCRIPTIONS: usize = 2; pub(in crate::ui::app) const SP_STATUS_LINE: usize = 3; pub(in crate::ui::app) const SP_CONFIG: usize = 4; -pub(in crate::ui::app) const SP_RESOURCES: usize = 5; -pub(in crate::ui::app) const SP_FEEDBACK: usize = 6; -pub(in crate::ui::app) const SP_ACCOUNT: usize = 7; -pub(in crate::ui::app) const SP_HELP: usize = 8; +pub(in crate::ui::app) const SP_FEEDBACK: usize = 5; +pub(in crate::ui::app) const SP_ACCOUNT: usize = 6; +pub(in crate::ui::app) const SP_HELP: usize = 7; /// The index of a tab by name, or 0 if unknown. Keeps tab jumps robust as the tab /// list grows. @@ -455,8 +453,6 @@ pub struct App { /// the page entirely. Entering the pane hands `↑↓` to the content and makes /// the letter bindings deliberate rather than ambient. pub(in crate::ui::app) settings_focused: bool, - /// Selected option on the Resources settings page. - pub(in crate::ui::app) resources_settings_index: usize, /// The selected row on the Appearance subpage. pub(in crate::ui::app) appearance_index: usize, /// The selected meter row on the Subscriptions subpage. @@ -497,12 +493,9 @@ pub struct App { pub(in crate::ui::app) device_monitor: crate::ui::resources::DeviceMonitor, /// Throttled sampler backing the per-session usage shown in pane titles. pub(in crate::ui::app) session_monitor: crate::ui::resources::SessionMonitor, - /// State owned by the Resources tab. - pub(in crate::ui::app) resources: crate::ui::app::resources::ResourcesState, - /// Latest whole-host snapshot from the background sampler, drawn by the - /// Resources tab. - pub(in crate::ui::app) resource_snapshot: - std::sync::Arc, + /// Where the Resources tab last drew btop, so mouse events inside it can + /// be translated into btop's coordinates. + pub(in crate::ui::app) resources_area: ratatui::layout::Rect, /// The selected field row on the Status line subpage. pub(in crate::ui::app) status_line_index: usize, /// Whether the next persisted status-line edit must write the complete From 52a65df0ef265cd19a077da2e2434be0227b0ef8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:03:56 +0000 Subject: [PATCH 34/60] refactor(tui): remove resources settings subpage The resources settings subpage and its key handling, rendering, and edit modules have been removed, along with the plot module export. The btop module is now exported from the ui module instead. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/keys/settings/mod.rs | 24 +---------------------- src/tui/src/ui/app/render/mod.rs | 1 - src/tui/src/ui/app/render/settings/mod.rs | 3 +-- src/tui/src/ui/app/settings_edit/mod.rs | 1 - src/tui/src/ui/mod.rs | 2 +- 5 files changed, 3 insertions(+), 28 deletions(-) diff --git a/src/tui/src/ui/app/keys/settings/mod.rs b/src/tui/src/ui/app/keys/settings/mod.rs index f83253a13..1403b5531 100644 --- a/src/tui/src/ui/app/keys/settings/mod.rs +++ b/src/tui/src/ui/app/keys/settings/mod.rs @@ -22,7 +22,7 @@ use medulla::client::FeedbackType; use super::super::appearance::APPEARANCE_ROWS; use super::super::types::{ App, Cmd, SETTINGS_SUBPAGES, SP_ACCOUNT, SP_APPEARANCE, SP_CONFIG, SP_FEEDBACK, SP_HELP, - SP_RESOURCES, SP_STATUS_LINE, SP_SUBSCRIPTIONS, SP_USAGE, + SP_STATUS_LINE, SP_SUBSCRIPTIONS, SP_USAGE, }; impl App { @@ -83,24 +83,6 @@ impl App { SP_CONFIG => self.config_key(code), SP_FEEDBACK => self.feedback_key(code), SP_ACCOUNT => self.account_key(code), - SP_RESOURCES => match code { - KeyCode::Char('j') | KeyCode::Char('k') => { - self.move_resources_settings(matches!(code, KeyCode::Char('k'))); - SettingsKey::handled(None) - } - KeyCode::Enter => { - let status = self.toggle_resources_setting(); - self.set_status(status); - SettingsKey::handled(None) - } - KeyCode::Left | KeyCode::Right => { - let delta = if code == KeyCode::Left { -1 } else { 1 }; - let status = self.adjust_resources_setting(delta); - self.set_status(status); - SettingsKey::handled(None) - } - _ => SettingsKey::Unhandled, - }, _ => SettingsKey::Unhandled, } } @@ -132,10 +114,6 @@ impl App { SettingsKey::handled(None) } SP_FEEDBACK => SettingsKey::handled(self.move_feedback_index(up)), - SP_RESOURCES => { - self.move_resources_settings(up); - SettingsKey::handled(None) - } // Help is a single long page rather than a list, so it scrolls by // the line. It outgrew a short terminal once the harness bindings // and commands landed on it, and a reference you cannot reach the diff --git a/src/tui/src/ui/app/render/mod.rs b/src/tui/src/ui/app/render/mod.rs index bba2340a4..91b1e7e54 100644 --- a/src/tui/src/ui/app/render/mod.rs +++ b/src/tui/src/ui/app/render/mod.rs @@ -21,7 +21,6 @@ mod frame_state; mod hosts; mod points; mod prompt; -pub(super) mod resources; mod selection; mod session_modals; mod sessions; diff --git a/src/tui/src/ui/app/render/settings/mod.rs b/src/tui/src/ui/app/render/settings/mod.rs index 498da0c1a..59cf23651 100644 --- a/src/tui/src/ui/app/render/settings/mod.rs +++ b/src/tui/src/ui/app/render/settings/mod.rs @@ -17,7 +17,7 @@ use ratatui::Frame; use crate::ui::multi_pane; use super::super::types::{ - App, SP_ACCOUNT, SP_APPEARANCE, SP_CONFIG, SP_FEEDBACK, SP_RESOURCES, SP_STATUS_LINE, + App, SP_ACCOUNT, SP_APPEARANCE, SP_CONFIG, SP_FEEDBACK, SP_STATUS_LINE, SP_SUBSCRIPTIONS, SP_USAGE, }; @@ -59,7 +59,6 @@ impl App { SP_CONFIG => self.draw_config(f, content), SP_FEEDBACK => self.draw_feedback(f, content), SP_ACCOUNT => self.draw_account(f, content), - SP_RESOURCES => self.draw_resources_settings(f, content), _ => self.draw_help(f, content), } } diff --git a/src/tui/src/ui/app/settings_edit/mod.rs b/src/tui/src/ui/app/settings_edit/mod.rs index 85040ab80..aba897f42 100644 --- a/src/tui/src/ui/app/settings_edit/mod.rs +++ b/src/tui/src/ui/app/settings_edit/mod.rs @@ -17,7 +17,6 @@ use medulla::config::OpencodeConfig; use super::types::App; -mod resources; mod types; #[cfg(test)] diff --git a/src/tui/src/ui/mod.rs b/src/tui/src/ui/mod.rs index e35625d7e..6705d00f4 100644 --- a/src/tui/src/ui/mod.rs +++ b/src/tui/src/ui/mod.rs @@ -14,6 +14,7 @@ pub use medulla::ui::{agents, command, fleet, git_review, harness, hosts, meters pub(crate) mod agent_lane; pub mod app; +pub mod btop; pub mod chat; pub mod composer; pub(crate) mod gauge; @@ -24,7 +25,6 @@ pub(crate) mod layout; pub mod login; pub(crate) mod multi_pane; pub mod onboarding; -pub mod plot; pub mod resources; pub mod screen; pub(crate) mod selection; From 27e6ceb31c9969a6e633863ac7eec0d6f2b459b8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:04:09 +0000 Subject: [PATCH 35/60] refactor(theme): remove resources theme and gradient helpers The ResourcesTheme struct and its gradient-based color helpers were dropped from the theme module, along with the with_depth palette adaptation and the resources field on Theme. The Resources tab now relies on the shared Theme colors instead of maintaining a separate btop-style palette. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/theme/mod.rs | 31 +---- src/tui/src/ui/theme/types.rs | 213 ---------------------------------- 2 files changed, 2 insertions(+), 242 deletions(-) diff --git a/src/tui/src/ui/theme/mod.rs b/src/tui/src/ui/theme/mod.rs index 4eaebe486..d1dd9b699 100644 --- a/src/tui/src/ui/theme/mod.rs +++ b/src/tui/src/ui/theme/mod.rs @@ -73,7 +73,6 @@ impl Default for Theme { attention_blink: true, attention_blink_ms: DEFAULT_BLINK_MS, background: Color::Rgb(0, 0, 0), - resources: ResourcesTheme::default(), } } } @@ -112,21 +111,6 @@ impl Theme { s.as_deref().and_then(parse_color).unwrap_or(fallback) }; let background = types::background_color(cfg.background.as_deref(), d.background); - // The Resources tab sits on the app's background unless its own - // `mainBg` says otherwise. - let mut resources = cfg - .resources - .as_ref() - .map(ResourcesTheme::from_config) - .unwrap_or_default(); - if cfg - .resources - .as_ref() - .and_then(|r| r.main_bg.as_ref()) - .is_none() - { - resources.main_bg = background; - } Theme { primary: pick(&cfg.primary, d.primary), accent: pick(&cfg.accent, d.accent), @@ -139,17 +123,9 @@ impl Theme { .map(blink_ms_from_seconds) .unwrap_or(d.attention_blink_ms), background, - resources, } } - /// Adapt resource colors to the detected terminal palette. - pub fn with_depth(mut self, depth: ColorDepth) -> Self { - self.background = depth.convert(self.background); - self.resources = self.resources.with_depth(depth); - self - } - /// Whether the attention pulse is in its bright phase on `frame`. /// /// The pulse is driven off the event loop's frame counter rather than @@ -310,7 +286,7 @@ pub fn color_to_string(color: Color) -> String { /// Read-modify-write the `[theme]` keys Appearance owns in the config file at /// `path`, preserving every other section and every other `[theme]` key — a -/// hand-set `background` or `[theme.resources]` table is not Appearance's to +/// hand-set `background` or any other `[theme]` table is not Appearance's to /// drop. Missing files (and parent dirs) are created. Comments are not /// preserved (the `toml` crate is value-based). pub fn persist_theme(path: &Path, theme: &Theme) -> anyhow::Result<()> { @@ -355,7 +331,4 @@ pub fn persist_theme(path: &Path, theme: &Theme) -> anyhow::Result<()> { mod tests; mod types; -pub use types::{ResourcesTheme, Theme}; - -mod gradient; -pub use gradient::{truecolor_to_16, truecolor_to_256, ColorDepth, Gradient, TTY_PALETTE}; +pub use types::Theme; diff --git a/src/tui/src/ui/theme/types.rs b/src/tui/src/ui/theme/types.rs index f10006971..093876f60 100644 --- a/src/tui/src/ui/theme/types.rs +++ b/src/tui/src/ui/theme/types.rs @@ -1,14 +1,6 @@ //! Data types for the `theme` module. #[allow(unused_imports)] use super::*; - -fn pick_gradient_color(value: &Option, fallback: Option) -> Option { - match value { - None => fallback, - Some(value) if value.trim().is_empty() => None, - Some(value) => parse_color(value).or(fallback), - } -} /// The resolved color roles used across the TUI. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Theme { @@ -34,111 +26,6 @@ pub struct Theme { /// Background behind the whole interface, painted under every cell no /// widget gave a colour of its own; `Color::Reset` keeps the terminal's. pub background: Color, - /// Colors and gradients used by resource panels and charts. - pub resources: ResourcesTheme, -} - -/// btop-style colors for resource panels and their graphs. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ResourcesTheme { - pub cpu_box: Color, - pub mem_box: Color, - pub net_box: Color, - pub proc_box: Color, - pub div_line: Color, - pub meter_bg: Color, - pub graph_text: Color, - pub inactive_fg: Color, - /// Body text inside resource boxes. - pub main_fg: Color, - /// Background behind the whole Resources tab; follows - /// [`Theme::background`] unless `mainBg` overrides it, and `Color::Reset` - /// keeps the terminal's own. - pub main_bg: Color, - /// Box titles. - pub title: Color, - /// Hotkey letters inside box titles and buttons. - pub hi_fg: Color, - /// Background of the selected Agents row. - pub selected_bg: Color, - /// Foreground of the selected Agents row. - pub selected_fg: Color, - pub cpu: Gradient, - pub temp: Gradient, - pub used: Gradient, - pub free: Gradient, - pub cached: Gradient, - pub available: Gradient, - pub download: Gradient, - pub upload: Gradient, - pub process: Gradient, -} - -impl Default for ResourcesTheme { - fn default() -> Self { - let color = |hex| parse_color(hex).expect("valid built-in theme color"); - Self { - cpu_box: color("#556d59"), - mem_box: color("#6c6c4b"), - net_box: color("#5c588d"), - proc_box: color("#805252"), - div_line: color("#303030"), - meter_bg: color("#404040"), - graph_text: color("#606060"), - inactive_fg: color("#404040"), - main_fg: color("#cccccc"), - main_bg: color("#000000"), - title: color("#eeeeee"), - hi_fg: color("#b54040"), - selected_bg: color("#6a2f2f"), - selected_fg: color("#eeeeee"), - cpu: Gradient::new( - color("#77ca9b"), - Some(color("#cbc06c")), - Some(color("#dc4c4c")), - ), - temp: Gradient::new( - color("#4897d4"), - Some(color("#5474e8")), - Some(color("#ff40b6")), - ), - used: Gradient::new( - color("#592b26"), - Some(color("#d9626d")), - Some(color("#ff4769")), - ), - free: Gradient::new( - color("#384f21"), - Some(color("#b5e685")), - Some(color("#dcff85")), - ), - cached: Gradient::new( - color("#163350"), - Some(color("#74e6fc")), - Some(color("#26c5ff")), - ), - available: Gradient::new( - color("#4e3f0e"), - Some(color("#ffd77a")), - Some(color("#ffb814")), - ), - download: Gradient::new( - color("#291f75"), - Some(color("#4f43a3")), - Some(color("#b0a9de")), - ), - upload: Gradient::new( - color("#620665"), - Some(color("#7d4180")), - Some(color("#dcafde")), - ), - process: Gradient::new( - color("#80d0a3"), - Some(color("#dcd179")), - Some(color("#d45454")), - ), - } - } } /// Resolve a configured background: an empty string asks for the terminal's @@ -149,103 +36,3 @@ pub(crate) fn background_color(value: Option<&str>, fallback: Color) -> Color { value => value.and_then(parse_color).unwrap_or(fallback), } } - -impl ResourcesTheme { - pub(crate) fn from_config(cfg: &medulla::config::ResourcesThemeConfig) -> Self { - let defaults = Self::default(); - let pick = |value: &Option, fallback: Color| { - value.as_deref().and_then(parse_color).unwrap_or(fallback) - }; - Self { - cpu_box: pick(&cfg.cpu_box, defaults.cpu_box), - mem_box: pick(&cfg.mem_box, defaults.mem_box), - net_box: pick(&cfg.net_box, defaults.net_box), - proc_box: pick(&cfg.proc_box, defaults.proc_box), - div_line: pick(&cfg.div_line, defaults.div_line), - meter_bg: pick(&cfg.meter_bg, defaults.meter_bg), - graph_text: pick(&cfg.graph_text, defaults.graph_text), - inactive_fg: pick(&cfg.inactive_fg, defaults.inactive_fg), - main_fg: pick(&cfg.main_fg, defaults.main_fg), - main_bg: background_color(cfg.main_bg.as_deref(), defaults.main_bg), - title: pick(&cfg.title, defaults.title), - hi_fg: pick(&cfg.hi_fg, defaults.hi_fg), - selected_bg: pick(&cfg.selected_bg, defaults.selected_bg), - selected_fg: pick(&cfg.selected_fg, defaults.selected_fg), - cpu: Gradient::new( - pick(&cfg.cpu_start, defaults.cpu.start), - pick_gradient_color(&cfg.cpu_mid, defaults.cpu.mid), - pick_gradient_color(&cfg.cpu_end, defaults.cpu.end), - ), - temp: Gradient::new( - pick(&cfg.temp_start, defaults.temp.start), - pick_gradient_color(&cfg.temp_mid, defaults.temp.mid), - pick_gradient_color(&cfg.temp_end, defaults.temp.end), - ), - used: Gradient::new( - pick(&cfg.used_start, defaults.used.start), - pick_gradient_color(&cfg.used_mid, defaults.used.mid), - pick_gradient_color(&cfg.used_end, defaults.used.end), - ), - free: Gradient::new( - pick(&cfg.free_start, defaults.free.start), - pick_gradient_color(&cfg.free_mid, defaults.free.mid), - pick_gradient_color(&cfg.free_end, defaults.free.end), - ), - cached: Gradient::new( - pick(&cfg.cached_start, defaults.cached.start), - pick_gradient_color(&cfg.cached_mid, defaults.cached.mid), - pick_gradient_color(&cfg.cached_end, defaults.cached.end), - ), - available: Gradient::new( - pick(&cfg.available_start, defaults.available.start), - pick_gradient_color(&cfg.available_mid, defaults.available.mid), - pick_gradient_color(&cfg.available_end, defaults.available.end), - ), - download: Gradient::new( - pick(&cfg.download_start, defaults.download.start), - pick_gradient_color(&cfg.download_mid, defaults.download.mid), - pick_gradient_color(&cfg.download_end, defaults.download.end), - ), - upload: Gradient::new( - pick(&cfg.upload_start, defaults.upload.start), - pick_gradient_color(&cfg.upload_mid, defaults.upload.mid), - pick_gradient_color(&cfg.upload_end, defaults.upload.end), - ), - process: Gradient::new( - pick(&cfg.process_start, defaults.process.start), - pick_gradient_color(&cfg.process_mid, defaults.process.mid), - pick_gradient_color(&cfg.process_end, defaults.process.end), - ), - } - } - - /// Convert the resource palette and its gradients for a terminal's color depth. - pub fn with_depth(self, depth: ColorDepth) -> Self { - let convert = |color| depth.convert(color); - Self { - cpu_box: convert(self.cpu_box), - mem_box: convert(self.mem_box), - net_box: convert(self.net_box), - proc_box: convert(self.proc_box), - div_line: convert(self.div_line), - meter_bg: convert(self.meter_bg), - graph_text: convert(self.graph_text), - inactive_fg: convert(self.inactive_fg), - main_fg: convert(self.main_fg), - main_bg: convert(self.main_bg), - title: convert(self.title), - hi_fg: convert(self.hi_fg), - selected_bg: convert(self.selected_bg), - selected_fg: convert(self.selected_fg), - cpu: self.cpu.with_depth(depth), - temp: self.temp.with_depth(depth), - used: self.used.with_depth(depth), - free: self.free.with_depth(depth), - cached: self.cached.with_depth(depth), - available: self.available.with_depth(depth), - download: self.download.with_depth(depth), - upload: self.upload.with_depth(depth), - process: self.process.with_depth(depth), - } - } -} From f0fc3d702aaed5a2210755f8e17df5660759c3d3 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:04:24 +0000 Subject: [PATCH 36/60] refactor(tui): replace resource sampler with btop redraw waker The event loop no longer spawns a background resource sampler; instead the btop pane installs a waker that sends a Redraw message so the Resources tab updates as soon as btop draws. The remote server's usage sampler and its interval option were removed along with the now-unused sampling code. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/event_loop/mod.rs | 14 ++++++++------ src/tui/src/event_loop/types.rs | 4 ++-- src/tui/src/remote/serve/entry.rs | 6 +----- src/tui/src/remote/serve/mod.rs | 12 +----------- src/tui/src/ui/theme/types.rs | 1 + 5 files changed, 13 insertions(+), 24 deletions(-) diff --git a/src/tui/src/event_loop/mod.rs b/src/tui/src/event_loop/mod.rs index 5c700370d..92870e46b 100644 --- a/src/tui/src/event_loop/mod.rs +++ b/src/tui/src/event_loop/mod.rs @@ -21,7 +21,6 @@ use medulla_tui::ui::app::{App, Cmd}; use crate::terminal::set_mouse_capture; mod cmd_dispatch; -mod resources; mod types; mod update_checker; @@ -95,12 +94,14 @@ pub(crate) async fn run( // header banner. Disabled via `[update] check = false` or // `MEDULLA_NO_UPDATE_CHECK`. spawn_update_checker(&app.loaded, &msg_tx); - // Two readings per column, so a full-width graph is never short of history. - let history_capacity = usize::from(terminal.size()?.width).saturating_mul(2); - let resource_sampler = resources::ResourceSampler::spawn(&app, history_capacity, &msg_tx); + // btop draws on its own threads; this wakes the loop to show it at once + // rather than on the next animation tick. + let btop_tx = msg_tx.clone(); + medulla_tui::ui::btop::pane().set_waker(std::sync::Arc::new(move || { + let _ = btop_tx.send(AppMsg::Redraw); + })); loop { - resource_sampler.retune(&app); terminal.draw(|f| app.draw(f))?; if app.should_quit { break; @@ -134,7 +135,8 @@ pub(crate) async fn run( } Some(msg) = msg_rx.recv() => { match msg { - AppMsg::Resources(snapshot) => app.set_resource_snapshot(snapshot), + // Nothing to fold in: the loop iteration itself redraws. + AppMsg::Redraw => {} AppMsg::Status(s) => app.set_status(s), AppMsg::RemoteHostConnected { host_id, diff --git a/src/tui/src/event_loop/types.rs b/src/tui/src/event_loop/types.rs index baa6243e6..8a79e5823 100644 --- a/src/tui/src/event_loop/types.rs +++ b/src/tui/src/event_loop/types.rs @@ -61,8 +61,8 @@ impl Drop for PendingFrame { /// Messages sent from spawned async tasks back to the event loop. pub(super) enum AppMsg { - /// Fresh whole-host resources, sampled away from the UI task. - Resources(std::sync::Arc), + /// btop drew something; redraw so the Resources tab shows it. + Redraw, /// A status-line update. Status(String), /// A remote host answered, and this is what it can do. diff --git a/src/tui/src/remote/serve/entry.rs b/src/tui/src/remote/serve/entry.rs index c0e7fc2a1..6eec1561e 100644 --- a/src/tui/src/remote/serve/entry.rs +++ b/src/tui/src/remote/serve/entry.rs @@ -209,11 +209,7 @@ pub async fn run(args: &[String]) -> anyhow::Result<()> { ); } - let mut server = RemoteServer::new(sessions, bridge, host_name) - .with_workspaces(workspaces) - .with_usage_interval(std::time::Duration::from_millis( - loaded.config.resources.update_ms, - )); + let mut server = RemoteServer::new(sessions, bridge, host_name).with_workspaces(workspaces); #[cfg(feature = "workflows")] { server = server.with_workflows(super::WorkflowHost::from_config( diff --git a/src/tui/src/remote/serve/mod.rs b/src/tui/src/remote/serve/mod.rs index 747a856c1..f0a9da217 100644 --- a/src/tui/src/remote/serve/mod.rs +++ b/src/tui/src/remote/serve/mod.rs @@ -35,7 +35,6 @@ pub mod paired; mod paired_tests; mod sessions; mod types; -mod usage; mod workflows; // Unix only, and not for want of portability: these drive a **real pty running @@ -104,8 +103,6 @@ pub struct RemoteServer { /// /// [`publish_sessions_if_changed`]: Self::publish_sessions_if_changed last_rows: Vec, - /// Samples each session's agent process for the rows' usage. - usage: usage::UsageSampler, /// Generation of [`last_rows`](Self::last_rows), so a client can tell the /// parts of one chunked list from another's. sessions_batch_id: u64, @@ -132,7 +129,6 @@ impl RemoteServer { capabilities, peers: HashSet::new(), last_rows: Vec::new(), - usage: usage::UsageSampler::default(), sessions_batch_id: 0, log: None, workflows: None, @@ -145,12 +141,6 @@ impl RemoteServer { self } - /// Set the minimum time between process usage samples and broadcasts. - pub fn with_usage_interval(mut self, interval: Duration) -> Self { - self.usage.set_interval(interval); - self - } - /// Narrate what the server does to `log`. pub fn with_log(mut self, log: LogFn) -> Self { self.log = Some(log); @@ -474,7 +464,7 @@ impl RemoteServer { wire_row(row, bracketed) }) .collect(); - self.usage.annotate(&self.sessions.sessions, rows) + rows } /// Send `peer` the cached session list. diff --git a/src/tui/src/ui/theme/types.rs b/src/tui/src/ui/theme/types.rs index 093876f60..4226a5559 100644 --- a/src/tui/src/ui/theme/types.rs +++ b/src/tui/src/ui/theme/types.rs @@ -1,6 +1,7 @@ //! Data types for the `theme` module. #[allow(unused_imports)] use super::*; + /// The resolved color roles used across the TUI. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Theme { From 80863653507ca18ebea1d266a4ac62f450909782 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:04:38 +0000 Subject: [PATCH 37/60] refactor(remote): simplify session row collection and drop usage test module The current_rows helper now returns the collected rows directly instead of binding them to a temporary, and its doc comment no longer mentions agent process usage sampling. The unused usage test module was removed. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/remote/serve/mod.rs | 9 +++------ src/tui/src/remote/serve/tests/mod.rs | 1 - 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/tui/src/remote/serve/mod.rs b/src/tui/src/remote/serve/mod.rs index f0a9da217..f5b06548d 100644 --- a/src/tui/src/remote/serve/mod.rs +++ b/src/tui/src/remote/serve/mod.rs @@ -447,11 +447,9 @@ impl RemoteServer { self.send_sessions(peer).await; } - /// The session list as the client's rail draws it, freshly computed, - /// with each session's agent process usage when it is due a sample. + /// The session list as the client's rail draws it, freshly computed. fn current_rows(&mut self) -> Vec { - let rows = self - .sessions + self.sessions .sessions .rows() .iter() @@ -463,8 +461,7 @@ impl RemoteServer { .unwrap_or(false); wire_row(row, bracketed) }) - .collect(); - rows + .collect() } /// Send `peer` the cached session list. diff --git a/src/tui/src/remote/serve/tests/mod.rs b/src/tui/src/remote/serve/tests/mod.rs index a812ff6d9..acd483133 100644 --- a/src/tui/src/remote/serve/tests/mod.rs +++ b/src/tui/src/remote/serve/tests/mod.rs @@ -15,4 +15,3 @@ mod config; mod paired; mod sessions; mod support; -mod usage; From 9bd4c4ba58db12777ed3e8c48c599b5c0c00acc7 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:04:50 +0000 Subject: [PATCH 38/60] refactor(config): remove resources config types Drops the ResourcesConfig and ResourcesThemeConfig types along with the resources field on TuiConfig and the theme's resource color overrides, since the Resources tab they configured no longer exists. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/sdk/src/config/mod.rs | 6 +- src/sdk/src/config/types/document.rs | 4 - src/sdk/src/config/types/mod.rs | 1 - src/sdk/src/config/types/presentation.rs | 94 ------------------------ 4 files changed, 1 insertion(+), 104 deletions(-) diff --git a/src/sdk/src/config/mod.rs b/src/sdk/src/config/mod.rs index a97263cba..b1e15661c 100644 --- a/src/sdk/src/config/mod.rs +++ b/src/sdk/src/config/mod.rs @@ -15,7 +15,6 @@ mod load; mod local_hosts; mod persist; mod remote_hosts; -mod resources; mod subscriptions; mod types; mod urls; @@ -55,9 +54,6 @@ pub use persist::{ pub use remote_hosts::{ remote_host_id, remote_host_name, remote_host_section, remote_hosts, RemoteHostRef, }; -pub use resources::{ - ResourcesConfig, DEFAULT_RESOURCES_UPDATE_MS, MAX_RESOURCES_UPDATE_MS, MIN_RESOURCES_UPDATE_MS, -}; pub use subscriptions::{ MeterId, MeterSource, SubscriptionsConfig, DEFAULT_SUBSCRIPTION_REFRESH_SECONDS, MIN_SUBSCRIPTION_REFRESH_SECONDS, @@ -67,7 +63,7 @@ pub use types::{ FavoriteWorkspace, FieldPlacement, FieldVisibility, FleetConfig, HarnessNameStyle, HarnessSection, HookDefaultsConfig, HostSection, HubSection, HubWorkerConfig, LinkConfig, LoadedConfig, McpSection, OnboardingConfig, OpencodeConfig, PathStyle, Peer, - ProviderBudgetConfig, RemoteHostSection, ResourcesThemeConfig, RouterConfig, + ProviderBudgetConfig, RemoteHostSection, RouterConfig, RouterProviderConfig, StatusLineConfig, ThemeConfig, TuiConfig, UpdateConfig, WorkflowConfig, WorkflowsConfig, }; diff --git a/src/sdk/src/config/types/document.rs b/src/sdk/src/config/types/document.rs index ab24aef28..8917d22c5 100644 --- a/src/sdk/src/config/types/document.rs +++ b/src/sdk/src/config/types/document.rs @@ -33,9 +33,6 @@ pub struct TuiConfig { /// Which subscription-usage meters the Agents sidebar shows, and how. #[serde(default)] pub subscriptions: SubscriptionsConfig, - /// Sampling cadence and layout for the Resources tab. - #[serde(default)] - pub resources: ResourcesConfig, /// How a harness row on the Agents rail is laid out. Absent means "derive /// it from `[appearance]`" — see [`TuiConfig::status_line`]. #[serde(skip_serializing_if = "Option::is_none")] @@ -123,7 +120,6 @@ impl Default for TuiConfig { theme: ThemeConfig::default(), appearance: AppearanceConfig::default(), subscriptions: SubscriptionsConfig::default(), - resources: ResourcesConfig::default(), status_line: None, onboarding: OnboardingConfig::default(), workflow: WorkflowConfig::default(), diff --git a/src/sdk/src/config/types/mod.rs b/src/sdk/src/config/types/mod.rs index 62ec60709..cd48ef040 100644 --- a/src/sdk/src/config/types/mod.rs +++ b/src/sdk/src/config/types/mod.rs @@ -13,7 +13,6 @@ use serde_json::Value; use super::urls::PROD_BACKEND_BASE_URL; use super::AppearanceConfig; -use super::ResourcesConfig; use super::SubscriptionsConfig; use crate::fleet::AgentDescriptor; use crate::fleet::{ diff --git a/src/sdk/src/config/types/presentation.rs b/src/sdk/src/config/types/presentation.rs index d966ebed6..4ed8f5996 100644 --- a/src/sdk/src/config/types/presentation.rs +++ b/src/sdk/src/config/types/presentation.rs @@ -39,100 +39,6 @@ pub struct ThemeConfig { /// empty string keeps the terminal's own background. #[serde(skip_serializing_if = "Option::is_none")] pub background: Option, - /// Optional btop-style resource panel colors and gradients. - #[serde(skip_serializing_if = "Option::is_none")] - pub resources: Option, -} - -/// Optional color overrides for the resource panels. Keys use camelCase in -/// configuration, for example `cpuBox` and `cpuStart`. -#[derive(Debug, Clone, Serialize, Deserialize, Default)] -#[serde(default, rename_all = "camelCase")] -pub struct ResourcesThemeConfig { - #[serde(skip_serializing_if = "Option::is_none")] - pub cpu_box: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub mem_box: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub net_box: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub proc_box: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub div_line: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub meter_bg: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub graph_text: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub inactive_fg: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub main_fg: Option, - /// Background painted behind every resource box; empty keeps the - /// terminal's own. - #[serde(skip_serializing_if = "Option::is_none")] - pub main_bg: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub hi_fg: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub selected_bg: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub selected_fg: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cpu_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cpu_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cpu_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub temp_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub temp_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub temp_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub used_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub used_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub used_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub free_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub free_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub free_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cached_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cached_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cached_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub available_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub available_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub available_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub download_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub download_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub download_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub upload_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub upload_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub upload_end: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub process_start: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub process_mid: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub process_end: Option, } /// Onboarding state: what the welcome flow has already shown this user. From bfeebda45d3fae6c62390d9322f9e36a714be769 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:05:26 +0000 Subject: [PATCH 39/60] fix(tui): hide resources when their tab is not shown The render loop now calls hide_resources_unless_shown before drawing each frame so the resources pane only collects and draws while its tab is on screen, matching btop's behaviour. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/render/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tui/src/ui/app/render/mod.rs b/src/tui/src/ui/app/render/mod.rs index 91b1e7e54..b5fa5f530 100644 --- a/src/tui/src/ui/app/render/mod.rs +++ b/src/tui/src/ui/app/render/mod.rs @@ -93,6 +93,8 @@ impl App { // Everything the last frame recorded for the next key press, dropped // before this one records its own — see [`frame_state`]. self.reset_frame_state(); + // btop collects and draws only while its tab is the one on screen. + self.hide_resources_unless_shown(); // The composer now lives inside the Sessions pane, so the only thing // that still claims a row of its own below the content is the inline // prompt. From 4168b3d20a26791d05bbdf9af21478db6ad1e525 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:05:33 +0000 Subject: [PATCH 40/60] test(theme): drop assertions for retired resources section Removed the remaining references to the retired `theme.resources` table from the theme tests and updated the persistence test's doc comment to explain that the table is now an unknown section that must still survive a save. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/render/tests.rs | 1 - src/tui/src/ui/theme/tests.rs | 4 ++-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/tui/src/ui/app/render/tests.rs b/src/tui/src/ui/app/render/tests.rs index f7aed07a8..9bf860e38 100644 --- a/src/tui/src/ui/app/render/tests.rs +++ b/src/tui/src/ui/app/render/tests.rs @@ -274,5 +274,4 @@ fn an_empty_background_keeps_the_terminal_colour() { ..Default::default() }); assert_eq!(theme.background, Color::Reset); - assert_eq!(theme.resources.main_bg, Color::Reset); } diff --git a/src/tui/src/ui/theme/tests.rs b/src/tui/src/ui/theme/tests.rs index af8f29917..6d9da4b9e 100644 --- a/src/tui/src/ui/theme/tests.rs +++ b/src/tui/src/ui/theme/tests.rs @@ -35,7 +35,6 @@ fn from_config_falls_back_per_field() { attention_blink: Some(false), attention_blink_seconds: None, background: None, - resources: None, }; let t = Theme::from_config(&cfg); assert_eq!(t.primary, Color::Rgb(0x12, 0x34, 0x56)); @@ -163,7 +162,8 @@ fn persist_theme_preserves_unrelated_sections() { } /// Saving Appearance rewrites only the keys it owns: a hand-set `background` -/// and the `[theme.resources]` table survive it. +/// and a table it does not know — here the retired `[theme.resources]`, still +/// in older configs — survive it. #[test] fn persist_theme_keeps_theme_keys_it_does_not_own() { let dir = tempfile::tempdir().unwrap(); From 5df10936fb66d6f0a7f9a63c54409215eb1da770 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:06:07 +0000 Subject: [PATCH 41/60] feat(tui): add tests for btop ui Add a test module covering the btop UI rendering so its behaviour is verified and regressions are caught. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/btop/tests.rs | 185 +++++++++++++++++++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 src/tui/src/ui/btop/tests.rs diff --git a/src/tui/src/ui/btop/tests.rs b/src/tui/src/ui/btop/tests.rs new file mode 100644 index 000000000..df0d6ea5e --- /dev/null +++ b/src/tui/src/ui/btop/tests.rs @@ -0,0 +1,185 @@ +//! The pure halves of the btop pane: event encoding, the screen blit, and the +//! agent table built from classified processes. + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; +use medulla::resources::agents::{AgentKind, AgentOrigin, AgentProcess, ProcessUsage}; +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::style::{Color, Modifier}; + +use super::feed::tags; +use super::input::{key_bytes, mouse_bytes}; +use super::render::blit; + +fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent { + KeyEvent::new(code, modifiers) +} + +#[test] +fn keys_encode_as_the_bytes_an_xterm_sends() { + let none = KeyModifiers::NONE; + assert_eq!(key_bytes(key(KeyCode::Char('A'), none)), Some(b"A".to_vec())); + assert_eq!(key_bytes(key(KeyCode::Char('é'), none)), Some("é".as_bytes().to_vec())); + assert_eq!(key_bytes(key(KeyCode::Enter, none)), Some(b"\n".to_vec())); + assert_eq!(key_bytes(key(KeyCode::Esc, none)), Some(b"\x1b".to_vec())); + assert_eq!(key_bytes(key(KeyCode::Up, none)), Some(b"\x1b[A".to_vec())); + assert_eq!(key_bytes(key(KeyCode::Left, none)), Some(b"\x1b[D".to_vec())); + assert_eq!(key_bytes(key(KeyCode::PageDown, none)), Some(b"\x1b[6~".to_vec())); + assert_eq!(key_bytes(key(KeyCode::Delete, none)), Some(b"\x1b[3~".to_vec())); + assert_eq!(key_bytes(key(KeyCode::BackTab, none)), Some(b"\x1b[Z".to_vec())); + assert_eq!(key_bytes(key(KeyCode::F(1), none)), Some(b"\x1bOP".to_vec())); + assert_eq!(key_bytes(key(KeyCode::F(12), none)), Some(b"\x1b[24~".to_vec())); + assert_eq!(key_bytes(key(KeyCode::F(13), none)), None); + assert_eq!(key_bytes(key(KeyCode::CapsLock, none)), None); +} + +#[test] +fn control_and_alt_modify_the_encoding() { + // ⌃R is btop's config reload. + assert_eq!( + key_bytes(key(KeyCode::Char('r'), KeyModifiers::CONTROL)), + Some(vec![0x12]) + ); + assert_eq!( + key_bytes(key(KeyCode::Char('R'), KeyModifiers::CONTROL)), + Some(vec![0x12]) + ); + assert_eq!(key_bytes(key(KeyCode::Char('1'), KeyModifiers::CONTROL)), None); + assert_eq!( + key_bytes(key(KeyCode::Char('x'), KeyModifiers::ALT)), + Some(b"\x1bx".to_vec()) + ); +} + +fn mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent { + MouseEvent { + kind, + column, + row, + modifiers: KeyModifiers::NONE, + } +} + +#[test] +fn mouse_events_become_sgr_reports_relative_to_btops_screen() { + let area = Rect::new(10, 2, 80, 20); + let down = MouseEventKind::Down(MouseButton::Left); + // The pane's top-left cell is btop's (1, 1). + assert_eq!( + mouse_bytes(mouse(down, 10, 2), area), + Some(b"\x1b[<0;1;1M".to_vec()) + ); + assert_eq!( + mouse_bytes(mouse(MouseEventKind::Up(MouseButton::Left), 14, 7), area), + Some(b"\x1b[<0;5;6m".to_vec()) + ); + assert_eq!( + mouse_bytes(mouse(MouseEventKind::Drag(MouseButton::Left), 11, 3), area), + Some(b"\x1b[<32;2;2M".to_vec()) + ); + assert_eq!( + mouse_bytes(mouse(MouseEventKind::ScrollUp, 11, 3), area), + Some(b"\x1b[<64;2;2M".to_vec()) + ); + assert_eq!( + mouse_bytes(mouse(MouseEventKind::ScrollDown, 11, 3), area), + Some(b"\x1b[<65;2;2M".to_vec()) + ); +} + +#[test] +fn mouse_events_outside_btop_or_unused_by_it_are_not_sent() { + let area = Rect::new(10, 2, 80, 20); + let down = MouseEventKind::Down(MouseButton::Left); + // The tab bar above the pane, and just past its right and bottom edges. + assert_eq!(mouse_bytes(mouse(down, 10, 1), area), None); + assert_eq!(mouse_bytes(mouse(down, 90, 5), area), None); + assert_eq!(mouse_bytes(mouse(down, 20, 22), area), None); + assert_eq!( + mouse_bytes(mouse(MouseEventKind::Down(MouseButton::Right), 20, 5), area), + None + ); + assert_eq!(mouse_bytes(mouse(MouseEventKind::Moved, 20, 5), area), None); +} + +#[test] +fn the_blit_copies_glyphs_and_colours_cell_for_cell() { + let mut parser = vt100::Parser::new(3, 10, 0); + // A truecolour bold "cpu" at (1,2), an inverse cell, and a wide glyph. + parser.process(b"\x1b[2;3H\x1b[1;38;2;1;2;3mcpu\x1b[0m\x1b[3;1H\x1b[7mX\x1b[0m\x1b[3;4H\xe2\x96\x88\xe7\x95\x8c"); + let area = Rect::new(5, 1, 10, 3); + let mut buf = Buffer::empty(Rect::new(0, 0, 20, 5)); + blit(parser.screen(), &mut buf, area); + + let c = &buf[(5 + 2, 1 + 1)]; + assert_eq!(c.symbol(), "c"); + assert_eq!(c.fg, Color::Rgb(1, 2, 3)); + assert!(c.modifier.contains(Modifier::BOLD)); + assert_eq!(buf[(5 + 4, 2)].symbol(), "u"); + // Blank emulator cells become spaces, not stale buffer content. + assert_eq!(buf[(5, 1)].symbol(), " "); + // Inverse swaps colours rather than relying on REVERSED. + let inverse = &buf[(5, 3)]; + assert_eq!(inverse.symbol(), "X"); + assert!(!inverse.modifier.contains(Modifier::REVERSED)); + // The wide glyph takes two columns; the second is left to it. + assert_eq!(buf[(5 + 3, 3)].symbol(), "█"); + assert_eq!(buf[(5 + 4, 3)].symbol(), "界"); + assert_eq!(buf[(5 + 5, 3)].symbol(), ""); + // Nothing is drawn outside the area. + assert_eq!(buf[(4, 1)].symbol(), " "); + assert_eq!(buf[(15, 1)].symbol(), " "); +} + +#[test] +fn the_blit_clips_to_the_frame() { + let parser = vt100::Parser::new(5, 5, 0); + let mut buf = Buffer::empty(Rect::new(0, 0, 3, 3)); + // An area hanging off the buffer's edge must not panic. + blit(parser.screen(), &mut buf, Rect::new(1, 1, 5, 5)); +} + +fn agent(pid: Option, kind: AgentKind, origin: AgentOrigin) -> AgentProcess { + AgentProcess { + pid, + kind, + origin, + exe: None, + cwd: None, + started_at_secs: 0, + runtime_secs: 0, + usage: ProcessUsage::default(), + children: Vec::new(), + } +} + +#[test] +fn classified_agents_become_btops_agent_table() { + let table = tags( + &[ + agent(Some(41), AgentKind::Claude, AgentOrigin::External), + agent( + Some(42), + AgentKind::Codex, + AgentOrigin::Session { id: "s1".into() }, + ), + agent(Some(43), AgentKind::Opencode, AgentOrigin::Headless), + agent(None, AgentKind::EmbeddedOpenhuman, AgentOrigin::Headless), + ], + 7, + ); + let rows: Vec<_> = table + .iter() + .map(|t| (t.pid, t.label.as_str(), t.launched)) + .collect(); + assert_eq!( + rows, + vec![ + (41, "Claude", false), + (42, "Codex", true), + (43, "OpenCode", true), + // In-process: tagged on Medulla's own pid. + (7, "OpenHuman", true), + ] + ); +} From 0e6fee60de6367da169c58bb2e09697a3dac4435 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:06:25 +0000 Subject: [PATCH 42/60] feat(tui): add tests for app resources Add unit tests covering the app resources module to verify its behaviour and guard against regressions. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/resources/tests.rs | 107 ++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/tui/src/ui/app/resources/tests.rs diff --git a/src/tui/src/ui/app/resources/tests.rs b/src/tui/src/ui/app/resources/tests.rs new file mode 100644 index 000000000..be3e69d3a --- /dev/null +++ b/src/tui/src/ui/app/resources/tests.rs @@ -0,0 +1,107 @@ +//! The Resources tab against the real, embedded btop. +//! +//! btop runs once per process and every `App` shares it, so the lifecycle is +//! one test walked end to end; key routing that never reaches btop is tested +//! on its own. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; +use medulla::backend::{Backend, MockBackend}; +use medulla::config::LoadedConfig; +use ratatui::backend::TestBackend; +use ratatui::Terminal; + +use crate::ui::app::types::tab_pos; +use crate::ui::app::App; + +fn app_on_resources() -> App { + let backend: Arc = Arc::new(MockBackend::new()); + let mut app = App::new(backend, LoadedConfig::defaults("medulla.tui.json".into())); + app.tab_index = tab_pos("Resources"); + app +} + +fn press(app: &mut App, code: KeyCode, modifiers: KeyModifiers) { + app.on_key(KeyEvent::new(code, modifiers)); +} + +/// Redraw until the screen satisfies `done`, as the event loop would on +/// btop's wakes; false if it never does. +fn draw_until(app: &mut App, terminal: &mut Terminal, done: impl Fn(&App, &str) -> bool) -> bool { + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline { + terminal.draw(|f| app.draw(f)).expect("draw"); + let screen = crate::ui::btop::pane().contents(); + if done(app, &screen) { + return true; + } + std::thread::sleep(Duration::from_millis(25)); + } + false +} + +#[test] +fn tab_switching_and_global_chords_stay_medullas() { + let mut app = app_on_resources(); + press(&mut app, KeyCode::Tab, KeyModifiers::NONE); + assert_ne!(app.tab(), "Resources", "Tab must still switch tabs"); + + let mut app = app_on_resources(); + press(&mut app, KeyCode::BackTab, KeyModifiers::SHIFT); + assert_ne!(app.tab(), "Resources", "Shift-Tab must still switch tabs"); + + let mut app = app_on_resources(); + press(&mut app, KeyCode::Char('c'), KeyModifiers::CONTROL); + assert!(app.should_quit, "⌃C must still quit"); +} + +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[test] +fn the_tab_runs_btop_focused_on_agents_and_q_returns_to_sessions() { + let mut app = app_on_resources(); + let mut terminal = Terminal::new(TestBackend::new(160, 48)).expect("terminal"); + + // btop draws its boxes, with the process box narrowed to coding agents. + assert!( + draw_until(&mut app, &mut terminal, |_, screen| screen.contains("cpu") + && screen.contains("agents")), + "btop never drew: {}", + crate::ui::btop::pane().contents() + ); + assert!(crate::ui::btop::pane().running()); + // What btop drew is what the frame shows, below the tab bar. + let frame: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(|cell| cell.symbol()) + .collect(); + assert!(frame.contains("agents")); + + // `A` is btop's agents toggle; the title follows it. + press(&mut app, KeyCode::Char('A'), KeyModifiers::NONE); + assert!( + draw_until(&mut app, &mut terminal, |_, screen| screen.contains("proc") + && !screen.contains("agents")), + "A did not switch to all processes" + ); + press(&mut app, KeyCode::Char('A'), KeyModifiers::NONE); + assert!(draw_until(&mut app, &mut terminal, |_, screen| screen + .contains("agents"))); + + // btop's quit is "leave the tab", not "end Medulla". + press(&mut app, KeyCode::Char('q'), KeyModifiers::NONE); + assert!( + draw_until(&mut app, &mut terminal, |app, _| app.tab() == "Sessions"), + "q did not return to Sessions" + ); + assert!(!app.should_quit); + // Off screen, btop is paused, and coming back resumes it. + assert!(!crate::ui::btop::pane().visible); + app.tab_index = tab_pos("Resources"); + assert!(draw_until(&mut app, &mut terminal, |_, _| crate::ui::btop::pane() + .visible)); +} From 7485d7c15a2fa5b6160ed9b8f322dc01ecff2602 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:07:02 +0000 Subject: [PATCH 43/60] fix(tui): hide resources pane when leaving it The resources pane is now hidden as soon as it reports that the user is leaving, so it no longer stays visible while the tab switches to Sessions. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/resources/mod.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/tui/src/ui/app/resources/mod.rs b/src/tui/src/ui/app/resources/mod.rs index 43e8f25b6..585698188 100644 --- a/src/tui/src/ui/app/resources/mod.rs +++ b/src/tui/src/ui/app/resources/mod.rs @@ -24,6 +24,9 @@ impl App { pane.show(&config_dir, area); let leave = pane.pump(); pane.render(f.buffer_mut(), area); + if leave { + pane.hide(); + } drop(pane); if leave { self.tab_index = tab_pos("Sessions"); From 4628fefce35260bc9015ac39893ea4c34f62e71d Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:08:05 +0000 Subject: [PATCH 44/60] fix(btop): use escape sequences supported by the host terminal emulator The cursor positioning, save, and restore sequences were switched from HVP, CSI s, and CSI u to CUP, DECSC, and DECRC, and the clear sequence now homes the cursor with CUP, because the host's vt100 emulator does not implement the former forms. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- vendor/btop/src/btop_tools.cpp | 2 +- vendor/btop/src/btop_tools.hpp | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/vendor/btop/src/btop_tools.cpp b/vendor/btop/src/btop_tools.cpp index 113589605..48613bfe6 100644 --- a/vendor/btop/src/btop_tools.cpp +++ b/vendor/btop/src/btop_tools.cpp @@ -699,7 +699,7 @@ const string Term::hide_cursor = Fx::e + "?25l"; const string Term::show_cursor = Fx::e + "?25h"; const string Term::alt_screen = Fx::e + "?1049h"; const string Term::normal_screen = Fx::e + "?1049l"; -const string Term::clear = Fx::e + "2J" + Fx::e + "0;0f"; +const string Term::clear = Fx::e + "2J" + Fx::e + "H"; const string Term::clear_end = Fx::e + "0J"; const string Term::clear_begin = Fx::e + "1J"; const string Term::mouse_on = Fx::e + "?1002h" + Fx::e + "?1015h" + Fx::e + "?1006h"; //? Enable reporting of mouse position on click and release diff --git a/vendor/btop/src/btop_tools.hpp b/vendor/btop/src/btop_tools.hpp index 3249e8f2e..ef1a20c51 100644 --- a/vendor/btop/src/btop_tools.hpp +++ b/vendor/btop/src/btop_tools.hpp @@ -104,7 +104,9 @@ namespace Fx { //* Collection of escape codes and functions for cursor manipulation namespace Mv { //* Move cursor to , - inline string to(int line, int col) { return Fx::e + to_string(line) + ';' + to_string(col) + 'f'; } + //? Medulla: CUP ('H') rather than upstream's equivalent HVP ('f'), which the + //? host's vt100 emulator does not implement. + inline string to(int line, int col) { return Fx::e + to_string(line) + ';' + to_string(col) + 'H'; } //* Move cursor right columns inline string r(int x) { return Fx::e + to_string(x) + 'C'; } @@ -118,11 +120,11 @@ namespace Mv { //* Move cursor down x lines inline string d(int x) { return Fx::e + to_string(x) + 'B'; } - //* Save cursor position - const string save = Fx::e + "s"; + //* Save cursor position (Medulla: DECSC, which the host emulator implements; CSI s is not) + const string save = "\x1b" "7"; - //* Restore saved cursor position - const string restore = Fx::e + "u"; + //* Restore saved cursor position (Medulla: DECRC, for the same reason) + const string restore = "\x1b" "8"; } //* Collection of escape codes and functions for terminal manipulation From 6ad7a6f96d0a5dd69cae2cf30ece0e954efbf953 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:08:48 +0000 Subject: [PATCH 45/60] test(tui): assert btop boxes honour cursor positioning Extend the btop tab test to check that the emulator applies btop's absolute cursor moves, verifying the cpu box title sits on the first row and the frame stays on the left edge. Without this, boxes would run together and the test would still pass. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/resources/tests.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/tui/src/ui/app/resources/tests.rs b/src/tui/src/ui/app/resources/tests.rs index be3e69d3a..57b971d20 100644 --- a/src/tui/src/ui/app/resources/tests.rs +++ b/src/tui/src/ui/app/resources/tests.rs @@ -71,6 +71,19 @@ fn the_tab_runs_btop_focused_on_agents_and_q_returns_to_sessions() { crate::ui::btop::pane().contents() ); assert!(crate::ui::btop::pane().running()); + // btop places every box absolutely; if the emulator ignored its cursor + // moves the boxes would run together instead of the cpu box's title + // sitting on the first row and its frame on the first column. + let contents = crate::ui::btop::pane().contents(); + let mut rows = contents.lines(); + assert!( + rows.next().is_some_and(|row| row.contains("cpu") && row.starts_with('╭')), + "cpu box is not at the top: {contents}" + ); + assert!( + rows.take(5).all(|row| row.starts_with('│')), + "box frame is not on the left edge: {contents}" + ); // What btop drew is what the frame shows, below the tab bar. let frame: String = terminal .backend() From 37cf43da7f5421534c4788cb5e6a413c088d3ead Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:10:51 +0000 Subject: [PATCH 46/60] test(tui): tighten btop cpu box placement assertions Extract a helper that checks the cpu box frame and title on the first row, and wait for that frame rather than the bare word "cpu", which the agents box's sort label also contains. The left-edge check now skips the title row explicitly instead of relying on the consumed iterator. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/resources/tests.rs | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/tui/src/ui/app/resources/tests.rs b/src/tui/src/ui/app/resources/tests.rs index 57b971d20..c40e03241 100644 --- a/src/tui/src/ui/app/resources/tests.rs +++ b/src/tui/src/ui/app/resources/tests.rs @@ -57,6 +57,14 @@ fn tab_switching_and_global_chords_stay_medullas() { assert!(app.should_quit, "⌃C must still quit"); } +/// Whether btop's cpu box frame and title open the screen's first row. +fn cpu_box_on_top(screen: &str) -> bool { + screen + .lines() + .next() + .is_some_and(|row| row.starts_with('╭') && row.contains("cpu┌")) +} + #[cfg(any(target_os = "linux", target_os = "macos"))] #[test] fn the_tab_runs_btop_focused_on_agents_and_q_returns_to_sessions() { @@ -64,24 +72,20 @@ fn the_tab_runs_btop_focused_on_agents_and_q_returns_to_sessions() { let mut terminal = Terminal::new(TestBackend::new(160, 48)).expect("terminal"); // btop draws its boxes, with the process box narrowed to coding agents. + // The cpu box waits for its first sample, so wait for its frame — not just + // the word, which the agents box's sort label also contains. assert!( - draw_until(&mut app, &mut terminal, |_, screen| screen.contains("cpu") + draw_until(&mut app, &mut terminal, |_, screen| cpu_box_on_top(screen) && screen.contains("agents")), "btop never drew: {}", crate::ui::btop::pane().contents() ); assert!(crate::ui::btop::pane().running()); - // btop places every box absolutely; if the emulator ignored its cursor - // moves the boxes would run together instead of the cpu box's title - // sitting on the first row and its frame on the first column. + // btop places every box absolutely; had the emulator dropped its cursor + // moves the boxes would run together instead of framing the left edge. let contents = crate::ui::btop::pane().contents(); - let mut rows = contents.lines(); - assert!( - rows.next().is_some_and(|row| row.contains("cpu") && row.starts_with('╭')), - "cpu box is not at the top: {contents}" - ); assert!( - rows.take(5).all(|row| row.starts_with('│')), + contents.lines().skip(1).take(5).all(|row| row.starts_with('│')), "box frame is not on the left edge: {contents}" ); // What btop drew is what the frame shows, below the tab bar. From 5f9b25a30aeb5c0e9b754a8359d90ecbfa600bf9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:11:33 +0000 Subject: [PATCH 47/60] chore(tui): use a shared scratch dir for btop config without a home Apps without a medulla home now resolve their btop config to a single fixed scratch directory instead of a per-process one, so tests and other home-less runs reuse the same location. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/src/ui/app/resources/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tui/src/ui/app/resources/mod.rs b/src/tui/src/ui/app/resources/mod.rs index 585698188..a870cf850 100644 --- a/src/tui/src/ui/app/resources/mod.rs +++ b/src/tui/src/ui/app/resources/mod.rs @@ -59,11 +59,11 @@ impl App { /// Where btop keeps `btop.conf` and its log: beside Medulla's own state /// rather than in the operator's `~/.config/btop`, so Medulla's defaults /// (the agents box, tree view) never rewrite a standalone btop's config. - /// An app with no home (a test) gets a per-process scratch directory. + /// An app with no home (a test) shares one scratch directory. fn btop_config_dir(&self) -> PathBuf { match &self.medulla_home { Some(home) => home.join("btop"), - None => std::env::temp_dir().join(format!("medulla-btop-{}", std::process::id())), + None => std::env::temp_dir().join("medulla-btop"), } } } From 854f3de14657ba5087c46ff1b45552d99fdd8041 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:12:22 +0000 Subject: [PATCH 48/60] ci: add macOS btop build job and install g++-14 for native deps Adds a macOS CI job that builds and tests the vendored btop crate so Apple-clang issues surface on pull requests instead of at release time. The native-deps action now installs g++-14 because the vendored btop requires C++23 ranges support that Ubuntu 24.04's default g++ 13 lacks. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/actions/native-deps/action.yml | 5 ++++- .github/workflows/ci.yml | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/.github/actions/native-deps/action.yml b/.github/actions/native-deps/action.yml index fd26e7b0c..5fefae5ba 100644 --- a/.github/actions/native-deps/action.yml +++ b/.github/actions/native-deps/action.yml @@ -21,9 +21,12 @@ runs: # in the graph on a headless build too and their build scripts fail # without these. Not needed by medulla itself. # - libgit2 needs nothing: libgit2-sys builds vendored C via cc. + # - g++-14: the vendored btop (`src/btop`, the Resources tab) is C++23 and + # needs libstdc++ 14's `std::ranges::to`. Ubuntu 24.04 defaults to + # g++ 13; `src/btop/build.rs` picks `g++-14` when the default is older. - name: Install native build dependencies shell: bash run: | sudo apt-get update sudo apt-get install -y --no-install-recommends \ - pkg-config libssl-dev libx11-dev libxi-dev libxtst-dev libxdo-dev + pkg-config libssl-dev libx11-dev libxi-dev libxtst-dev libxdo-dev g++-14 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dd6a3dd39..72db98f61 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -287,6 +287,25 @@ jobs: if: always() run: sccache --show-stats + # The Resources tab compiles the vendored btop (C++23) into the binary, and + # the macOS release build is the only other place that compiler meets it. + # Building just that crate here surfaces an Apple-clang gap on the pull + # request rather than at release time, without a full macOS workspace build. + btop-macos: + name: btop (macOS) + runs-on: macos-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + submodules: false + + - uses: dtolnay/rust-toolchain@stable + + - name: Test the embedded btop + run: cargo test --locked -p medulla-btop + # ── end-to-end harness ───────────────────────────────────────────────────── # Does this change need the docker/tmux harness run at all? # From 0614b8550b8262954789ff1ea90965a7bbb97ae5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:12:29 +0000 Subject: [PATCH 49/60] ci: initialize submodules before embedded btop tests Cargo reads every workspace member's manifest, including path dependencies, even when building with `-p`, so the submodules must be checked out before the embedded btop test job runs. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/workflows/ci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 72db98f61..170659b82 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -301,6 +301,11 @@ jobs: persist-credentials: false submodules: false + # Cargo reads every workspace member's manifest, path deps included, + # even for `-p`. + - name: Initialize submodules + run: bash scripts/init-submodules.sh + - uses: dtolnay/rust-toolchain@stable - name: Test the embedded btop From d9bedbf091e106c4cfa58330e0de528e4fa757f0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:12:47 +0000 Subject: [PATCH 50/60] fix(release): include medulla-btop in version bump packages The release script now updates the lockfile entry for medulla-btop alongside the other workspace members, so its version stays in sync when bumping the shared version. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- scripts/release/bump-version.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/release/bump-version.sh b/scripts/release/bump-version.sh index 066f6ff4f..07f0f0a00 100755 --- a/scripts/release/bump-version.sh +++ b/scripts/release/bump-version.sh @@ -18,7 +18,7 @@ root="${2:-.}" cargo_toml="${root}/Cargo.toml" cargo_lock="${root}/Cargo.lock" # Workspace members whose lockfile entries carry the shared version. -packages=(medulla medulla-link medulla-tui) +packages=(medulla medulla-btop medulla-link medulla-tui) case "$bump" in patch | minor | major) ;; From 5a4531fadec4cbf26cda5d2ffc0731a0e08062cb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:12:56 +0000 Subject: [PATCH 51/60] test(release): cover medulla-btop in bump-version lockfile fixture The fixture lockfile now includes a medulla-btop package and the expected version count is raised to four, so the test exercises the newly added workspace crate. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- scripts/release/test-bump-version.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/scripts/release/test-bump-version.sh b/scripts/release/test-bump-version.sh index cedc2fefb..ed124ae0c 100755 --- a/scripts/release/test-bump-version.sh +++ b/scripts/release/test-bump-version.sh @@ -23,6 +23,10 @@ EOF name = "medulla" version = "0.14.1" +[[package]] +name = "medulla-btop" +version = "0.14.1" + [[package]] name = "medulla-link" version = "0.14.1" @@ -46,7 +50,7 @@ expect_bump() { failures=$((failures + 1)) return fi - if [[ "$(grep -c "version = \"${want}\"" "$work/Cargo.lock")" != 3 ]] || + if [[ "$(grep -c "version = \"${want}\"" "$work/Cargo.lock")" != 4 ]] || ! grep -q '^name = "other"$' "$work/Cargo.lock" || [[ "$(grep -A1 '^name = "other"$' "$work/Cargo.lock" | tail -1)" != 'version = "0.14.1"' ]]; then echo "FAIL ${kind}: lockfile not rewritten for exactly the workspace packages" From 770056bca3a8add2dd070412196e6c35634ff782 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:13:17 +0000 Subject: [PATCH 52/60] docs(agents): document vendored btop and medulla-btop crate Expands the repository layout notes to cover the vendored C++ btop source and the medulla-btop crate that compiles and embeds it, plus the TUI host side behind the Resources tab, so contributors know where the btop integration lives and that its patches are tracked in vendor/btop/MEDULLA.md. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- AGENTS.md | 3 ++- vendor/btop/MEDULLA.md | 50 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 vendor/btop/MEDULLA.md diff --git a/AGENTS.md b/AGENTS.md index 08007b39d..be43b79e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,8 @@ This repository is a two-crate Cargo workspace: the `medulla` SDK library at `sr - `src/tui/src/ui/` owns ratatui state, rendering, input, and theming; `src/tui/src/cli.rs` owns argument parsing; `src/tui/src/main.rs` owns process wiring. - `src/sdk/tests/` and `src/tui/tests/` contain feature and mocked end-to-end suites; reusable stand-ins live in `src/sdk/tests/support/` (the app crate's tests reach them via `#[path]`). - `src/sdk/src/agent/` is the local agent: a `tinyagents` harness plus Medulla's own tool surface (shell, filesystem), used by the in-process daemon provider. -- `vendor/` holds the three vendored crates (`tinyagents`, `tinyflows`, `tinyhumans-sdk`), excluded from the workspace. Avoid unrelated edits there. +- `vendor/` holds the three vendored crates (`tinyagents`, `tinyflows`, `tinyhumans-sdk`), excluded from the workspace, and the vendored C++ `btop` (`vendor/btop`, plain source, not a submodule). Avoid unrelated edits there; `vendor/btop/MEDULLA.md` lists every Medulla patch to btop. +- `src/btop/` is the `medulla-btop` crate: its `build.rs` compiles `vendor/btop` and its safe API runs btop embedded. `src/tui/src/ui/btop/` is the host side (emulator, input encoding, agent feed) behind the Resources tab. - `target/` and `.medulla-state/` are generated or local runtime data; never commit them. ## Build, Test, and Development Commands diff --git a/vendor/btop/MEDULLA.md b/vendor/btop/MEDULLA.md new file mode 100644 index 000000000..8576f726b --- /dev/null +++ b/vendor/btop/MEDULLA.md @@ -0,0 +1,50 @@ +# btop, vendored for Medulla + +Upstream: [aristocratos/btop](https://github.com/aristocratos/btop) **v1.4.8**, +Apache-2.0 (`LICENSE`). Imported unmodified in the first commit that adds this +directory, so `git diff -- vendor/btop` is exactly the list below. + +Kept: `src/` shared sources, the Linux and macOS collectors, and the bundled +`include/fmt` and `include/widechar_width.hpp`. Dropped: the CLI (`btop_cli.*`, +`main.cpp`), the BSD collectors, GPU support (`intel_gpu_top`, NVML/ROCm), the +CMake/Make build, themes, docs and tests. `src/btop/build.rs` (the +`medulla-btop` crate) is the build. + +## Embedding: btop without a terminal of its own + +btop runs on a thread inside Medulla. Everything that assumed it owned the +process's terminal goes through `src/btop_embed.{hpp,cpp}` instead, with the C +ABI in `include/medulla_btop.h`. + +| Upstream | Embedded | +|---|---| +| `btop_main()` parses argv, sets up the tty and signal handlers, loops | `btop_embed_main()` (end of `btop.cpp`): same scheduling loop, no argv, no signals, pauses while the host hides it | +| `cout << …` | `Embed::write()` into a buffer the host drains | +| `Term::init/refresh/restore` use `tcsetattr`/`TIOCGWINSZ` | size comes from `medulla_btop_resize()`; no tty is touched | +| `Input::poll` reads stdin with `pselect` | `Embed::wait_input()` pops one host-queued key chunk | +| `Input::interrupt` sends `SIGUSR1` to the process | condition-variable notify | +| `q` / menu Quit / size-error `q` call `clean_quit(0)` → `quick_exit` | `Embed::request_leave()`; the host leaves the tab | +| `clean_quit(1)` on fatal errors | throws `Embed::Fatal`, caught on btop's thread; the host shows the message | +| `⌃R` sends `SIGUSR2` | sets `Global::reload_conf` | +| config/log in `$XDG_CONFIG_HOME/btop`, `$XDG_STATE_HOME` | `/btop.conf`, `btop.log`, `themes/` chosen by the host | +| `setlocale(LC_ALL, …)` | `LC_CTYPE` only — the locale is the host's too | +| `Mv::to` emits HVP (`CSI y;x f`), `Mv::save/restore` emit `CSI s/u` | CUP (`CSI y;x H`) and DECSC/DECRC (`ESC 7/8`): the host's `vt100` emulator implements those, not the former | + +## Agent focus + +- `proc_agents` (config, default **on**; `A` toggles, also in Options): the + process box shows only the coding-agent processes the host names through + `medulla_btop_set_agents()` and their descendants, titled `agents`. In tree + view each agent is a root. +- In that mode the `User` column is `Agent`: the agent's name (`◆` and the + highlight colour when Medulla launched it) on its own process, `↳ name` + dimmed on its descendants. An empty box says why and how to see everything. +- `Proc::refresh_agents/passes_filter/agent_of/box_title` (`btop_shared.cpp`) + hold the logic; both collectors call it where they apply the text filter. +- Default `proc_tree` is **on**. + +## Updating upstream + +Import the new release over a scratch branch, commit it unmodified, then replay +the diff above. The embed seam touches few lines per file by design; the agent +hooks are the two-line changes in each `btop_collect.cpp` filter block. From 10590f4b6f42e22486de10db2ab4048d37238ac5 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:13:24 +0000 Subject: [PATCH 53/60] docs(developing): document c++23 compiler requirement for btop Added a note to the development guide explaining that building requires a C++23 compiler because the Resources tab compiles btop from vendor/btop, and listed the minimum GCC, Clang, and Xcode versions along with the Windows exception. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- DEVELOPING.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/DEVELOPING.md b/DEVELOPING.md index 946d5ab62..19b52560f 100644 --- a/DEVELOPING.md +++ b/DEVELOPING.md @@ -30,6 +30,12 @@ cargo clippy --all-targets -- -D warnings cargo fmt --check ``` +Building needs a C++23 compiler as well as Rust: the Resources tab is btop, +compiled into the binary from `vendor/btop` by `src/btop/build.rs`. Use GCC 14+ +or Clang 18+ on Linux (on Ubuntu 24.04, `apt install g++-14` — the build picks +it up when the default `g++` is older) and Xcode 16+ on macOS. Windows builds +without it, and the tab says btop is unavailable there. + Run tests, Clippy, and formatting before pushing. See [Contributing](https://tinyhumans.gitbook.io/medulla/developers/contributing) for the full loop and the release process. From 4e47f506f0060e0d4422b884f1f061cac3ce0c1e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:13:46 +0000 Subject: [PATCH 54/60] test(config): cover loading configs with retired resources tables Adds a test asserting that a config still containing the old `[resources]` and `[theme.resources]` tables parses successfully, since those tables are now ignored after the Resources tab moved to btop. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/sdk/src/config/types_tests.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/sdk/src/config/types_tests.rs b/src/sdk/src/config/types_tests.rs index 174814c23..07ca3a3a3 100644 --- a/src/sdk/src/config/types_tests.rs +++ b/src/sdk/src/config/types_tests.rs @@ -43,6 +43,29 @@ fn defaults_are_applied() { assert!(cfg.appearance.show_session_titles); } +/// The Resources tab used to read `[resources]` and `[theme.resources]`; it is +/// btop now, configured in btop's own menu. A config written before that must +/// still load, with the retired tables simply ignored. +#[test] +fn a_config_with_the_retired_resources_tables_still_loads() { + let cfg: TuiConfig = toml::from_str( + r#" + [theme] + primary = "red" + + [theme.resources] + cpuBox = "#556d59" + + [resources] + updateMs = 2000 + shown = ["cpu", "mem"] + "#, + ) + .expect("a config from before the btop Resources tab parses"); + + assert_eq!(cfg.theme.primary.as_deref(), Some("red")); +} + #[test] fn appearance_session_titles_can_be_hidden() { let cfg: TuiConfig = From afa7ba4da373fe2fdd53678b58834a97864ad2ff Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:14:01 +0000 Subject: [PATCH 55/60] test(config): use raw string delimiters that survive embedded quotes The TOML fixture in the retired-resources-tables test now uses double-hash raw string delimiters so the embedded quoted values no longer terminate the literal early. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/sdk/src/config/types_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sdk/src/config/types_tests.rs b/src/sdk/src/config/types_tests.rs index 07ca3a3a3..274a0150d 100644 --- a/src/sdk/src/config/types_tests.rs +++ b/src/sdk/src/config/types_tests.rs @@ -49,7 +49,7 @@ fn defaults_are_applied() { #[test] fn a_config_with_the_retired_resources_tables_still_loads() { let cfg: TuiConfig = toml::from_str( - r#" + r##" [theme] primary = "red" @@ -59,7 +59,7 @@ fn a_config_with_the_retired_resources_tables_still_loads() { [resources] updateMs = 2000 shown = ["cpu", "mem"] - "#, + "##, ) .expect("a config from before the btop Resources tab parses"); From 51a1d815492c52604f95370d81b2f3588f134db0 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:14:24 +0000 Subject: [PATCH 56/60] chore: apply rustfmt formatting across btop and tui modules Reformatted long expressions, import lists, and closures to satisfy rustfmt, with no behavioural changes. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/btop/build.rs | 17 +++++++-- src/btop/src/handle.rs | 4 +- src/btop/src/tests.rs | 3 +- src/sdk/src/config/mod.rs | 5 +-- src/tui/src/ui/app/render/settings/mod.rs | 4 +- src/tui/src/ui/app/resources/tests.rs | 17 +++++++-- src/tui/src/ui/app/state.rs | 1 - src/tui/src/ui/btop/tests.rs | 45 ++++++++++++++++++----- 8 files changed, 70 insertions(+), 26 deletions(-) diff --git a/src/btop/build.rs b/src/btop/build.rs index 76c385d7b..145da09c2 100644 --- a/src/btop/build.rs +++ b/src/btop/build.rs @@ -61,7 +61,10 @@ fn main() { println!("cargo:rerun-if-changed={}", path.display()); build.file(path); } - for header in watched_headers(&src).into_iter().chain([root.join("include/medulla_btop.h")]) { + for header in watched_headers(&src) + .into_iter() + .chain([root.join("include/medulla_btop.h")]) + { println!("cargo:rerun-if-changed={}", header.display()); } build.compile("medulla_btop"); @@ -78,12 +81,20 @@ fn main() { fn modern_gxx() -> Option<&'static str> { let major = |cmd: &str| -> Option { let out = Command::new(cmd).arg("-dumpversion").output().ok()?; - String::from_utf8(out.stdout).ok()?.trim().split('.').next()?.parse().ok() + String::from_utf8(out.stdout) + .ok()? + .trim() + .split('.') + .next()? + .parse() + .ok() }; if major("g++").is_some_and(|v| v >= 14) { return None; } - ["g++-15", "g++-14"].into_iter().find(|cmd| major(cmd).is_some()) + ["g++-15", "g++-14"] + .into_iter() + .find(|cmd| major(cmd).is_some()) } /// Headers whose edits must rebuild the library. diff --git a/src/btop/src/handle.rs b/src/btop/src/handle.rs index 807f1566c..1ce6ce7ce 100644 --- a/src/btop/src/handle.rs +++ b/src/btop/src/handle.rs @@ -196,9 +196,7 @@ impl Btop { { let mut buf = vec![0u8; 512]; // SAFETY: btop writes at most `buf.len()` bytes, NUL included. - let len = unsafe { - crate::ffi::medulla_btop_error(buf.as_mut_ptr().cast(), buf.len()) - }; + let len = unsafe { crate::ffi::medulla_btop_error(buf.as_mut_ptr().cast(), buf.len()) }; if len == 0 { return None; } diff --git a/src/btop/src/tests.rs b/src/btop/src/tests.rs index 3905c8e2a..0e3187bf5 100644 --- a/src/btop/src/tests.rs +++ b/src/btop/src/tests.rs @@ -35,7 +35,8 @@ fn btop_runs_embedded_and_hands_quit_back_to_the_host() { // It draws its boxes into the virtual terminal, and wakes the host to say so. let mut seen = String::new(); assert!( - drain_until(&btop, &mut seen, |out| out.contains("cpu") && out.contains("mem")), + drain_until(&btop, &mut seen, |out| out.contains("cpu") + && out.contains("mem")), "no boxes drawn: {seen:?}" ); assert!(wakes.load(Ordering::Relaxed) > 0); diff --git a/src/sdk/src/config/mod.rs b/src/sdk/src/config/mod.rs index b1e15661c..026afef4c 100644 --- a/src/sdk/src/config/mod.rs +++ b/src/sdk/src/config/mod.rs @@ -63,8 +63,7 @@ pub use types::{ FavoriteWorkspace, FieldPlacement, FieldVisibility, FleetConfig, HarnessNameStyle, HarnessSection, HookDefaultsConfig, HostSection, HubSection, HubWorkerConfig, LinkConfig, LoadedConfig, McpSection, OnboardingConfig, OpencodeConfig, PathStyle, Peer, - ProviderBudgetConfig, RemoteHostSection, RouterConfig, - RouterProviderConfig, StatusLineConfig, ThemeConfig, TuiConfig, UpdateConfig, WorkflowConfig, - WorkflowsConfig, + ProviderBudgetConfig, RemoteHostSection, RouterConfig, RouterProviderConfig, StatusLineConfig, + ThemeConfig, TuiConfig, UpdateConfig, WorkflowConfig, WorkflowsConfig, }; pub use urls::{backend_base_url, display_host, resolve_forwarder_base_url, PROD_BACKEND_BASE_URL}; diff --git a/src/tui/src/ui/app/render/settings/mod.rs b/src/tui/src/ui/app/render/settings/mod.rs index 59cf23651..b11ca5aaa 100644 --- a/src/tui/src/ui/app/render/settings/mod.rs +++ b/src/tui/src/ui/app/render/settings/mod.rs @@ -17,8 +17,8 @@ use ratatui::Frame; use crate::ui::multi_pane; use super::super::types::{ - App, SP_ACCOUNT, SP_APPEARANCE, SP_CONFIG, SP_FEEDBACK, SP_STATUS_LINE, - SP_SUBSCRIPTIONS, SP_USAGE, + App, SP_ACCOUNT, SP_APPEARANCE, SP_CONFIG, SP_FEEDBACK, SP_STATUS_LINE, SP_SUBSCRIPTIONS, + SP_USAGE, }; mod account; diff --git a/src/tui/src/ui/app/resources/tests.rs b/src/tui/src/ui/app/resources/tests.rs index c40e03241..347135569 100644 --- a/src/tui/src/ui/app/resources/tests.rs +++ b/src/tui/src/ui/app/resources/tests.rs @@ -29,7 +29,11 @@ fn press(app: &mut App, code: KeyCode, modifiers: KeyModifiers) { /// Redraw until the screen satisfies `done`, as the event loop would on /// btop's wakes; false if it never does. -fn draw_until(app: &mut App, terminal: &mut Terminal, done: impl Fn(&App, &str) -> bool) -> bool { +fn draw_until( + app: &mut App, + terminal: &mut Terminal, + done: impl Fn(&App, &str) -> bool, +) -> bool { let deadline = Instant::now() + Duration::from_secs(15); while Instant::now() < deadline { terminal.draw(|f| app.draw(f)).expect("draw"); @@ -85,7 +89,11 @@ fn the_tab_runs_btop_focused_on_agents_and_q_returns_to_sessions() { // moves the boxes would run together instead of framing the left edge. let contents = crate::ui::btop::pane().contents(); assert!( - contents.lines().skip(1).take(5).all(|row| row.starts_with('│')), + contents + .lines() + .skip(1) + .take(5) + .all(|row| row.starts_with('│')), "box frame is not on the left edge: {contents}" ); // What btop drew is what the frame shows, below the tab bar. @@ -119,6 +127,7 @@ fn the_tab_runs_btop_focused_on_agents_and_q_returns_to_sessions() { // Off screen, btop is paused, and coming back resumes it. assert!(!crate::ui::btop::pane().visible); app.tab_index = tab_pos("Resources"); - assert!(draw_until(&mut app, &mut terminal, |_, _| crate::ui::btop::pane() - .visible)); + assert!(draw_until(&mut app, &mut terminal, |_, _| { + crate::ui::btop::pane().visible + })); } diff --git a/src/tui/src/ui/app/state.rs b/src/tui/src/ui/app/state.rs index c6b56cf60..6e493f2cc 100644 --- a/src/tui/src/ui/app/state.rs +++ b/src/tui/src/ui/app/state.rs @@ -183,7 +183,6 @@ impl App { self.device_monitor.inject(snapshot); } - /// Configure Account logout with a testable home; without it, logout reports no writable location. pub fn set_medulla_home(&mut self, home: std::path::PathBuf) { self.medulla_home = Some(home); diff --git a/src/tui/src/ui/btop/tests.rs b/src/tui/src/ui/btop/tests.rs index df0d6ea5e..bf76cb239 100644 --- a/src/tui/src/ui/btop/tests.rs +++ b/src/tui/src/ui/btop/tests.rs @@ -18,17 +18,41 @@ fn key(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent { #[test] fn keys_encode_as_the_bytes_an_xterm_sends() { let none = KeyModifiers::NONE; - assert_eq!(key_bytes(key(KeyCode::Char('A'), none)), Some(b"A".to_vec())); - assert_eq!(key_bytes(key(KeyCode::Char('é'), none)), Some("é".as_bytes().to_vec())); + assert_eq!( + key_bytes(key(KeyCode::Char('A'), none)), + Some(b"A".to_vec()) + ); + assert_eq!( + key_bytes(key(KeyCode::Char('é'), none)), + Some("é".as_bytes().to_vec()) + ); assert_eq!(key_bytes(key(KeyCode::Enter, none)), Some(b"\n".to_vec())); assert_eq!(key_bytes(key(KeyCode::Esc, none)), Some(b"\x1b".to_vec())); assert_eq!(key_bytes(key(KeyCode::Up, none)), Some(b"\x1b[A".to_vec())); - assert_eq!(key_bytes(key(KeyCode::Left, none)), Some(b"\x1b[D".to_vec())); - assert_eq!(key_bytes(key(KeyCode::PageDown, none)), Some(b"\x1b[6~".to_vec())); - assert_eq!(key_bytes(key(KeyCode::Delete, none)), Some(b"\x1b[3~".to_vec())); - assert_eq!(key_bytes(key(KeyCode::BackTab, none)), Some(b"\x1b[Z".to_vec())); - assert_eq!(key_bytes(key(KeyCode::F(1), none)), Some(b"\x1bOP".to_vec())); - assert_eq!(key_bytes(key(KeyCode::F(12), none)), Some(b"\x1b[24~".to_vec())); + assert_eq!( + key_bytes(key(KeyCode::Left, none)), + Some(b"\x1b[D".to_vec()) + ); + assert_eq!( + key_bytes(key(KeyCode::PageDown, none)), + Some(b"\x1b[6~".to_vec()) + ); + assert_eq!( + key_bytes(key(KeyCode::Delete, none)), + Some(b"\x1b[3~".to_vec()) + ); + assert_eq!( + key_bytes(key(KeyCode::BackTab, none)), + Some(b"\x1b[Z".to_vec()) + ); + assert_eq!( + key_bytes(key(KeyCode::F(1), none)), + Some(b"\x1bOP".to_vec()) + ); + assert_eq!( + key_bytes(key(KeyCode::F(12), none)), + Some(b"\x1b[24~".to_vec()) + ); assert_eq!(key_bytes(key(KeyCode::F(13), none)), None); assert_eq!(key_bytes(key(KeyCode::CapsLock, none)), None); } @@ -44,7 +68,10 @@ fn control_and_alt_modify_the_encoding() { key_bytes(key(KeyCode::Char('R'), KeyModifiers::CONTROL)), Some(vec![0x12]) ); - assert_eq!(key_bytes(key(KeyCode::Char('1'), KeyModifiers::CONTROL)), None); + assert_eq!( + key_bytes(key(KeyCode::Char('1'), KeyModifiers::CONTROL)), + None + ); assert_eq!( key_bytes(key(KeyCode::Char('x'), KeyModifiers::ALT)), Some(b"\x1bx".to_vec()) From b2155286a974a7f416b083579c3c7ade66b594ad Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:16:38 +0000 Subject: [PATCH 57/60] test(tui): update expected subpage in config editor navigation test The navigation test now expects "Feedback" instead of "Resources" after moving down from the nav, matching the current subpage ordering. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/tests/feature_config_editor.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tui/tests/feature_config_editor.rs b/src/tui/tests/feature_config_editor.rs index 989ed9a8f..6ee57a593 100644 --- a/src/tui/tests/feature_config_editor.rs +++ b/src/tui/tests/feature_config_editor.rs @@ -147,7 +147,7 @@ fn up_and_down_follow_focus_between_the_nav_and_the_page() { // Back on the nav, the same keys walk the subpage list again. key(&mut app, KeyCode::Esc); key(&mut app, KeyCode::Down); - assert_eq!(app.settings_subpage(), "Resources"); + assert_eq!(app.settings_subpage(), "Feedback"); key(&mut app, KeyCode::Up); assert_eq!(app.settings_subpage(), "Config"); } From 8dc637d763900bd946e42e1f1cb4ed588e10b0a6 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:18:38 +0000 Subject: [PATCH 58/60] test(tui): update settings subpage key assertions Adjust the number-key navigation test to expect the Feedback subpage on key 6 and Account on key 7, matching the current subpage ordering. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/tui/tests/feature_settings.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tui/tests/feature_settings.rs b/src/tui/tests/feature_settings.rs index 3048338d1..b8839c9ee 100644 --- a/src/tui/tests/feature_settings.rs +++ b/src/tui/tests/feature_settings.rs @@ -82,8 +82,8 @@ fn number_keys_jump_subpages() { let _ = key(&mut app, KeyCode::Char('5')); assert_eq!(app.settings_subpage(), "Config"); let _ = key(&mut app, KeyCode::Char('6')); - assert_eq!(app.settings_subpage(), "Resources"); - let _ = key(&mut app, KeyCode::Char('8')); + assert_eq!(app.settings_subpage(), "Feedback"); + let _ = key(&mut app, KeyCode::Char('7')); assert_eq!(app.settings_subpage(), "Account"); // A digit also enters the pane, so getting to Help means stepping back out // to the nav first — the arrows browse content once a page has focus. From be139bbceea3b6936e3b94f9882b903ea2c4f9f2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 28 Oct 2026 19:21:41 +0000 Subject: [PATCH 59/60] fix(btop): keep btop alive across relogin and stop it safely at exit The event loop now hides the btop pane instead of shutting it down when a session ends, since a relogin re-enters the loop in the same process and btop can only start once per process. An atexit handler stops and saves btop before static destructors run, the runner thread is joined on stop, and the error query checks the length before allocating a buffer each frame. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- src/btop/src/handle.rs | 5 +++++ src/tui/src/event_loop/mod.rs | 4 ++++ src/tui/src/ui/btop/pane.rs | 4 +++- vendor/btop/src/btop.cpp | 3 +++ vendor/btop/src/btop_embed.cpp | 6 +++++- 5 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/btop/src/handle.rs b/src/btop/src/handle.rs index 1ce6ce7ce..3d27a2d17 100644 --- a/src/btop/src/handle.rs +++ b/src/btop/src/handle.rs @@ -194,6 +194,11 @@ impl Btop { pub fn error(&self) -> Option { #[cfg(not(medulla_btop_unsupported))] { + // Asked every frame, so check the length before allocating. + // SAFETY: a null buffer with zero capacity only reports the length. + if unsafe { crate::ffi::medulla_btop_error(std::ptr::null_mut(), 0) } == 0 { + return None; + } let mut buf = vec![0u8; 512]; // SAFETY: btop writes at most `buf.len()` bytes, NUL included. let len = unsafe { crate::ffi::medulla_btop_error(buf.as_mut_ptr().cast(), buf.len()) }; diff --git a/src/tui/src/event_loop/mod.rs b/src/tui/src/event_loop/mod.rs index 92870e46b..8fca15ea6 100644 --- a/src/tui/src/event_loop/mod.rs +++ b/src/tui/src/event_loop/mod.rs @@ -417,6 +417,10 @@ pub(crate) async fn run( } } } + // Pause, never stop, btop here: a relogin re-enters this loop in the same + // process, and btop starts once per process. Its own atexit hook stops and + // saves it when the process really ends. + medulla_tui::ui::btop::pane().hide(); Ok(if app.relogin_requested() { SessionExit::Relogin } else { diff --git a/src/tui/src/ui/btop/pane.rs b/src/tui/src/ui/btop/pane.rs index be856cf8e..86c192874 100644 --- a/src/tui/src/ui/btop/pane.rs +++ b/src/tui/src/ui/btop/pane.rs @@ -139,7 +139,9 @@ impl BtopPane { self.screen.screen().contents() } - /// Stop btop so it saves its config. Called once as the app exits. + /// Stop btop so it saves its config. Final: btop cannot start again in + /// this process, so only call it when the process is ending (btop's own + /// atexit hook already does this on a normal exit). pub fn shutdown(&mut self) { if let Lifecycle::Running { btop, .. } = &self.lifecycle { btop.stop(STOP_TIMEOUT); diff --git a/vendor/btop/src/btop.cpp b/vendor/btop/src/btop.cpp index 5db1d75a6..a64c2ebd6 100644 --- a/vendor/btop/src/btop.cpp +++ b/vendor/btop/src/btop.cpp @@ -779,6 +779,9 @@ auto btop_embed_main() -> void { Global::quitting = true; Runner::stopping = true; Runner::thread_trigger(); + //? Joined, not left running: the host may be about to exit, and the + //? runner must not outlive the globals it reads. + pthread_join(Runner::runner_id, nullptr); if (Config::getB("save_config_on_exit")) { try { Config::write(); } catch (...) {} } diff --git a/vendor/btop/src/btop_embed.cpp b/vendor/btop/src/btop_embed.cpp index 8ba952745..07958a1c5 100644 --- a/vendor/btop/src/btop_embed.cpp +++ b/vendor/btop/src/btop_embed.cpp @@ -156,6 +156,10 @@ int medulla_btop_start(const char* config_dir, uint16_t cols, uint16_t rows, catch (const std::system_error&) { return -2; } + //? btop's threads read C++ globals that static destruction tears down at + //? exit. An atexit handler registered now runs before those destructors, so + //? whichever way the host exits, btop has stopped (and saved) first. + std::atexit([] { medulla_btop_stop(2000); }); return 0; } @@ -230,7 +234,7 @@ size_t medulla_btop_error(char* buf, size_t cap) { } void medulla_btop_stop(uint32_t timeout_ms) { - if (not started.load()) return; + if (not started.load() or finished.load()) return; stop_requested = true; in_cv.notify_all(); Embed::interrupt(); From 89650077732c233f98f670d6b05edf720b346d33 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Thu, 29 Oct 2026 06:31:19 +0000 Subject: [PATCH 60/60] fix(btop): degrade gracefully when no g++ 14 is available The build script now distinguishes a missing modern compiler from a usable one and falls back to the unsupported stub with a warning instead of failing, so older toolchains like Debian 12's g++ 12 can still build the workspace. CI lanes set MEDULLA_BTOP_REQUIRED to turn that fallback into a hard error, and the shell test writes its record file atomically to avoid reading a partial file. Auto-committed-on: cuttlefish Co-authored-by: Medulla --- .github/actions/native-deps/action.yml | 6 +++ src/btop/build.rs | 49 ++++++++++++++++++--- src/tui/src/ui/harness_pane/tests/shells.rs | 4 +- 3 files changed, 51 insertions(+), 8 deletions(-) diff --git a/.github/actions/native-deps/action.yml b/.github/actions/native-deps/action.yml index 5fefae5ba..b624cd3a8 100644 --- a/.github/actions/native-deps/action.yml +++ b/.github/actions/native-deps/action.yml @@ -30,3 +30,9 @@ runs: sudo apt-get update sudo apt-get install -y --no-install-recommends \ pkg-config libssl-dev libx11-dev libxi-dev libxtst-dev libxdo-dev g++-14 + + # Lanes with g++-14 must really build btop: without this, `src/btop/build.rs` + # would quietly fall back to the unsupported stub on a broken toolchain. + - name: Require the embedded btop + shell: bash + run: echo "MEDULLA_BTOP_REQUIRED=1" >> "$GITHUB_ENV" diff --git a/src/btop/build.rs b/src/btop/build.rs index 145da09c2..008d8571a 100644 --- a/src/btop/build.rs +++ b/src/btop/build.rs @@ -25,6 +25,7 @@ const SHARED: [&str; 10] = [ fn main() { println!("cargo::rustc-check-cfg=cfg(medulla_btop_unsupported)"); println!("cargo:rerun-if-env-changed=CXX"); + println!("cargo:rerun-if-env-changed=MEDULLA_BTOP_REQUIRED"); let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("manifest dir")) .join("../../vendor/btop"); @@ -52,8 +53,25 @@ fn main() { .warnings(false) .flag_if_supported("-Wno-deprecated-declarations"); if target_os == "linux" && std::env::var_os("CXX").is_none() { - if let Some(compiler) = modern_gxx() { - build.compiler(compiler); + match modern_gxx() { + Compiler::Default => {} + Compiler::Versioned(compiler) => { + build.compiler(compiler); + } + Compiler::TooOld => { + // A toolchain that cannot build btop (Debian 12's g++ 12) must + // not break every build of the workspace; the Resources tab + // degrades exactly as it does on Windows. CI and releases set + // `MEDULLA_BTOP_REQUIRED` so they can never ship without it. + if std::env::var_os("MEDULLA_BTOP_REQUIRED").is_some() { + panic!("btop needs g++ >= 14 (std::ranges::to); install g++-14 or set CXX"); + } + println!( + "cargo:warning=medulla-btop: no g++ >= 14 found, building without the embedded btop" + ); + println!("cargo:rustc-cfg=medulla_btop_unsupported"); + return; + } } } for file in SHARED.iter().chain(platform) { @@ -75,10 +93,20 @@ fn main() { } } +/// Which C++ compiler the Linux build should use. +enum Compiler { + /// The platform default already suffices (g++ >= 14, or not GCC at all). + Default, + /// A versioned g++ installed beside an older default. + Versioned(&'static str), + /// Only a g++ too old for btop is available. + TooOld, +} + /// btop needs `std::ranges::to` and `std::expected`, which libstdc++ ships from /// GCC 14. Ubuntu 24.04's default `g++` is 13 with `g++-14` installed beside /// it, so prefer a versioned compiler when the default is too old. -fn modern_gxx() -> Option<&'static str> { +fn modern_gxx() -> Compiler { let major = |cmd: &str| -> Option { let out = Command::new(cmd).arg("-dumpversion").output().ok()?; String::from_utf8(out.stdout) @@ -89,12 +117,21 @@ fn modern_gxx() -> Option<&'static str> { .parse() .ok() }; - if major("g++").is_some_and(|v| v >= 14) { - return None; + let is_clang = Command::new("c++") + .arg("--version") + .output() + .ok() + .is_some_and(|out| String::from_utf8_lossy(&out.stdout).contains("clang")); + if is_clang || major("g++").is_some_and(|v| v >= 14) { + return Compiler::Default; } - ["g++-15", "g++-14"] + match ["g++-15", "g++-14"] .into_iter() .find(|cmd| major(cmd).is_some()) + { + Some(cmd) => Compiler::Versioned(cmd), + None => Compiler::TooOld, + } } /// Headers whose edits must rebuild the library. diff --git a/src/tui/src/ui/harness_pane/tests/shells.rs b/src/tui/src/ui/harness_pane/tests/shells.rs index e7f75bf3a..e5b94b89d 100644 --- a/src/tui/src/ui/harness_pane/tests/shells.rs +++ b/src/tui/src/ui/harness_pane/tests/shells.rs @@ -120,8 +120,8 @@ fn a_shell_session_is_spawned_bare() { std::fs::write( &bin, format!( - "#!/bin/sh\n{{ printf 'argc:%s\\n' \"$#\"; env; }} > {}\nsleep 30\n", - record.display() + "#!/bin/sh\n{{ printf 'argc:%s\\n' \"$#\"; env; }} > {r}.tmp && mv {r}.tmp {r}\nsleep 30\n", + r = record.display() ), ) .expect("the stand-in shell is writable");