commit f4b6bff4ec0974315e7aa62f3b6d9687c560f66b Author: aristocratos Date: Thu May 6 20:32:03 2021 +0200 Init diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..e69de29 diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..139878e --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,2 @@ +file(GLOB sources *.h *.c *.cxx *.cpp *.hxx) +add_executable(btop ${sources}) \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..4ef2c68 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at admin@qvantnet.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..fc8c323 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,33 @@ +# Contributing guidelines + +## When submitting pull requests + +* Explain your thinking in why a change or addition is needed. + * Is it a requested change or feature? + * If not, open a feature request to get feedback before making a pull request. + +* Split up multiple unrelated changes in multiple pull requests. + +* If it's a fix for a unreported bug, make a bug report and link the pull request. + +* Purely cosmetic changes won't be accepted without a very good explanation of its value. + +## Formatting + +### Follow the current syntax design + +* Indent type: Tabs + +* Tab size: 4 + +## Optimization + +* Avoid writing to disk if possible. + +* Make sure variables/vectors/maps/classes etc. are cleaned up if not reused. + +* Compare cpu and memory usage with and without your code and look for alternatives if they cause a noticeable negative impact. + +For questions contact Aristocratos at admin@qvantnet.com + +For proposing changes to this document create a [new issue](https://github.com/aristocratos/btop/issues/new/choose). diff --git a/Img/logo.png b/Img/logo.png new file mode 100644 index 0000000..75a2f04 Binary files /dev/null and b/Img/logo.png differ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/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/Makefile b/Makefile new file mode 100644 index 0000000..f2d680a --- /dev/null +++ b/Makefile @@ -0,0 +1,23 @@ +PREFIX ?= /usr/local +DOCDIR ?= $(PREFIX)/share/btop/doc +CXX=g++ +CXXFLAGS=-std=c++20 -pthread + +btop: btop.cpp + $(CXX) $(CXXFLAGS) -o btop btop.cpp + +install: + @mkdir -p $(DESTDIR)$(PREFIX)/bin + @cp -p btop $(DESTDIR)$(PREFIX)/bin/btop + @mkdir -p $(DESTDIR)$(DOCDIR) + @cp -p README.md $(DESTDIR)$(DOCDIR) + @cp -pr themes $(DESTDIR)$(PREFIX)/share/btop + @chmod 755 $(DESTDIR)$(PREFIX)/bin/btop + +uninstall: + @rm -rf $(DESTDIR)$(PREFIX)/bin/btop + @rm -rf $(DESTDIR)$(DOCDIR) + @rm -rf $(DESTDIR)$(PREFIX)/share/btop + +distclean: + rm -f btop diff --git a/README.md b/README.md new file mode 100644 index 0000000..eaa1aca --- /dev/null +++ b/README.md @@ -0,0 +1,184 @@ +# ![btop++](Img/logo.png) + +![Linux](https://img.shields.io/badge/-Linux-grey?logo=linux) +![Usage](https://img.shields.io/badge/Usage-System%20resource%20monitor-yellow) +![c++20](https://img.shields.io/badge/cpp-c%2B%2B20-green) +![btop_version](https://img.shields.io/github/v/tag/aristocratos/btop?label=version) +[![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) + +## 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!) +* [Dependencies](#dependencies) +* [Screenshots](#screenshots) +* [Installation](#installation) +* [Configurability](#configurability) +* [License](#license) + +## News + +### Under development +##### 5 May 2021 + +This project is gonna take some time until it has complete feature parity with bpytop, since all system information gathering will likely 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 OSX. + +If you got suggestions of C++ libraries that are multi-platform and are as extensive as [psutil](https://github.com/giampaolo/psutil) are for python, feel free to open up a new thread in Discussions, it could help speed up the development a lot. + +## 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 (at release) + +* Easy to use, with a game inspired menu system. +* Full mouse support, all buttons with a highlighted key is clickable and mouse scroll works in process list and menu boxes. +* Fast and responsive UI with UP, DOWN keys process selection. +* Function for showing detailed stats for selected process. +* Ability to filter processes, multiple filters can be entered. +* Easy switching between sorting options. +* Send SIGTERM, SIGKILL, SIGINT to selected process. +* UI menu for changing all config file options. +* Auto scaling graph for network usage. +* Shows message in menu if new version is available +* Shows current read and write speeds for disks + +## 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/master/themes) folder for available themes. + +The `make install` command places the default themes in `/usr/local/share/btop/themes`. +User created themes should be placed in `$HOME/.config/btop/themes`. + +Let me know if you want to contribute with new themes. + +## 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 correct display, a terminal with support for: + +* 24-bit truecolor ([See list of terminals with truecolor support](https://gist.github.com/XVilka/8346728)) +* 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" argument. +* Wide characters (Are sometimes problematic in web-based terminals) + +Also needs a UTF8 locale and a font that covers: + +* Unicode Block “Braille Patterns” U+2800 - U+28FF +* Unicode Block “Geometric Shapes” U+25A0 - U+25FF +* Unicode Block "Box Drawing" and "Block Elements" U+2500 - U+259F + +#### 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/tree/master/patched-fonts/Terminus/terminus-ttf-4.40.1) 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 are misaligned and you are using Konsole or Yakuake, turning off "Bi-Directional text rendering" is a possible fix. + +Characters clipping in to each other or text/border misalignments is not bugs caused by bpytop, 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 previous mentioned fixes don't work for you. + +## Dependencies + +None + +But will need G++ 10 or Clang 11 if compiling from source. + +## Screenshots + +Main UI showing details for a selected process. +![Screenshot 1]() + +Main UI in mini mode. +![Screenshot 2]() + +Main menu. +![Screenshot 3]() + +Options menu. +![Screenshot 4]() + +## Installation + +#### Manual compilation and installation + +>Clone and compile + +``` bash +git clone https://github.com/aristocratos/btop.git +cd btop +make +``` + +>to install + +``` bash +sudo make install +``` + +>to uninstall + +``` bash +sudo make uninstall +``` + +>to clear any compiled files + +```bash +make distclean +``` + +## Configurability + +All options changeable from within UI. +Config files stored in "$HOME/.config/btop" folder + +#### btop.cfg: (auto generated if not found) + +"/etc/bpytop.conf" will be used as default seed for config file creation if it exists. ("/usr/local/etc/bpytop.conf" on BSD) + +```bash +#? Config file for btop v. 0.0.1 + + +``` + +#### Command line options: + +```text +usage: btop [-v] +``` + +## LICENSE + +[Apache License 2.0](LICENSE) diff --git a/btop b/btop new file mode 100755 index 0000000..97ca7be Binary files /dev/null and b/btop differ diff --git a/btop.cpp b/btop.cpp new file mode 100644 index 0000000..d9c0c62 --- /dev/null +++ b/btop.cpp @@ -0,0 +1,671 @@ +/* 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 +#include +#include +#include + +using namespace std; + +//? ------------------------------------------------- GLOBALS --------------------------------------------------------- + +const vector> BANNER_SRC = { + {"#E62525", "██████╗ ████████╗ ██████╗ ██████╗"}, + {"#CD2121", "██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗ ██╗ ██╗"}, + {"#B31D1D", "██████╔╝ ██║ ██║ ██║██████╔╝ ██████╗██████╗"}, + {"#9A1919", "██╔══██╗ ██║ ██║ ██║██╔═══╝ ╚═██╔═╝╚═██╔═╝"}, + {"#801414", "██████╔╝ ██║ ╚██████╔╝██║ ╚═╝ ╚═╝"}, + {"#000000", "╚═════╝ ╚═╝ ╚═════╝ ╚═╝"}, +}; + +const string VERSION = "0.0.1"; + +const map DEFAULT_THEME = { + { "main_bg", "#00" }, + { "main_fg", "#cc" }, + { "title", "#ee" }, + { "hi_fg", "#969696" }, + { "selected_bg", "#7e2626" }, + { "selected_fg", "#ee" }, + { "inactive_fg", "#40" }, + { "graph_text", "#60" }, + { "meter_bg", "#40" }, + { "proc_misc", "#0de756" }, + { "cpu_box", "#3d7b46" }, + { "mem_box", "#8a882e" }, + { "net_box", "#423ba5" }, + { "proc_box", "#923535" }, + { "div_line", "#30" }, + { "temp_start", "#4897d4" }, + { "temp_mid", "#5474e8" }, + { "temp_end", "#ff40b6" }, + { "cpu_start", "#50f095" }, + { "cpu_mid", "#f2e266" }, + { "cpu_end", "#fa1e1e" }, + { "free_start", "#223014" }, + { "free_mid", "#b5e685" }, + { "free_end", "#dcff85" }, + { "cached_start", "#0b1a29" }, + { "cached_mid", "#74e6fc" }, + { "cached_end", "#26c5ff" }, + { "available_start", "#292107" }, + { "available_mid", "#ffd77a" }, + { "available_end", "#ffb814" }, + { "used_start", "#3b1f1c" }, + { "used_mid", "#d9626d" }, + { "used_end", "#ff4769" }, + { "download_start", "#231a63" }, + { "download_mid", "#4f43a3" }, + { "download_end", "#b0a9de" }, + { "upload_start", "#510554" }, + { "upload_mid", "#7d4180" }, + { "upload_end", "#dcafde" }, + { "process_start", "#80d0a3" }, + { "process_mid", "#dcd179" }, + { "process_end", "#d45454" } +}; + +map>> MENUS = { + { "options", { + { "normal", + { "┌─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐", + "│ │├─┘ │ ││ ││││└─┐", + "└─┘┴ ┴ ┴└─┘┘└┘└─┘" + } }, + { "selected", + { "╔═╗╔═╗╔╦╗╦╔═╗╔╗╔╔═╗", + "║ ║╠═╝ ║ ║║ ║║║║╚═╗", + "╚═╝╩ ╩ ╩╚═╝╝╚╝╚═╝" + } } + } }, + { "help", { + { "normal", + { "┬ ┬┌─┐┬ ┌─┐", + "├─┤├┤ │ ├─┘", + "┴ ┴└─┘┴─┘┴ " + } }, + { "selected", + { "╦ ╦╔═╗╦ ╔═╗", + "╠═╣║╣ ║ ╠═╝", + "╩ ╩╚═╝╩═╝╩ " + } } + } }, + { "quit", { + { "normal", + { "┌─┐ ┬ ┬ ┬┌┬┐", + "│─┼┐│ │ │ │ ", + "└─┘└└─┘ ┴ ┴ " + } }, + { "selected", + { "╔═╗ ╦ ╦ ╦╔╦╗ ", + "║═╬╗║ ║ ║ ║ ", + "╚═╝╚╚═╝ ╩ ╩ " + } } + } } +}; + +//? ------------------------------------------------- NAMESPACES ------------------------------------------------------ + +namespace State { + atomic MenuActive(false); +}; + +namespace Fx { //? Collection of escape codes for text style and formatting + const string e = "\x1b["; //* Escape sequence start + const string r = e + "0m"; //* Reset foreground/background color and text effects + const string b = e + "1m"; //* Bold on + const string ub = e + "22m"; //* Bold off + const string d = e + "2m"; //* Dark on + const string ud = e + "22m"; //* Dark off + const string i = e + "3m"; //* Italic on + const string ui = e + "23m"; //* Italic off + const string ul = e + "4m"; //* Underline on + const string uul = e + "24m"; //* Underline off + const string bl = e + "5m"; //* Blink on + const string ubl = e + "25m"; //* Blink off + const string s = e + "9m"; //* Strike / crossed-out on + const string us = e + "29m"; //* Strike / crossed-out off +}; + +namespace Mv { //? Collection of escape codes and functions for cursor manipulation + string to(int line, int col){ return Fx::e + to_string(line) + ";" + to_string(col) + "f";} //* Move cursor to line, column + string r(int x){ return Fx::e + to_string(x) + "C";} //* Move cursor right x columns + string l(int x){ return Fx::e + to_string(x) + "D";} //* Move cursor left x columns + string u(int x){ return Fx::e + to_string(x) + "A";} //* Move cursor up x lines + string d(int x) { return Fx::e + to_string(x) + "B";} //* Move cursor down x lines + const string save = Fx::e + "s"; //* Save cursor position + const string restore = Fx::e + "u"; //* Restore saved cursor postion +}; + +//? --------------------------------------- FUNCTIONS, STRUCTS & CLASSES ---------------------------------------------- + +inline size_t ulen(const string& str){ //? Return number of UTF8 characters in a string + size_t len = 0; + for (char c : str) if ((c & 0xC0) != 0x80) ++len; + return len; +} + +string color_to_string(string hexa="", unsigned r=0, unsigned g=0, unsigned b=0, string depth="fg"){ + //? Generate escape sequence for 24-bit color and return as a string + //? Accepted arguments: hexa="#000000" to "#ffffff" for color, or "#00" to "#ff" for greyscale + //? Or: r=0-255, g=0-255, b=0-255 + //? depth=string "fg" or "bg" for either a foreground color or a background color + depth = (depth == "fg") ? "38" : "48"; + if (hexa.size() > 1){ + hexa.erase(0, 1); + for (auto& c : hexa) if (!isxdigit(c)) return ""; + + if (hexa.size() == 2){ + string h_str = ";" + to_string(stoi(hexa, 0, 16)); + return Fx::e + depth + ";2" + h_str + h_str + h_str + "m"; + } + else if (hexa.size() == 6){ + return Fx::e + depth + ";2" + ";" + + to_string(stoi(hexa.substr(0, 2), 0, 16)) + ";" + + to_string(stoi(hexa.substr(2, 2), 0, 16)) + ";" + + to_string(stoi(hexa.substr(4, 2), 0, 16)) + "m"; + } + } else if (r && g && b){ + r = (r > 255) ? 255 : r; + g = (g > 255) ? 255 : g; + b = (b > 255) ? 255 : b; + return Fx::e + depth + ";2" + ";" + to_string(r) + ";" + to_string(g) + ";" + to_string(b) + "m"; + } + return ""; +} + +string ltrim(string str, string t_str = " "){ //? Left-trim from and return string + size_t t_str_size = t_str.size(); + while (str.substr(0, t_str_size) == t_str) str.erase(0, t_str_size); + return str; +} + +string rtrim(string str, string t_str = " "){ //? Right-trim from and return string + size_t t_str_size = t_str.size(); + while (str.substr(str.size() - t_str_size, t_str_size) == t_str) str.erase(str.size() - t_str_size, t_str_size); + return str; +} + +string trim(string str, string t_str = " "){ //? Left-right-trim from and return string + return ltrim(rtrim(str, t_str), t_str); +} + +vector ssplit(string str, string delim = " ", int times = 0){ //? Split at (0 for unlimited) times and return vector + vector out; + if (str != "" && delim != ""){ + size_t pos = 0; + int x = 0; + string tmp; + while ((pos = str.find(delim)) != string::npos){ + tmp = str.substr(0, pos); + if (tmp != delim && tmp != "") out.push_back(tmp); + str.erase(0, pos + delim.size()); + if (times > 0 && ++x >= times) break; + } + } + out.push_back(str); + return out; +} + +map c_to_rgb(string c_string){ //? Return a map of "r", "g", "b", 0-255 values for a 24-bit color escape string + map rgb = {{"r", 0}, {"g", 0}, {"b", 0}}; + if (c_string.size() >= 14){ + c_string.erase(0, 7); + auto c_split = ssplit(c_string, ";"); + if (c_split.size() == 3){ + rgb["r"] = stoi(c_split[0]); + rgb["g"] = stoi(c_split[1]); + rgb["b"] = stoi(c_split[2].erase(c_split[2].size())); + } + } + return rgb; +} + +class C_Term { //? Collection of escape codes and functions for terminal manipulation + bool initialized = false; + struct termios initial_settings; +public: + int width = 0; + int height = 0; + bool resized = false; + string fg = "" ; //* Default foreground color + string bg = ""; //* Default background color + const string hide_cursor = Fx::e + "?25l"; //* Hide terminal cursor + const string show_cursor = Fx::e + "?25h"; //* Show terminal cursor + const string alt_screen = Fx::e + "?1049h"; //* Switch to alternate screen + const string normal_screen = Fx::e + "?1049l"; //* Switch to normal screen + const string clear = Fx::e + "2J" + Fx::e + "0;0f"; //* Clear screen and set cursor to position 0,0 + const string mouse_on = Fx::e + "?1002h" + Fx::e + "?1015h" + Fx::e + "?1006h"; //* Enable reporting of mouse position on click and release + const string mouse_off = "\033[?1002l"; //* Disable mouse reporting + const string mouse_direct_on = "\033[?1003h"; //* Enable reporting of mouse position at any movement + const string mouse_direct_off = "\033[?1003l"; //* Disable direct mouse reporting + + bool init(){ //? Save terminal options and check valid tty + if (!this->initialized){ + this->initialized = (bool)isatty(STDIN_FILENO); + if (this->initialized) this->initialized = (0 == tcgetattr(STDIN_FILENO, &this->initial_settings)); + if (this->initialized) cin.sync_with_stdio(); + } + return initialized; + } + + void restore(){ //? Restore terminal options + if (this->initialized) tcsetattr(STDIN_FILENO, TCSANOW, &this->initial_settings); + } + + bool linebuffered(bool on=true){ //? Toggle need for return key when reading input + struct termios settings; + if (tcgetattr(STDIN_FILENO, &settings)) return false; + if (on) settings.c_lflag |= ICANON; + else settings.c_lflag &= ~(ICANON); + if (tcsetattr(STDIN_FILENO, TCSANOW, &settings)) return false; + if (on) setlinebuf(stdin); + else setbuf(stdin, NULL); + return true; + } + + bool echo(bool on=true){ //? Toggle terminal input echo + 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); + } + + bool refresh(){ //? Refresh variables holding current terminal width and height and return true if resized + struct winsize w; + ioctl(STDOUT_FILENO, TIOCGWINSZ, &w); + this->resized = (this->width != w.ws_col || this->height != w.ws_row) ? true : false; + this->width = w.ws_col; + this->height = w.ws_row; + return resized; + } + + C_Term() { + this->init(); + this->refresh(); + this->resized = false; + } + +}; + +C_Term Term; //* Make C_Term globally available as Term + +struct C_Key { + string last = ""; + + const map KEY_ESCAPES = { + {"\033", "escape"}, + {"\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"}, + {"[3~", "delete"}, + {"[H", "home"}, + {"[F", "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"} + }; + + bool wait(unsigned timeout_ms=0){ + struct pollfd pls[1]; + pls[ 0 ].fd = STDIN_FILENO; + pls[ 0 ].events = POLLIN | POLLPRI; + return poll(pls, 1, timeout_ms) > 0; + } + + string get(){ + string key = ""; + while (this->wait() && key.size() < 100) key += cin.get(); + if (key != ""){ + if (key.substr(0,2) == Fx::e) key.erase(0, 1); + if (this->KEY_ESCAPES.count(key)) key = this->KEY_ESCAPES.at(key); + else if (ulen(key) > 1) key = ""; + + this->last = key; + } + return key; + } + + string operator()(unsigned timeout_ms=0){ + if (this->wait(timeout_ms)) { + return this->get(); + } else { + return ""; + } + } +}; + +C_Key Key; + +class C_Theme { + map c; + map> g; + + map generate(map& source){ + //? Generate theme from map, default to DEFAULT_THEME on missing or malformatted values + map out; + for (auto& item : DEFAULT_THEME) { + if (source.count(item.first)) out[item.first] = color_to_string(source.at(item.first)); + else out[item.first] = ""; + if (out[item.first] == "") out[item.first] = color_to_string(item.second); + } + return out; + } + +public: + + void swap(map source){ + this->c = this->generate(source); + } + + C_Theme(map source){ + this->c = this->generate(source); + } + + auto operator()(string name){ + return this->c.at(name); + } + + auto gradient(string name){ + return this->g.at(name); + } + + auto rgb(string name){ + return c_to_rgb(this->c.at(name)); + } + +}; + +struct C_Banner { + string banner_str; + + C_Banner(){ + size_t z = 0; + string b_color, bg, fg, out, oc, letter; + this->banner_str = ""; + for (auto line: BANNER_SRC) { + fg = color_to_string(line[0]); + bg = color_to_string("#" + to_string(80-z*6)); + for (unsigned i = 0; i < line[1].size(); i += 3) { + if (line[1][i] == ' '){ + letter = ' '; + i -= 2; + } else{ + letter = line[1].substr(i, 3); + } + b_color = (letter == "█") ? fg : bg; + if (b_color != oc) out += b_color; + out += letter; + oc = b_color; + } + z++; + if (z < BANNER_SRC.size()) out += Mv::l(ulen(line[1])) + Mv::d(1); + } + this->banner_str = out; + } + + string operator() (){ + return this->banner_str + Fx::r; + } +}; + +C_Banner Banner; + +//? ------------------------------------------------- FUNCTIONS ------------------------------------------------------- + +void argumentParser(int argc, char **argv){ //? A simple argument parser + string argument; + for(int i = 1; i < argc; i++) { + argument = argv[i]; + if (argument == "-v" || argument == "--version") { + cout << "btop version: " << VERSION << endl; + exit(0); + } else if (argument == "-h" || argument == "--help") { + cout << "help here" << endl; + exit(0); + } else { + cout << " Unknown argument: " << argument << "\n" << + " Use -h or --help for help." << endl; + exit(1); + } + } +} + +uint64_t time_ms(){ + return chrono::duration_cast(chrono::system_clock::now().time_since_epoch()).count(); +} + +//? --------------------------------------------- Main starts here! --------------------------------------------------- +int main(int argc, char **argv){ + int debug = 2; + int tests = 0; + + // bool thread_test = false; + + //? Init + + if (argc > 1) argumentParser(argc, argv); + + if (!Term.init()) { + cout << "No terminal detected!" << endl; + exit(1); + } + Term.echo(false); + Term.linebuffered(false); + + + if (debug < 2) cout << Term.alt_screen << Term.clear << Term.hide_cursor << flush; + + C_Theme Theme(DEFAULT_THEME); + + + //* Test MENUS + for (auto& outer : MENUS){ + for (auto& inner : outer.second){ + for (auto& item : inner.second){ + cout << item << endl; + } + } + } + + + string korv5 = "hejsan"; + if (korv5.starts_with("hej")) cout << "hej" << endl; + + + State::MenuActive.store(true); + + if (State::MenuActive.load()) cout << "WHUUUU and time: " << time_ms() << endl; + + //cout << korv2.size() << " " << ulen(korv2) << endl; + + //* Test theme + if (tests>0) for(auto& item : DEFAULT_THEME) cout << Theme(item.first) << item.first << endl; + + // if (thread_test){ + // int max = 50000; + // int count = max / 100; + // atomic running; + // running = true; + // thread ttg1(C_Theme::generate, DEFAULT_THEME); + + // for (int i = 0; i < max; i++) { + // // C_Theme tt(DEFAULT_THEME); + // // tt.del(); + // auto ttg1 = async(C_Theme::generate, DEFAULT_THEME); + // auto ttg2 = async(C_Theme::generate, DEFAULT_THEME); + // auto ttg3 = async(C_Theme::generate, DEFAULT_THEME); + // auto ttg4 = async(C_Theme::generate, DEFAULT_THEME); + // // ttg1.wait(); + // // ttg2.wait(); + // map tt1 = ttg1.get(); + // map tt2 = ttg2.get(); + // map tt3 = ttg3.get(); + // map tt4 = ttg4.get(); + // if (i >= count) { + // cout << Mv::restore << "(" << i * 100 / max << "%)" << flush; + // count += max / 100; + // } + // } + // } + + + + if (tests>1){ + string lk = "first second another lastone"; + + for (auto& it : ssplit(lk)){ + cout << it << flush; + switch (it.front()) { + case 's': cout << " <=" << endl; break; + default: cout << endl; + } + } + } + + + // if (tests>2){ + cout << " " << Banner() << endl; + // } + + if (tests>3){ + auto nbcolor = color_to_string(DEFAULT_THEME.at("net_box")); + auto nbcolor_rgb = c_to_rgb(nbcolor); + auto nbcolor_man = ssplit(nbcolor, ";"); + cout << nbcolor << "Some color" << Fx::r << " Normal Color" << endl; + cout << "nbcolor_rgb size=" << nbcolor_rgb.size() << endl; + cout << "R:" << nbcolor_rgb.at("r") << " G:" << nbcolor_rgb.at("g") << " B:" << nbcolor_rgb.at("b") << endl; + cout << "MANUAL R:" << nbcolor_man.at(2) << " G:" << nbcolor_man.at(3) << " B:" << nbcolor_man.at(4) << endl; + + auto ccc = color_to_string("", 100, 255, 100); + cout << "\n" << ccc << "Testing..." << Fx::r << " normal." << endl; + } + + + if (tests>4){ + string trim_test1 = "-*vad "; + string trim_test2 = " vad*-"; + string trim_test3 = trim_test1 + trim_test2; + + cout << "\"" << ltrim(trim_test1, "-*") << "\" \"" << rtrim(trim_test2, "*-") << "\" \"" << trim(trim_test3, "-") << "\"" << endl; + + + string testie = "Does this work as intended? Or?"; + auto t_vec = ssplit(testie); + for(auto& tp : t_vec){ + cout << "\"" << tp << "\" " << flush; + } + } + + + //if (tests>5){ + cout << "Width=" << Term.width << " Height=" << Term.height << endl; + //} + + // map dict = { + // {"Korv", "14"}, + // {"Vad", "13"} + // }; + + // cout << dict["Korv"] << ", " << dict["Vad"] << endl; + + // vector> test = { + // {{"first", 1}, {"second", 2}}, + // {{"first", 11}, {"second", 22}} + // }; + + //cout << test[0]["first"] << " " << test[1]["second"] << endl; + + // for (auto& m : test) { + // cout << endl; + // for (auto& item : m) { + // cout << item.first << " " << item.second << endl; + // } + // } + + + + if (debug == 0){ + cout << Mv::to(Term.height - 1, 0) << "Press q to exit! Timeout" << flush; + string chr; + string full; + int wt = 90; + bool qp = false; + while (!qp && wt >= 0){ + int wtm = wt / 60; + int wts = wt - wtm * 60; + wt--; + cout << Mv::to(Term.height - 1, 26) << "(" << wtm << ":" << wts << ") " << flush; + if (Key.wait(1000)) chr = Key.get(); + if (chr != ""){ + cout << Mv::to(Term.height - 2, 1) << "Last key: LEN=" << chr.size() << " ULEN=" << ulen(chr) << " KEY=\"" << chr << "\" CODE=" << (int)chr.at(0) << " " << flush; + full += chr; + cout << Mv::to(Term.height - 5, 1) << full << flush; + if (chr == "q") qp = true; + chr = ""; + wt++; + } + } + } + + if (debug == 1) Key(-1); + Term.restore(); + if (debug < 2) cout << Term.normal_screen << Term.show_cursor << flush; + return 0; +}