kmon-1.6.5/.cargo_vcs_info.json0000644000000001360000000000100120110ustar { "git": { "sha1": "2487c3a761d6672a5a73c913593ab6d1710b697f" }, "path_in_vcs": "" }kmon-1.6.5/CHANGELOG.md000064400000000000000000000177431046102023000124260ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.6.5] - 2024-04-12 ### Added - Add a panic hook to reset terminal upon panic by @eld4niz in [#141](https://github.com/orhun/kmon/pull/141) ### Changed - Upgrade dependencies by @orhun - Bump the Rust version in Dockerfile by @orhun - Update funding options - Update license copyright years - Prepare for the release v1.6.5 ### Fixed - Do not panic when /proc/modules does not exist by @eld4niz in [#139](https://github.com/orhun/kmon/pull/139) ### New Contributors * @eld4niz made their first contribution in [#139](https://github.com/orhun/kmon/pull/139) ## [1.6.4] - 2023-10-27 ### Changed - Bump dependencies ### Fixed - Fix all new clippy errors with 'rustc:1.73.0' ## [1.6.3] - 2023-04-06 ### Added - Build Docker image for arm64 - Generate SBOM/provenance for the Docker image ### Changed - Update README.md about manual installation (#37) - Apply clippy suggestions - Switch to `ratatui` (#40) - Integrate dependabot - Bump dependencies ### Fixed - Fix typos (#38) - Remove target directory from .dockerignore for proper caching ## [1.6.2] - 2022-10-02 ### Added - Add build script for generating manpage and completions ([#34](https://github.com/orhun/kmon/pull/34)) - Enable [GitHub Sponsors](https://github.com/sponsors/orhun) for funding - Consider supporting me for my open-source efforts 💖 ### Changed - Update the project structure to be used as library - Apply clippy suggestions - Bump dependencies ### Fixed - Switch to [copypasta-ext](https://gitlab.com/timvisee/copypasta-ext) crate for fixing [RUSTSEC-2022-0056](https://rustsec.org/advisories/RUSTSEC-2022-0056) ## [1.6.1] - 2022-10-02 ## [1.6.0] - 2021-11-05 ### Added - Add [options menu](https://github.com/orhun/kmon#options-menu) for managing the kernel modules. Press `m` to show: ### Changed - Migrate to Rust 2021 edition - Bump the dependencies - Optimize CI/CD workflows ## [1.5.5] - 2021-08-11 ### Changed - Center the title of kernel information block - Update dependencies to the latest version - Update the upload step in CD workflow ## [1.5.4] - 2021-07-16 This release contains major code refactoring for bumping [tui-rs](https://github.com/fdehau/tui-rs/) to the latest version. Please [report](https://github.com/orhun/kmon/issues/new/choose) if you come across any unexpected behaviour. ### Changed - Update dependencies to the latest version - Update README.md about social media links and AUR installation - Update RELEASE.md to mention the release signing key ### Fixed - Make the help text copyable via `c` key press - Apply clippy suggestions ## [1.5.3] - 2020-12-15 ### Fixed - Install X11 dependencies for crates.io release ## [1.5.2] - 2020-12-15 ### Added - Add codecov.yml - Add strategy to CD workflow for different targets ### Changed - Update kmon.8 to include string "kmod" ([#24](https://github.com/orhun/kmon/issues/24)) - Update Cargo.toml about project details - Update Dockerfile about image and dependency versions ### Removed - Remove snapcraft.yaml ## [1.5.1] - 2020-10-09 ### Fixed - Fix test failing when giving arguments to the test binary ## [1.5.0] - 2020-08-27 ### Added - Add alt-e/s keys for expanding/shrinking the selected block - Add ctrl-x key for changing the position of a block ### Changed - Update the AUR installation step in README.md ### Fixed - Fix the percentage overflow in kernel module table - Use the default colors if the accent color is not provided ### Removed - Remove the AUR binary package publish step from CD workflow ## [1.4.0] - 2020-08-05 ### Added - Add accent color option to set default text color ### Changed - Update README.md about accent color option - Update manual page about accent color option ## [1.3.5] - 2020-07-30 ### Changed - Update README.md about Arch Linux packages - Update the release steps of AUR packages in CD workflow - Update a link in release instructions about AUR packages ### Fixed - Continue to run the CD workflow if crates.io publish fails (for re-running the workflow) ## [1.3.4] - 2020-07-30 ### Fixed - Update CD workflow about AUR releases ## [1.3.3] - 2020-07-30 ### Changed - Update the release instructions about git tag command ### Fixed - Update the repository secrets for fixing the CD workflow ## [1.3.2] - 2020-07-29 ### Fixed - Update the publishing order in CD workflow ## [1.3.1] - 2020-07-29 ### Added - Add CNAME record and theme config for the project page - Add PGP keys to CD workflow for signing the releases ### Changed - Update README.md about Copr package ## [1.3.0] - 2020-07-22 ### Added - Support insmod/rmmod for low-level module handling ### Fixed - Use codecov action for uploading reports to codecov.io ### Changed - Update Cargo dependencies to the latest version - Update README.md about load/unload/reload commands - Update the CI workflow about clippy arguments ## [1.2.0] - 2020-05-03 ### Added - Add `ctrl-r, alt-r` key actions for reloading a module - Add `d, alt-d` key actions for showing the dependent modules ### Fixed - Use Box instead of failure::Error ### Changed - Update the date in the manual page - Update .gitignore about Visual Studio Code - Update README.md about key binding changes ### Removed - Remove the deprecated failure crate ## [1.1.0] - 2020-04-09 ### Added - Add `-d, --dependent` flag for sorting modules by their dependent modules - Add information about `-d, --dependent` flag to README.md - Add a section to README.md about installation from nixpkgs ### Fixed - Fix the CI workflow about Docker builds ### Changed - Update README.md about sorting/reversing GIFs - Improve the test cases of sort type flags ## [1.0.1] - 2020-04-05 ### Added - Add Copr package instructions to README.md ### Fixed - Fix the broken manpage link in README.md ## [1.0.0] - 2020-04-01 ### Added - Add roadmap, ToC, funding information and new images to README.md - Add FUNDING.yml ## [0.3.3] - 2020-03-23 ### Fixed - Update the AUR (git) release step in CD workflow ## [0.3.2] - 2020-03-23 ### Added - Add snapcraft.yml for the snap package ### Fixed - Fix the AUR publish actions in CD workflow according to the package guidelines ### Changed - Update .gitignore and .dockerignore files about snap package files - Update README.md about the main usage gif ## [0.3.1] - 2020-03-19 ### Fixed - Fix stylize function about adding colors to the text ### Changed - Update README.md about usage information, features and images - Update descriptions of the module management commands - Update the module blacklisting command ## [0.3.0] - 2020-03-10 ### Added - Add horizontal scrolling feature to kernel activities block - Add debug derive to enum types ### Fixed - Use the case insensitive alt-key combinations ### Changed - Update the runtime key bindings - Update README.md about key bindings and sections - Update the manual page about key bindings ## [0.2.2] - 2020-03-01 ### Added - Update README.md about man page and project description ### Changed - Move man page file to man/ directory - Update the CD workflow about the new location of man page ## [0.2.1] - 2020-02-28 ### Added - Add project installation, usage, key bindings and resources to README - Add manual page for the project - Add test for the `ctrl-l` key action ### Changed - Update the CD workflow for adding the manual page to the final binary package ## [0.2.0] - 2020-02-23 ### Added - Add key bindings for clearing the kernel ring buffer - Add `--ctime` parameter to `dmesg` command for human readable date format ## [0.1.1] - 2020-02-23 ### Added - Add contribution guidelines, release instructions and changelog ### Fixed - Improve the CI/CD workflows ### Changed - Update the documentation ## [0.1.0] - 2020-02-06 ### Added - Add CI/CD workflows to the project for automation kmon-1.6.5/Cargo.lock0000644000000620630000000000100077730ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "ahash" version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" dependencies = [ "cfg-if", "once_cell", "version_check", "zerocopy", ] [[package]] name = "allocator-api2" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" [[package]] name = "anstream" version = "0.6.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "utf8parse", ] [[package]] name = "anstyle" version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" [[package]] name = "anstyle-parse" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" dependencies = [ "windows-sys", ] [[package]] name = "anstyle-wincon" version = "3.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" dependencies = [ "anstyle", "windows-sys", ] [[package]] name = "autocfg" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" [[package]] name = "block" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" [[package]] name = "bytesize" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3e368af43e418a04d52505cf3dbc23dda4e3407ae2fa99fd0e4f308ce546acc" [[package]] name = "cassowary" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" [[package]] name = "castaway" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a17ed5635fc8536268e5d4de1e22e81ac34419e5f052d4d51f4e01dcc263fcc" dependencies = [ "rustversion", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "clap" version = "4.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" dependencies = [ "anstream", "anstyle", "clap_lex", "strsim", ] [[package]] name = "clap_complete" version = "4.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd79504325bf38b10165b02e89b4347300f855f273c4cb30c4a3209e6583275e" dependencies = [ "clap", ] [[package]] name = "clap_lex" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" [[package]] name = "clap_mangen" version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1dd95b5ebb5c1c54581dd6346f3ed6a79a3eef95dd372fc2ac13d535535300e" dependencies = [ "clap", "roff", ] [[package]] name = "clipboard-win" version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fdf5e01086b6be750428ba4a40619f847eb2e95756eee84b18e06e5f0b50342" dependencies = [ "lazy-bytes-cast", "winapi", ] [[package]] name = "colorchoice" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" [[package]] name = "colorsys" version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54261aba646433cb567ec89844be4c4825ca92a4f8afba52fc4dd88436e31bbd" [[package]] name = "compact_str" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f86b9c4c00838774a6d902ef931eff7470720c51d90c2e32cfe15dc304737b3f" dependencies = [ "castaway", "cfg-if", "itoa", "ryu", "static_assertions", ] [[package]] name = "copypasta" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "133fc8675ee3a4ec9aa513584deda9aa0faeda3586b87f7f0f2ba082c66fb172" dependencies = [ "clipboard-win", "objc", "objc-foundation", "objc_id", "smithay-clipboard", "x11-clipboard", ] [[package]] name = "copypasta-ext" version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9455f470ea0c7d50c3fe3d22389c3a482f38a9f5fbab1c8ee368121356c56718" dependencies = [ "copypasta", "libc", "which", "x11-clipboard", ] [[package]] name = "dlib" version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412" dependencies = [ "libloading", ] [[package]] name = "downcast-rs" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" [[package]] name = "either" version = "1.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11157ac094ffbdde99aa67b23417ebdd801842852b500e395a45a9c0aac03e4a" [[package]] name = "enum-iterator" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "600536cfe9e2da0820aa498e570f6b2b9223eec3ce2f835c8ae4861304fa4794" dependencies = [ "enum-iterator-derive", ] [[package]] name = "enum-iterator-derive" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03cdc46ec28bd728e67540c528013c6a10eb69a02eb31078a1bda695438cbfb8" dependencies = [ "proc-macro2", "quote", "syn 2.0.58", ] [[package]] name = "errno" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" dependencies = [ "libc", "windows-sys", ] [[package]] name = "gethostname" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1ebd34e35c46e00bb73e81363248d627782724609fe1b6396f553f68fe3862e" dependencies = [ "libc", "winapi", ] [[package]] name = "hashbrown" version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" dependencies = [ "ahash", "allocator-api2", ] [[package]] name = "heck" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" [[package]] name = "home" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" dependencies = [ "windows-sys", ] [[package]] name = "indoc" version = "2.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5" [[package]] name = "itertools" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" dependencies = [ "either", ] [[package]] name = "itoa" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "kmon" version = "1.6.5" dependencies = [ "bytesize", "clap", "clap_complete", "clap_mangen", "colorsys", "copypasta-ext", "enum-iterator", "ratatui", "termion", "unicode-width", ] [[package]] name = "lazy-bytes-cast" version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10257499f089cd156ad82d0a9cd57d9501fa2c989068992a97eb3c27836f206b" [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "libloading" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" dependencies = [ "cfg-if", "windows-targets", ] [[package]] name = "libredox" version = "0.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3af92c55d7d839293953fcd0fda5ecfe93297cfde6ffbdec13b41d99c0ba6607" dependencies = [ "bitflags 2.5.0", "libc", "redox_syscall", ] [[package]] name = "linux-raw-sys" version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "log" version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "lru" version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc" dependencies = [ "hashbrown", ] [[package]] name = "malloc_buf" version = "0.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" dependencies = [ "libc", ] [[package]] name = "memmap2" version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327" dependencies = [ "libc", ] [[package]] name = "memoffset" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" dependencies = [ "autocfg", ] [[package]] name = "nix" version = "0.24.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa52e972a9a719cecb6864fb88568781eb706bac2cd1d4f04a648542dbf78069" dependencies = [ "bitflags 1.3.2", "cfg-if", "libc", "memoffset", ] [[package]] name = "numtoa" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef" [[package]] name = "objc" version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" dependencies = [ "malloc_buf", ] [[package]] name = "objc-foundation" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" dependencies = [ "block", "objc", "objc_id", ] [[package]] name = "objc_id" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" dependencies = [ "objc", ] [[package]] name = "once_cell" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "paste" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" [[package]] name = "pkg-config" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" [[package]] name = "proc-macro2" version = "1.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] [[package]] name = "ratatui" version = "0.26.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcb12f8fbf6c62614b0d56eb352af54f6a22410c3b079eb53ee93c7b97dd31d8" dependencies = [ "bitflags 2.5.0", "cassowary", "compact_str", "indoc", "itertools", "lru", "paste", "stability", "strum", "termion", "unicode-segmentation", "unicode-width", ] [[package]] name = "redox_syscall" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ "bitflags 1.3.2", ] [[package]] name = "redox_termios" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20145670ba436b55d91fc92d25e71160fbfbdd57831631c8d7d36377a476f1cb" [[package]] name = "roff" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b833d8d034ea094b1ea68aa6d5c740e0d04bad9d16568d08ba6f76823a114316" [[package]] name = "rustix" version = "0.38.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" dependencies = [ "bitflags 2.5.0", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "rustversion" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80af6f9131f277a45a3fba6ce8e2258037bb0477a67e610d3c1fe046ab31de47" [[package]] name = "ryu" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" [[package]] name = "scoped-tls" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" [[package]] name = "smallvec" version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "smithay-client-toolkit" version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "870427e30b8f2cbe64bf43ec4b86e88fe39b0a84b3f15efd9c9c2d020bc86eb9" dependencies = [ "bitflags 1.3.2", "dlib", "lazy_static", "log", "memmap2", "nix", "pkg-config", "wayland-client", "wayland-cursor", "wayland-protocols", ] [[package]] name = "smithay-clipboard" version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a345c870a1fae0b1b779085e81b51e614767c239e93503588e54c5b17f4b0e8" dependencies = [ "smithay-client-toolkit", "wayland-client", ] [[package]] name = "stability" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebd1b177894da2a2d9120208c3386066af06a488255caabc5de8ddca22dbc3ce" dependencies = [ "quote", "syn 1.0.109", ] [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "strum" version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d8cec3501a5194c432b2b7976db6b7d10ec95c253208b45f83f7136aa985e29" dependencies = [ "strum_macros", ] [[package]] name = "strum_macros" version = "0.26.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6cf59daf282c0a494ba14fd21610a0325f9f90ec9d1231dea26bcb1d696c946" dependencies = [ "heck", "proc-macro2", "quote", "rustversion", "syn 2.0.58", ] [[package]] name = "syn" version = "1.0.109" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "syn" version = "2.0.58" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44cfb93f38070beee36b3fef7d4f5a16f27751d94b187b666a5cc5e9b0d30687" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "termion" version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "417813675a504dfbbf21bfde32c03e5bf9f2413999962b479023c02848c1c7a5" dependencies = [ "libc", "libredox", "numtoa", "redox_termios", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-segmentation" version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" [[package]] name = "unicode-width" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" [[package]] name = "utf8parse" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "wayland-client" version = "0.29.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f3b068c05a039c9f755f881dc50f01732214f5685e379829759088967c46715" dependencies = [ "bitflags 1.3.2", "downcast-rs", "libc", "nix", "scoped-tls", "wayland-commons", "wayland-scanner", "wayland-sys", ] [[package]] name = "wayland-commons" version = "0.29.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8691f134d584a33a6606d9d717b95c4fa20065605f798a3f350d78dced02a902" dependencies = [ "nix", "once_cell", "smallvec", "wayland-sys", ] [[package]] name = "wayland-cursor" version = "0.29.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6865c6b66f13d6257bef1cd40cbfe8ef2f150fb8ebbdb1e8e873455931377661" dependencies = [ "nix", "wayland-client", "xcursor", ] [[package]] name = "wayland-protocols" version = "0.29.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b950621f9354b322ee817a23474e479b34be96c2e909c14f7bc0100e9a970bc6" dependencies = [ "bitflags 1.3.2", "wayland-client", "wayland-commons", "wayland-scanner", ] [[package]] name = "wayland-scanner" version = "0.29.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f4303d8fa22ab852f789e75a967f0a2cdc430a607751c0499bada3e451cbd53" dependencies = [ "proc-macro2", "quote", "xml-rs", ] [[package]] name = "wayland-sys" version = "0.29.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be12ce1a3c39ec7dba25594b97b42cb3195d54953ddb9d3d95a7c3902bc6e9d4" dependencies = [ "dlib", "lazy_static", "pkg-config", ] [[package]] name = "which" version = "4.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" dependencies = [ "either", "home", "once_cell", "rustix", ] [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-wsapoll" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1eafc5f679c576995526e81635d0cf9695841736712b4e892f87abbe6fed3f28" dependencies = [ "winapi", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows-sys" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" [[package]] name = "windows_aarch64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" [[package]] name = "windows_i686_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" [[package]] name = "windows_i686_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" [[package]] name = "windows_x86_64_gnu" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" [[package]] name = "windows_x86_64_msvc" version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" [[package]] name = "x11-clipboard" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "980b9aa9226c3b7de8e2adb11bf20124327c054e0e5812d2aac0b5b5a87e7464" dependencies = [ "x11rb", ] [[package]] name = "x11rb" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "592b4883219f345e712b3209c62654ebda0bb50887f330cbd018d0f654bfd507" dependencies = [ "gethostname", "nix", "winapi", "winapi-wsapoll", "x11rb-protocol", ] [[package]] name = "x11rb-protocol" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56b245751c0ac9db0e006dc812031482784e434630205a93c73cfefcaabeac67" dependencies = [ "nix", ] [[package]] name = "xcursor" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a0ccd7b4a5345edfcd0c3535718a4e9ff7798ffc536bb5b5a0e26ff84732911" [[package]] name = "xml-rs" version = "0.8.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791978798f0597cfc70478424c2b4fdc2b7a8024aaff78497ef00f24ef674193" [[package]] name = "zerocopy" version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2", "quote", "syn 2.0.58", ] kmon-1.6.5/Cargo.toml0000644000000034730000000000100100160ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "kmon" version = "1.6.5" authors = ["Orhun Parmaksız "] include = [ "src/**/*", "Cargo.*", "LICENSE", "README.md", "CHANGELOG.md", ] description = "Linux kernel manager and activity monitor" homepage = "https://kmon.cli.rs" documentation = "https://github.com/orhun/kmon/blob/master/README.md" readme = "README.md" keywords = [ "linux", "kernel", "module", "activity", "monitor", ] categories = [ "command-line-utilities", "os", ] license = "GPL-3.0" repository = "https://github.com/orhun/kmon" [profile.bench] opt-level = 3 debug = 0 [profile.dev] opt-level = 0 debug = 2 panic = "abort" [profile.release] opt-level = 3 lto = true codegen-units = 1 debug = 0 panic = "abort" [profile.test] opt-level = 0 debug = 2 [dependencies.bytesize] version = "1.3.0" [dependencies.clap] version = "4.5.4" [dependencies.colorsys] version = "0.6.7" [dependencies.copypasta-ext] version = "0.4.4" [dependencies.enum-iterator] version = "2.0.0" [dependencies.ratatui] version = "0.26.1" features = ["termion"] default-features = false [dependencies.termion] version = "3.0.0" [dependencies.unicode-width] version = "0.1.11" [build-dependencies.clap] version = "4.4.7" [build-dependencies.clap_complete] version = "4.5.2" [build-dependencies.clap_mangen] version = "0.2.20" kmon-1.6.5/Cargo.toml.orig000064400000000000000000000021361046102023000134720ustar 00000000000000[package] name = "kmon" version = "1.6.5" description = "Linux kernel manager and activity monitor" authors = ["Orhun Parmaksız "] license = "GPL-3.0" readme = "README.md" documentation = "https://github.com/orhun/kmon/blob/master/README.md" homepage = "https://kmon.cli.rs" repository = "https://github.com/orhun/kmon" keywords = ["linux", "kernel", "module", "activity", "monitor"] categories = ["command-line-utilities", "os"] include = ["src/**/*", "Cargo.*", "LICENSE", "README.md", "CHANGELOG.md"] edition = "2021" [dependencies] ratatui = { version = "0.26.1", default-features = false, features = [ "termion", ] } termion = "3.0.0" bytesize = "1.3.0" unicode-width = "0.1.11" colorsys = "0.6.7" enum-iterator = "2.0.0" clap = "4.5.4" copypasta-ext = "0.4.4" [build-dependencies] clap_mangen = "0.2.20" clap_complete = "4.5.2" clap = "4.4.7" [profile.dev] opt-level = 0 debug = true panic = "abort" [profile.test] opt-level = 0 debug = true [profile.release] opt-level = 3 debug = false panic = "abort" lto = true codegen-units = 1 [profile.bench] opt-level = 3 debug = false kmon-1.6.5/LICENSE000064400000000000000000001045151046102023000116140ustar 00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . kmon-1.6.5/README.md000064400000000000000000000676551046102023000121030ustar 00000000000000


Linux Kernel Manager and Activity Monitor 🐧💻


**The kernel** is the part of the operating system that facilitates interactions between _hardware_ and _software_ components. On most systems, it is loaded on startup after the _bootloader_ and handles I/O requests as well as peripherals like keyboards, monitors, network adapters, and speakers. Typically, the kernel is responsible for **memory management**, **process management**, **device management**, **system calls**, and **security**. Applications use the **system call** mechanism for requesting a service from the operating system and most of the time, this request is passed to the kernel using a library provided by the operating system to invoke the related kernel function. While the kernel performs these low-level tasks, it's resident on a separate part of memory named **protected kernel space** which is not accessible by applications and other parts of the system. In contrast, applications like browsers, text editors, window managers or audio/video players use a different separate area of the memory, **user space**. This separation prevents user data and kernel data from interfering with each other and causing instability and slowness, as well as preventing malfunctioning application programs from crashing the entire operating system. There are different kernel designs due to the different ways of managing system calls and resources. For example, while **monolithic kernels** run all the operating system instructions in the same address space _for speed_, **microkernels** use different spaces for user and kernel services _for modularity_. Apart from those, there are **hybrid kernels**, **nanokernels**, and, **exokernels**. The hybrid kernel architecture is based on combining aspects of microkernel and monolithic kernels. **The Linux kernel** is the open-source, monolithic and, Unix-like operating system kernel that used in the Linux distributions, various embedded systems such as routers and as well as in the all Android-based systems. **Linus Torvalds** conceived and created the Linux kernel in 1991 and it's still being developed by thousands of developers today. It's a prominent example of **free and open source software** and it's used in other free software projects, notably the **GNU operating system**. Although the Linux-based operating systems dominate the most of computing, it still carries some of the design flaws which were quite a bit of debate in the early days of Linux. For example, it has the **largest footprint** and **the most complexity** over the other types of kernels. But it's a design feature that monolithic kernels inherent to have. These kind of design issues led developers to add new features and mechanisms to the Linux kernel which other kernels don't have. Unlike the standard monolithic kernels, the Linux kernel is also **modular**, accepting **loadable kernel modules (LKM)** that typically used to add support for new _hardware_ (as device drivers) and/or _filesystems_, or for adding _system calls_. Since LKMs could be loaded and unloaded to the system _at runtime_, they have the advantage of extending the kernel without rebooting and re-compiling. Thus, the kernel functionalities provided by modules would not reside in memory without being used and the related module can be unloaded in order to free memory and other resources. Loadable kernel modules are located in `/lib/modules` with the `.ko` (_kernel object_) extension in Linux. While the [lsmod](https://linux.die.net/man/8/lsmod) command could be used for listing the loaded kernel modules, [modprobe](https://linux.die.net/man/8/modprobe) or [insmod](https://linux.die.net/man/8/insmod)/[rmmod](https://linux.die.net/man/8/rmmod) is used for loading or unloading a kernel module. insmod/rmmod are used for modules independent of modprobe and without requiring an installation to `/lib/modules/$(uname -r)`. Here's a simple example of a Linux kernel module that prints a message when it's loaded and unloaded. The build and installation steps of the [module](https://github.com/orhun/kmon/blob/master/example/lkm_example.c) using a [Makefile](https://github.com/orhun/kmon/blob/master/example/Makefile) are shown below. ``` make # build sudo make install # install sudo modprobe lkm_example # load sudo modprobe -r lkm_example # unload ``` The [dmesg](https://linux.die.net/man/8/dmesg) command is used below to retrieve the message buffer of the kernel. ``` [16994.295552] [+] Example kernel module loaded. [16996.325674] [-] Example kernel module unloaded. ``` **kmon** provides a [text-based user interface](https://en.wikipedia.org/wiki/Text-based_user_interface) for managing the Linux kernel modules and monitoring the kernel activities. By managing, it means loading, unloading, blacklisting and showing the information of a module. These updates in the kernel modules, logs about the hardware and other kernel messages can be tracked with the real-time activity monitor in kmon. Since the usage of different tools like [dmesg](https://en.wikipedia.org/wiki/Dmesg) and [kmod](https://www.linux.org/docs/man8/kmod.html) are required for these tasks in Linux, kmon aims to gather them in a single terminal window and facilitate the usage as much as possible while keeping the functionality. kmon is written in [Rust](https://www.rust-lang.org/) and uses [tui-rs](https://github.com/fdehau/tui-rs) & [termion](https://github.com/redox-os/termion) libraries for its text-based user interface. ### Table of Contents - [Installation](#installation) - [Cargo](#cargo) - [Arch Linux](#arch-linux) - [Nixpkgs](#nixpkgs) - [Alpine Linux](#alpine-linux) - [Docker](#docker) - [Build](#build) - [Run](#run) - [Manual](#manual) - [Note](#note) - [Usage](#usage) - [Options](#options) - [Commands](#commands) - [Sort](#sort) - [Key Bindings](#key-bindings) - [Features](#features) - [Help](#help) - [Navigating & Scrolling](#navigating--scrolling) - [Scrolling Kernel Activities](#scrolling-kernel-activities) - [Smooth Scrolling](#smooth-scrolling) - [Options Menu](#options-menu) - [Block Sizes](#block-sizes) - [Block Positions](#block-positions) - [Kernel Information](#kernel-information) - [Module Information](#module-information) - [Displaying the dependent modules](#displaying-the-dependent-modules) - [Jumping to dependent modules](#jumping-to-dependent-modules) - [Searching a module](#searching-a-module) - [Loading a module](#loading-a-module) - [Unloading a module](#unloading-a-module) - [Blacklisting a module](#blacklisting-a-module) - [Reloading a module](#reloading-a-module) - [Clearing the ring buffer](#clearing-the-ring-buffer) - [Copy & Paste](#copy--paste) - [Sorting/reversing the kernel modules](#sortingreversing-the-kernel-modules) - [Customizing the colors](#customizing-the-colors) - [Supported colors](#supported-colors) - [Using a custom color](#using-a-custom-color) - [Changing the accent color](#changing-the-accent-color) - [Unicode symbols](#unicode-symbols) - [Setting the terminal tick rate](#setting-the-terminal-tick-rate) - [Roadmap](#roadmap) - [Accessibility](#accessibility) - [Dependencies](#dependencies) - [Features](#features-1) - [Testing](#testing) - [Resources](#resources) - [About the project](#about-the-project) - [Articles](#articles) - [In the media](#in-the-media) - [Gallery](#gallery) - [Social Media](#social-media) - [Funding](#funding) - [GitHub](#github) - [Patreon](#patreon) - [Open Collective](#open-collective) - [License](#license) - [Copyright](#copyright) ## Installation [![Packaging status](https://repology.org/badge/vertical-allrepos/kmon.svg)](https://repology.org/project/kmon/versions) ### Cargo **kmon** can be installed from [crates.io](https://crates.io/crates/kmon/) using Cargo if [Rust](https://www.rust-lang.org/tools/install) is installed. ``` cargo install kmon ``` The minimum supported Rust version (MSRV) is `1.70.0`. ### Arch Linux **kmon** can be installed from the Arch Linux [official repository](https://www.archlinux.org/packages/community/x86_64/kmon/). ``` pacman -S kmon ``` There is also a development package on the [AUR](https://aur.archlinux.org/packages/kmon-git/). Use your favorite [AUR helper](https://wiki.archlinux.org/index.php/AUR_helpers) to install. For example, ``` paru -S kmon-git ``` ### Nixpkgs **kmon** can be installed using [Nix package manager](https://nixos.org/nix/) from `nixpkgs-unstable` channel. ``` nix-channel --add https://nixos.org/channels/nixpkgs-unstable nix-channel --update nixpkgs nix-env -iA nixpkgs.kmon ``` On [NixOS](https://nixos.org/nixos/): ``` nix-channel --add https://nixos.org/channels/nixos-unstable nix-channel --update nixos nix-env -iA nixos.kmon ``` ### Alpine Linux **kmon** is available for [Alpine Edge](https://pkgs.alpinelinux.org/packages?name=kmon&branch=edge). It can be installed via [apk](https://wiki.alpinelinux.org/wiki/Alpine_Package_Keeper) after enabling the [community repository](https://wiki.alpinelinux.org/wiki/Repositories). ``` apk add kmon ``` ### Docker [![Docker Hub Build Status](https://img.shields.io/github/actions/workflow/status/orhun/kmon/docker.yml?color=000000&label=docker%20hub&style=flat-square)](https://hub.docker.com/r/orhunp/kmon) ``` docker run -it --cap-add syslog orhunp/kmon:tagname ``` #### Build ``` docker build -t kmon . ``` #### Run ``` docker run -it --cap-add syslog kmon ``` ### Manual 1. Download the latest binary from [releases](https://github.com/orhun/kmon/releases) section and pick between [glibc](https://en.wikipedia.org/wiki/Glibc) or [musl-libc](https://musl.libc.org/) binary. 2. To download the package compiled with [glibc](https://en.wikipedia.org/wiki/Glibc) run: ``` wget https://github.com/orhun/kmon/releases/download/v[VERSION]/kmon-[VERSION]-x86_64-unknown-linux-gnu.tar.gz ``` 3. To download the package compiled with [musl-libc](https://musl.libc.org/) run: ``` wget https://github.com/orhun/kmon/releases/download/v[VERSION]/kmon-[VERSION]-x86_64-unknown-linux-musl.tar.gz ``` 3. Extract the files. ``` tar -xvzf kmon-*.tar.gz ``` 4. Enter in the new folder. ``` cd kmon-[VERSION] ``` 5. Run the binary. ``` ./kmon ``` 6. Move binary to `/usr/local/bin/` for running it from the terminal using `kmon` command. 7. Man page and shell completions are generated at build time in `target` directory. #### Note [libxcb](https://xcb.freedesktop.org/) should be installed for using the copy/paste commands of X11. e.g: Install `libxcb1-dev` package for Debian/Ubuntu[\*](https://github.com/orhun/kmon/issues/2) and `libxcb-devel` package for Fedora/openSUSE/Void Linux. ## Usage ``` kmon [OPTIONS] [COMMAND] ``` ### Options ``` -a, --accent-color Set the accent color using hex or color name [default: white] -c, --color Set the main color using hex or color name [default: darkgray] -t, --tickrate Set the refresh rate of the terminal [default: 250] -r, --reverse Reverse the kernel module list -u, --unicode Show Unicode symbols for the block titles -h, --help Print help information -V, --version Print version information ``` ### Commands ``` sort Sort kernel modules ``` #### Sort ``` kmon sort [OPTIONS] ``` **Options:** ``` -s, --size Sort modules by their sizes -n, --name Sort modules by their names -d, --dependent Sort modules by their dependent modules -h, --help Print help information ``` ## Key Bindings | | | | ----------------------- | ------------------------------------- | | `[?], F1` | Help | | `right/left, h/l` | Switch between blocks | | `up/down, k/j, alt-k/j` | Scroll up/down [selected block] | | `pgup/pgdown` | Scroll up/down [kernel activities] | | `` | Scroll up/down [module information] | | `alt-h/l` | Scroll right/left [kernel activities] | | `ctrl-t/b, home/end` | Scroll to top/bottom [module list] | | `alt-e/s` | Expand/shrink the selected block | | `ctrl-x` | Change the block position | | `ctrl-l/u, alt-c` | Clear the kernel ring buffer | | `[d], alt-d` | Show the dependent modules | | `[1]..[9]` | Jump to the dependent module | | `[\], tab, backtab` | Show the next kernel information | | `[/], s, enter` | Search a kernel module | | `[+], i, insert` | Load a kernel module | | `[-], u, backspace` | Unload the kernel module | | `[x], b, delete` | Blacklist the kernel module | | `ctrl-r, alt-r` | Reload the kernel module | | `m, o` | Show the options menu | | `y/n` | Execute/cancel the command | | `c/v` | Copy/paste | | `r, F5` | Refresh | | `q, ctrl-c/d, ESC` | Quit | ## Features ### Help Press '`?`' while running the terminal UI to see key bindings. ![Help](https://user-images.githubusercontent.com/24392180/76685660-8d155f80-6626-11ea-9aa6-f3eb26a3869f.gif) ### Navigating & Scrolling `Arrow keys` are used for navigating between blocks and scrolling. ![Navigating & Scrolling](https://user-images.githubusercontent.com/24392180/76685750-26447600-6627-11ea-99fd-157449c9529f.gif) #### Scrolling Kernel Activities Some kernel messages might be long enough for not fitting into the kernel activities block since they are not wrapped. In this situation, kernel activities can be scrolled horizontally with `alt-h & alt-l` keys. Vertical scrolling mechanism is the same as other blocks. ![Scrolling Kernel Activities](https://user-images.githubusercontent.com/24392180/76685862-fe094700-6627-11ea-9996-4ff1d177baf3.gif) #### Smooth Scrolling `alt-j & alt-k` keys can be used to scroll kernel activity and module information blocks slowly. ![Smooth Scrolling](https://user-images.githubusercontent.com/24392180/76685907-4aed1d80-6628-11ea-96b7-a5bc0597455b.gif) ### Options Menu `m` and `o` keys can be used as a shortcut for kernel management operations. When pressed, an options menu will be provided for managing the currently selected kernel module. ![Options Menu](https://user-images.githubusercontent.com/24392180/140408275-5c400e39-c1e6-4484-85fe-f39160a842a0.gif) ### Block Sizes `alt-e & alt-s` keys can be used for expanding/shrinking the selected block. ![Block Sizes](https://user-images.githubusercontent.com/24392180/89716231-f8841300-d9b3-11ea-9cea-ee9816174336.gif) ### Block Positions `ctrl-x` key can be used for changing the positions of blocks. ![Block Positions](https://user-images.githubusercontent.com/24392180/90258934-e68dee80-de51-11ea-951a-ec5a301608a6.gif) ### Kernel Information Use one of the `\, tab, backtab` keys to switch between kernel release, version and platform information. ![Kernel Information](https://user-images.githubusercontent.com/24392180/76686943-9f949680-6630-11ea-9045-a8f83313faa1.gif) ### Module Information The status of a kernel module is shown on selection. ![Module Information](https://user-images.githubusercontent.com/24392180/76685957-b931e000-6628-11ea-8657-76047deee681.gif) #### Displaying the dependent modules Use one of the `d, alt-d` keys to show all the dependent modules of the selected module. ![Displaying the dependent modules](https://user-images.githubusercontent.com/24392180/80925098-d6b43800-8d95-11ea-8b41-da7d93fd12f8.gif) #### Jumping to dependent modules For jumping to a dependent kernel module from its parent module, `number keys` (1-9) can be used for specifying the index of the module on the _Used By_ column. ![Dependency Information](https://user-images.githubusercontent.com/24392180/76685972-eaaaab80-6628-11ea-94dd-630e07827949.gif) ### Searching a module Switch to the search area with arrow keys or using one of the `/, s, enter` and provide a search query for the module name. ![Searching a module](https://user-images.githubusercontent.com/24392180/76686001-23e31b80-6629-11ea-9e9a-ff92c6a05cdd.gif) ### Loading a module For adding a module to the Linux kernel, switch to load mode with one of the `+, i, insert` keys and provide the name of the module to load. Then confirm/cancel the execution of the load command with `y/n`. ![Loading a module](https://user-images.githubusercontent.com/24392180/76686027-64429980-6629-11ea-852f-1316ff08ec80.gif) The command that used for loading a module: ``` modprobe || insmod .ko ``` ### Unloading a module Use one of the `-, u, backspace` keys to remove the selected module from the Linux kernel. ![Unloading a module](https://user-images.githubusercontent.com/24392180/76686045-8b996680-6629-11ea-9d8c-c0f5b367e269.gif) The command that used for removing a module: ``` modprobe -r || rmmod ``` ### Blacklisting a module [Blacklisting](https://wiki.archlinux.org/index.php/Kernel_module#Blacklisting) is a mechanism to prevent the kernel module from loading. To blacklist the selected module, use one of the `x, b, delete` keys and confirm the execution. ![Blacklisting a module](https://user-images.githubusercontent.com/24392180/77003935-48176300-696f-11ea-9047-41f6a934be6e.gif) The command that used for blacklisting a module: ``` if ! grep -q /etc/modprobe.d/blacklist.conf; then echo 'blacklist ' >> /etc/modprobe.d/blacklist.conf echo 'install /bin/false' >> /etc/modprobe.d/blacklist.conf fi ``` ### Reloading a module Use `ctrl-r` or `alt-r` key for reloading the selected module. ![Reloading a module](https://user-images.githubusercontent.com/24392180/80925109-f3507000-8d95-11ea-9004-4063907f0cfc.gif) The command that used for reloading a module: ``` modprobe -r || rmmod && modprobe || insmod .ko ``` ### Clearing the ring buffer The kernel ring buffer can be cleared with using one of the `ctrl-l/u, alt-c` keys. ![Clearing the ring buffer](https://user-images.githubusercontent.com/24392180/76686162-87217d80-662a-11ea-9ced-36bb1e7a942b.gif) ``` dmesg --clear ``` ### Copy & Paste `c/v` keys are set for copy/paste operations. ![Copy & Paste](https://user-images.githubusercontent.com/24392180/76686463-986b8980-662c-11ea-9762-9137b32c5cca.gif) Use `ctrl-c/ctrl-v` for copying and pasting while in input mode. ### Sorting/reversing the kernel modules `sort` subcommand can be used for sorting the kernel modules by their names, sizes or dependent modules. ``` kmon sort --name kmon sort --size kmon sort --dependent ``` ![Sorting the kernel modules](https://user-images.githubusercontent.com/24392180/78900376-70324780-7a7f-11ea-813e-78972fc3c880.gif) Also the `-r, --reverse` flag is used for reversing the kernel module list. ``` kmon --reverse ``` ![Reversing the kernel modules](https://user-images.githubusercontent.com/24392180/78901094-812f8880-7a80-11ea-85cf-2a0c6ac6354a.gif) ### Customizing the colors kmon uses the colors of the terminal as default but the highlighting color could be specified with `-c, --color` option. Alternatively, default text color can be set via `-a, --accent-color` option. #### Supported colors Supported terminal colors are `black, red, green, yellow, blue, magenta, cyan, gray, darkgray, lightred, lightgreen, lightyellow, lightblue, lightmagenta, lightcyan, white`. ``` kmon --color red ``` ![Supported Colors](https://user-images.githubusercontent.com/24392180/76773518-a697e200-67b3-11ea-838b-6816193b88c5.gif) #### Using a custom color Provide a hexadecimal value for the color to use. ``` kmon --color 19683a ``` ![Using a custom color](https://user-images.githubusercontent.com/24392180/76772858-a0edcc80-67b2-11ea-86ea-9b138a0b937b.gif) #### Changing the accent color Default text color might cause readability issues on some themes that have transparency. `-a, --accent-color` option can be used similarly to the `-c, --color` option for overcoming this issue. ``` kmon --color 6f849c --accent-color e35760 ``` ![Changing the accent color](https://user-images.githubusercontent.com/24392180/89355576-61be0a80-d6c4-11ea-9693-f152edf5be38.gif) ### Unicode symbols Use `-u, --unicode` flag for showing Unicode symbols for the block titles. ``` kmon --unicode ``` ![Unicode symbols](https://user-images.githubusercontent.com/24392180/76711734-74d73a80-6723-11ea-8eae-180e69a5395c.gif) ### Setting the terminal tick rate `-t, --tickrate` option can be used for setting the refresh interval of the terminal UI in milliseconds. ![Setting the terminal tick rate](https://user-images.githubusercontent.com/24392180/76807925-1aa7a980-67f7-11ea-9af5-bb80849f5629.gif) ## Roadmap kmon aims to be a standard tool for Linux kernel management while supporting most of the Linux distributions. ### Accessibility For achieving this goal, kmon should be accessible from different package managers such as [Snap](https://snapcraft.io/)[\*](https://forum.snapcraft.io/t/unable-to-load-modules-to-kernel-and-get-module-information/16151) and [RPM](https://rpm.org/). ### Dependencies It is required to have the essential tools like [dmesg](https://en.wikipedia.org/wiki/Dmesg) and [kmod](https://www.linux.org/docs/man8/kmod.html) on the system for kmon to work as expected. Thus the next step would be using just the system resources for these functions. ### Features Management actions about the Linux kernel should be applicable in kmon for minimizing the dependence on to command line and other tools. ### Testing kmon should be tested and reported on different architectures for further development and support. ## Resources ### About the project - [Code of conduct](https://github.com/orhun/kmon/blob/master/CODE_OF_CONDUCT.md) - [Contributing](https://github.com/orhun/kmon/blob/master/CONTRIBUTING.md) - [Creating a release](https://github.com/orhun/kmon/blob/master/RELEASE.md) ### Articles - [Exploring the Linux Kernel by Bob Cromwell](https://cromwell-intl.com/open-source/linux-kernel-details.html) - [Anatomy of the Linux loadable kernel module by Terenceli](https://terenceli.github.io/%E6%8A%80%E6%9C%AF/2018/06/02/linux-loadable-module) - [Managing kernel modules with kmod by Lucas De Marchi](https://elinux.org/images/8/89/Managing_Kernel_Modules_With_kmod.pdf) ### In the media - [Manage And Monitor Linux Kernel Modules With Kmon](https://ostechnix.com/manage-and-monitor-linux-kernel-modules-with-kmon/) ( OSTechNix) - [Kmon The Linux Kernel Management And Monitoring Software](https://www.youtube.com/watch?v=lukxf6CnR2o) (Brodie Robertson on YouTube) ### Gallery | Fedora 31 | Debian 10 | Manjaro 19 | | :---------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------------------------: | | ![kmon on fedora](https://user-images.githubusercontent.com/24392180/76520554-27817180-6474-11ea-9966-e564f38c8a6a.png) | ![kmon on debian](https://user-images.githubusercontent.com/24392180/76514129-79bc9580-6468-11ea-9013-e32fbbdc1108.png) | ![kmon on manjaro](https://user-images.githubusercontent.com/24392180/76940351-1f5d8200-690b-11ea-8fe9-1d751fe102c5.png) | | Ubuntu 18.04 | openSUSE | Void Linux | | :---------------------------------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------: | | ![kmon on ubuntu](https://user-images.githubusercontent.com/24392180/76690341-18571b00-6650-11ea-85c9-3f511c054194.png) | ![kmon on opensuse](https://user-images.githubusercontent.com/24392180/77414512-38b27280-6dd2-11ea-888c-9bf6f7245387.png) | ![kmon on voidlinux](https://user-images.githubusercontent.com/24392180/77417004-c9d71880-6dd5-11ea-82b2-f6c7df9a05c3.png) | ### Social Media - Follow [@kmonitor\_](https://twitter.com/kmonitor_) on Twitter - Follow the [author](https://orhun.dev/): - [@orhun](https://github.com/orhun) on GitHub - [@orhunp\_](https://twitter.com/orhunp_) on Twitter ## Funding ### GitHub Support the development of my projects by supporting me on [GitHub Sponsors](https://github.com/sponsors/orhun). ### Patreon [![Patreon Button](https://user-images.githubusercontent.com/24392180/77826872-e7c8b400-711a-11ea-8f51-502e3a4d46b9.png)](https://www.patreon.com/join/orhunp) ### Open Collective [![Open Collective backers](https://img.shields.io/opencollective/backers/kmon?color=000000&style=flat-square)](https://opencollective.com/kmon) [![Open Collective sponsors](https://img.shields.io/opencollective/sponsors/kmon?color=000000&style=flat-square)](https://opencollective.com/kmon) Support the open source development efforts by becoming a [backer](https://opencollective.com/kmon/contribute/backer-15060/checkout) or [sponsor](https://opencollective.com/kmon/contribute/sponsor-15061/checkout). [![Open Collective Button](https://user-images.githubusercontent.com/24392180/77827001-d0d69180-711b-11ea-817e-855ec4cf56f7.png)](https://opencollective.com/kmon/donate) ## License GNU General Public License ([3.0](https://www.gnu.org/licenses/gpl.txt)) ## Copyright Copyright © 2020-2024, [Orhun Parmaksız](mailto:orhunparmaksiz@gmail.com) kmon-1.6.5/src/app.rs000064400000000000000000000433521046102023000125250ustar 00000000000000use crate::event::Event; use crate::kernel::cmd::ModuleCommand; use crate::kernel::lkm::KernelModules; use crate::kernel::log::KernelLogs; use crate::kernel::Kernel; use crate::style::{Style, StyledText, Symbol}; use crate::util; use crate::widgets::StatefulList; use copypasta_ext::display::DisplayServer as ClipboardDisplayServer; use copypasta_ext::ClipboardProviderExt; use enum_iterator::Sequence; use ratatui::layout::{Alignment, Constraint, Direction, Layout, Rect}; use ratatui::style::Style as TuiStyle; use ratatui::text::{Line, Span, Text}; use ratatui::widgets::{ Block as TuiBlock, Borders, Clear, List, ListItem, Paragraph, Row, Table, Wrap, }; use ratatui::Frame; use std::fmt::{Debug, Display, Formatter}; use std::slice::Iter; use std::sync::mpsc::Sender; use termion::event::Key; use unicode_width::UnicodeWidthStr; /* Table header of the module table */ pub const TABLE_HEADER: &[&str] = &[" Module", "Size", "Used by"]; /* Available options in the module management menu */ const OPTIONS: &[(&str, &str)] = &[ ("unload", "Unload the module"), ("reload", "Reload the module"), ("blacklist", "Blacklist the module"), ("dependent", "Show the dependent modules"), ("copy", "Copy the module name"), ("load", "Load a kernel module"), ("clear", "Clear the ring buffer"), ]; /* Supported directions of scrolling */ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ScrollDirection { Up, Down, Left, Right, Top, Bottom, } impl ScrollDirection { /** * Return iterator of the available scroll directions. * * @return Iter */ #[allow(dead_code)] pub fn iter() -> Iter<'static, ScrollDirection> { [ ScrollDirection::Up, ScrollDirection::Down, ScrollDirection::Left, ScrollDirection::Right, ScrollDirection::Top, ScrollDirection::Bottom, ] .iter() } } /* Main blocks of the terminal */ #[derive(Clone, Copy, Debug, PartialEq, Eq, Sequence)] pub enum Block { UserInput, ModuleTable, ModuleInfo, Activities, } /* Sizes of the terminal blocks */ pub struct BlockSize { pub input: u16, pub info: u16, pub activities: u16, } /* Default initialization values for BlockSize */ impl Default for BlockSize { fn default() -> Self { Self { input: 60, info: 40, activities: 25, } } } /* User input mode */ #[derive(Clone, Copy, Debug, PartialEq, Eq, Sequence)] pub enum InputMode { None, Search, Load, } impl InputMode { /** * Check if input mode is set. * * @return bool */ pub fn is_none(self) -> bool { self == Self::None } } /* Implementation of Display for using InputMode members as string */ impl Display for InputMode { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut input_mode = *self; if input_mode.is_none() { input_mode = match InputMode::first().and_then(|v| v.next()) { Some(v) => v, None => input_mode, } } write!(f, "{input_mode:?}") } } /* Application settings and related methods */ pub struct App { pub selected_block: Block, pub default_block: Block, pub block_size: BlockSize, pub block_index: u8, pub input_mode: InputMode, pub input_query: String, pub options: StatefulList<(String, String)>, pub show_options: bool, style: Style, clipboard: Option>, } impl App { /** * Create a new app instance. * * @param Block * @param Style * @return App */ pub fn new(block: Block, style: Style) -> Self { Self { selected_block: block, default_block: block, block_size: BlockSize::default(), block_index: 0, input_mode: InputMode::None, input_query: String::new(), options: StatefulList::with_items( OPTIONS .iter() .map(|(option, text)| { (String::from(*option), String::from(*text)) }) .collect(), ), show_options: false, style, clipboard: match ClipboardDisplayServer::select().try_context() { None => { eprintln!("failed to initialize clipboard, no suitable clipboard provider found"); None } clipboard => clipboard, }, } } /* Reset app properties to default. */ pub fn refresh(&mut self) { self.selected_block = self.default_block; self.block_size = BlockSize::default(); self.block_index = 0; self.input_mode = InputMode::None; self.input_query = String::new(); self.options.state.select(Some(0)); self.show_options = false; } /** * Get style depending on the selected state of the block. * * @param block * @return TuiStyle */ pub fn block_style(&self, block: Block) -> TuiStyle { if self.show_options { self.style.colored } else if block == self.selected_block { self.style.default } else { self.style.colored } } /** * Get the size of the selected block. * * @return u16 */ pub fn block_size(&mut self) -> &mut u16 { match self.selected_block { Block::ModuleInfo => &mut self.block_size.info, Block::Activities => &mut self.block_size.activities, _ => &mut self.block_size.input, } } /** * Get clipboard contents as String. * * @return contents */ pub fn get_clipboard_contents(&mut self) -> String { if let Some(clipboard) = self.clipboard.as_mut() { if let Ok(contents) = clipboard.get_contents() { return contents; } } String::new() } /** * Set clipboard contents. * * @param contents */ pub fn set_clipboard_contents(&mut self, contents: &str) { if let Some(clipboard) = self.clipboard.as_mut() { if let Err(e) = clipboard.set_contents(contents.to_string()) { eprintln!("{e}"); } } } /** * Show help message on the information block. * * @param kernel_modules */ pub fn show_help_message(&mut self, kernel_modules: &mut KernelModules<'_>) { let key_bindings: Vec<(&str, &str)> = util::KEY_BINDINGS.to_vec(); let mut help_text = Vec::new(); let mut help_text_raw = Vec::new(); for (key, desc) in &key_bindings { help_text.push(Line::from(Span::styled( format!("{}:", &key), self.style.colored, ))); help_text_raw.push(format!("{key}:")); help_text.push(Line::from(Span::styled( format!("{}{}", self.style.unicode.get(Symbol::Blank), &desc), self.style.default, ))); help_text_raw.push(format!(" {}", &desc)); } kernel_modules.info_scroll_offset = 0; kernel_modules.command = ModuleCommand::None; kernel_modules.current_name = format!("!Help{}", self.style.unicode.get(Symbol::Helmet)); kernel_modules .current_info .set(Text::from(help_text), help_text_raw.join("\n")); } /** * Show dependent modules on the information block. * * @param kernel_modules */ #[allow(clippy::nonminimal_bool)] pub fn show_dependent_modules( &mut self, kernel_modules: &mut KernelModules<'_>, ) { let dependent_modules_list = kernel_modules.default_list [kernel_modules.index][2] .split(' ') .last() .unwrap_or("-") .split(',') .collect::>(); if !(dependent_modules_list[0] == "-" || kernel_modules.current_name.contains("Dependent modules")) || cfg!(test) { kernel_modules.info_scroll_offset = 0; kernel_modules.command = ModuleCommand::None; kernel_modules.current_name = format!( "!Dependent modules of {}{}", kernel_modules.current_name, self.style.unicode.get(Symbol::HistoricSite) ); let mut dependent_modules = Vec::new(); for module in &dependent_modules_list { dependent_modules.push(Line::from(vec![ Span::styled("-", self.style.colored), Span::styled(format!(" {module}"), self.style.default), ])); } kernel_modules.current_info.set( Text::from(dependent_modules), kernel_modules.current_name.clone(), ); } } /** * Draw a block according to the index. * * @param frame * @param area * @param kernel */ pub fn draw_dynamic_block( &mut self, frame: &mut Frame, area: Rect, kernel: &mut Kernel, ) { match self.block_index { 0 => self.draw_kernel_modules(frame, area, &mut kernel.modules), 1 => self.draw_module_info(frame, area, &mut kernel.modules), _ => self.draw_kernel_activities(frame, area, &mut kernel.logs), } if self.block_index < 2 { self.block_index += 1; } else { self.block_index = 0; } } /** * Draw a paragraph widget for using as user input. * * @param frame * @param area * @param tx */ pub fn draw_user_input( &self, frame: &mut Frame, area: Rect, tx: &Sender>, ) { frame.render_widget( Paragraph::new(Span::raw(self.input_query.to_string())) .block( TuiBlock::default() .border_style(match self.selected_block { Block::UserInput => { if self.input_mode.is_none() { tx.send(Event::Input(Key::Char('\n'))).unwrap(); } self.style.default } _ => self.style.colored, }) .borders(Borders::ALL) .title(Span::styled( format!( "{}{}", self.input_mode, match self.input_mode { InputMode::Load => self.style.unicode.get(Symbol::Anchor), _ => self.style.unicode.get(Symbol::Magnifier), } ), self.style.bold, )), ) .alignment(Alignment::Left), area, ); } /** * Draw a paragraph widget for showing the kernel information. * * @param frame * @param area * @param info */ pub fn draw_kernel_info(&self, frame: &mut Frame, area: Rect, info: &[String]) { frame.render_widget( Paragraph::new(Span::raw(&info[1])) .block( TuiBlock::default() .border_style(self.style.colored) .borders(Borders::ALL) .title(Span::styled( &format!( "{}{}", info[0], self.style.unicode.get(Symbol::Gear) ), self.style.bold, )) .title_alignment(Alignment::Center), ) .alignment(Alignment::Center) .wrap(Wrap { trim: true }), area, ); } /** * Configure and draw kernel modules table. * * @param frame * @param area * @param kernel_modules */ pub fn draw_kernel_modules( &mut self, frame: &mut Frame, area: Rect, kernel_modules: &mut KernelModules<'_>, ) { /* Filter the module list depending on the input query. */ let mut kernel_module_list = kernel_modules.default_list.clone(); if (self.input_mode == InputMode::None || self.input_mode == InputMode::Search) && !self.input_query.is_empty() { kernel_module_list.retain(|module| { module[0] .to_lowercase() .contains(&self.input_query.to_lowercase()) }); } /* Append '...' if dependent modules exceed the block width. */ let dependent_width = (area.width / 2).saturating_sub(7) as usize; for module in &mut kernel_module_list { if module[2].len() > dependent_width { module[2].truncate(dependent_width); module[2] = format!("{}...", module[2]); } } kernel_modules.list = kernel_module_list; /* Set the scroll offset for modules. */ let modules_scroll_offset = area .height .checked_sub(5) .and_then(|height| kernel_modules.index.checked_sub(height as usize)) .unwrap_or(0); /* Set selected state of the modules and render the table widget. */ frame.render_widget( Table::new( kernel_modules .list .iter() .skip(modules_scroll_offset) .enumerate() .map(|(i, item)| { let item = item.iter().map(|v| v.to_string()); if Some(i) == kernel_modules .index .checked_sub(modules_scroll_offset) { Row::new(item).style(self.style.default) } else { Row::new(item).style(self.style.colored) } }), &[ Constraint::Percentage(30), Constraint::Percentage(20), Constraint::Percentage(50), ], ) .header( Row::new(TABLE_HEADER.iter().map(|v| v.to_string())) .style(self.style.bold), ) .block( TuiBlock::default() .border_style(self.block_style(Block::ModuleTable)) .borders(Borders::ALL) .title(Span::styled( format!( "Loaded Kernel Modules {}{}/{}{} {}{}%{}", self.style.unicode.get(Symbol::LeftBracket), match kernel_modules.list.len() { 0 => kernel_modules.index, _ => kernel_modules.index + 1, }, kernel_modules.list.len(), self.style.unicode.get(Symbol::RightBracket), self.style.unicode.get(Symbol::LeftBracket), if !kernel_modules.list.is_empty() { ((kernel_modules.index + 1) as f64 / kernel_modules.list.len() as f64 * 100.0) as u64 } else { 0 }, self.style.unicode.get(Symbol::RightBracket), ), self.style.bold, )), ), area, ); if self.show_options { self.draw_options_menu(frame, area, kernel_modules); } } /** * Draws the options menu as a popup. * * @param frame * @param area */ pub fn draw_options_menu( &mut self, frame: &mut Frame, area: Rect, kernel_modules: &mut KernelModules<'_>, ) { let block_title = format!( "Options ({})", kernel_modules.list[kernel_modules.index][0] .split_whitespace() .next() .unwrap_or("?") .trim() ); let items = self .options .items .iter() .map(|(_, text)| ListItem::new(Span::raw(format!(" {text}")))) .collect::>>(); let (mut percent_y, mut percent_x) = (40, 60); let text_height = items.iter().map(|v| v.height() as f32).sum::() + 3.; if area.height.checked_sub(5).unwrap_or(area.height) as f32 > text_height { percent_y = ((text_height / area.height as f32) * 100.) as u16; } if let Some(text_width) = self .options .items .iter() .map(|(_, text)| text.width()) .chain(vec![block_title.width()]) .max() .map(|v| v as f32 + 7.) { if area.width.checked_sub(2).unwrap_or(area.width) as f32 > text_width { percent_x = ((text_width / area.width as f32) * 100.) as u16; } } let popup_layout = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Percentage((100 - percent_y) / 2), Constraint::Percentage(percent_y), Constraint::Percentage((100 - percent_y) / 2), ] .as_ref(), ) .split(area); let popup_rect = Layout::default() .direction(Direction::Horizontal) .constraints( [ Constraint::Percentage((100 - percent_x) / 2), Constraint::Percentage(percent_x), Constraint::Percentage((100 - percent_x) / 2), ] .as_ref(), ) .split(popup_layout[1])[1]; frame.render_widget(Clear, popup_rect); frame.render_stateful_widget( List::new(items) .block( TuiBlock::default() .title(Span::styled(block_title, self.style.bold)) .title_alignment(Alignment::Center) .style(self.style.default) .borders(Borders::ALL), ) .style(self.style.colored) .highlight_style(self.style.default), popup_rect, &mut self.options.state, ); } /** * Draw a paragraph widget for showing module information. * * @param frame * @param area * @param kernel_modules */ pub fn draw_module_info( &self, frame: &mut Frame, area: Rect, kernel_modules: &mut KernelModules<'_>, ) { frame.render_widget( Paragraph::new(kernel_modules.current_info.get()) .block( TuiBlock::default() .border_style(self.block_style(Block::ModuleInfo)) .borders(Borders::ALL) .title(Span::styled( format!( "{}{}", kernel_modules.get_current_command().title, self.style.unicode.get( kernel_modules.get_current_command().symbol ) ), self.style.bold, )), ) .alignment( if kernel_modules.command.is_none() && !kernel_modules .current_info .raw_text .contains("Execution Error\n") { Alignment::Left } else { Alignment::Center }, ) .wrap(Wrap { trim: true }) .scroll((kernel_modules.info_scroll_offset as u16, 0)), area, ); } /** * Draw a paragraph widget for showing kernel activities. * * @param frame * @param area * @param kernel_logs */ pub fn draw_kernel_activities( &self, frame: &mut Frame, area: Rect, kernel_logs: &mut KernelLogs, ) { frame.render_widget( Paragraph::new(StyledText::default().stylize_data( kernel_logs.select(area.height, 2), "] ", self.style.clone(), )) .block( TuiBlock::default() .border_style(self.block_style(Block::Activities)) .borders(Borders::ALL) .title(Span::styled( format!( "Kernel Activities{}", self.style.unicode.get(Symbol::HighVoltage) ), self.style.bold, )), ) .alignment(Alignment::Left), area, ); } } #[cfg(test)] mod tests { use super::*; use crate::event::Events; use crate::kernel::info; use crate::kernel::lkm::ListArgs; use clap::ArgMatches; use ratatui::backend::TestBackend; use ratatui::Terminal; #[test] fn test_app() { let args = ArgMatches::default(); let mut kernel_modules = KernelModules::new(ListArgs::new(&args), Style::new(&args)); let mut app = App::new(Block::ModuleTable, kernel_modules.style.clone()); app.set_clipboard_contents("test"); assert_ne!("x", app.get_clipboard_contents()); assert_eq!(app.style.default, app.block_style(Block::ModuleTable)); assert_eq!(app.style.colored, app.block_style(Block::Activities)); let mut kernel_logs = KernelLogs::default(); let backend = TestBackend::new(20, 10); let mut terminal = Terminal::new(backend).unwrap(); terminal .draw(|f| { let size = f.size(); app.selected_block = Block::UserInput; app.draw_user_input(f, size, &Events::new(100, &kernel_logs).tx); app.draw_kernel_info(f, size, &info::KernelInfo::new().current_info); app.input_query = String::from("a"); app.draw_kernel_modules(f, size, &mut kernel_modules); app.draw_module_info(f, size, &mut kernel_modules); app.draw_kernel_activities(f, size, &mut kernel_logs); }) .unwrap(); } #[test] fn test_input_mode() { let mut input_mode = InputMode::Load; assert!(!input_mode.is_none()); assert!(input_mode.to_string().contains("Load")); input_mode = InputMode::None; assert!(input_mode.to_string().contains("Search")); } } kmon-1.6.5/src/args.rs000064400000000000000000000047711046102023000127030ustar 00000000000000use clap::{Arg, ArgAction, Command as App}; /* ASCII format of the project logo */ const ASCII_LOGO: &str = " `` ```````````` ```` ``````````` ``````````` :NNs `hNNNNNNNNNNNNh` sNNNy yNNNNNNNNNN+ dNNNNNNNNNN: /MMMydMMyyyyyyydMMMMdhMMMMy yMMMyyyhMMMo dMMMyyydMMM/ /MMMMMMM` oMMMMMMMMMMy yMMM` -MMMo dMMN /MMM/ /MMMs:::hhhs oMMM+:::MMMNhhhNMMMdhhdMMMmhhhNMMN /MMM/ :mmm/ dmmh +mmm- `mmmmmmmmmmmmmmmmmmmmmmmmmd /mmm: ``` ``` ``` `````````````````````````` ```"; /** * Parse command line arguments using clap. * * @return App */ pub fn get_args() -> App { App::new(env!("CARGO_PKG_NAME")) .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(format!( "{} {}\n{}\n{}\n\n{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS"), env!("CARGO_PKG_DESCRIPTION"), "Press '?' while running the terminal UI to see key bindings." )) .before_help(ASCII_LOGO) .arg( Arg::new("accent-color") .short('a') .long("accent-color") .value_name("COLOR") .default_value("white") .help("Set the accent color using hex or color name") .num_args(1), ) .arg( Arg::new("color") .short('c') .long("color") .value_name("COLOR") .default_value("darkgray") .help("Set the main color using hex or color name") .num_args(1), ) .arg( Arg::new("rate") .short('t') .long("tickrate") .value_name("MS") .default_value("250") .help("Set the refresh rate of the terminal") .num_args(1), ) .arg( Arg::new("reverse") .short('r') .long("reverse") .help("Reverse the kernel module list") .action(ArgAction::SetTrue), ) .arg( Arg::new("unicode") .short('u') .long("unicode") .help("Show Unicode symbols for the block titles") .action(ArgAction::SetTrue), ) .subcommand( App::new("sort") .about("Sort kernel modules") .arg( Arg::new("size") .short('s') .long("size") .help("Sort modules by their sizes") .action(ArgAction::SetTrue), ) .arg( Arg::new("name") .short('n') .long("name") .help("Sort modules by their names") .action(ArgAction::SetTrue), ) .arg( Arg::new("dependent") .short('d') .long("dependent") .help("Sort modules by their dependent modules") .action(ArgAction::SetTrue), ), ) } #[cfg(test)] mod tests { use super::*; #[test] fn test_args() { get_args().debug_assert(); } } kmon-1.6.5/src/event.rs000064400000000000000000000047171046102023000130700ustar 00000000000000use crate::kernel::log::KernelLogs; use std::io; use std::sync::mpsc; use std::thread; use std::time::Duration; use termion::event::Key; use termion::input::TermRead; /* Terminal event methods */ pub enum Event { Input(I), Kernel(String), Tick, } /* Terminal events */ #[allow(dead_code)] pub struct Events { pub tx: mpsc::Sender>, pub rx: mpsc::Receiver>, input_handler: thread::JoinHandle<()>, kernel_handler: thread::JoinHandle<()>, tick_handler: thread::JoinHandle<()>, } impl Events { /** * Create a new events instance. * * @param refresh_rate * @param kernel_logs * @return Events */ pub fn new(refresh_rate: u64, kernel_logs: &KernelLogs) -> Self { /* Convert refresh rate to Duration from milliseconds. */ let refresh_rate = Duration::from_millis(refresh_rate); /* Create a new asynchronous channel. */ let (tx, rx) = mpsc::channel(); /* Handle inputs using stdin stream and sender of the channel. */ let input_handler = { let tx = tx.clone(); thread::spawn(move || { let stdin = io::stdin(); for key in stdin.keys().flatten() { tx.send(Event::Input(key)).unwrap(); } }) }; /* Handle kernel logs using 'dmesg' output. */ let kernel_handler = { let tx = tx.clone(); let mut kernel_logs = kernel_logs.clone(); thread::spawn(move || loop { if kernel_logs.update() { tx.send(Event::Kernel(kernel_logs.output.to_string())) .unwrap_or_default(); } thread::sleep(refresh_rate * 10); }) }; /* Create a loop for handling events. */ let tick_handler = { let tx = tx.clone(); thread::spawn(move || loop { tx.send(Event::Tick).unwrap_or_default(); thread::sleep(refresh_rate); }) }; /* Return events. */ Self { tx, rx, input_handler, kernel_handler, tick_handler, } } } #[cfg(test)] mod tests { use super::*; use std::error::Error; #[test] fn test_events() -> Result<(), Box> { let kernel_logs = KernelLogs::default(); let events = Events::new(100, &kernel_logs); let mut i = 0; loop { let tx = events.tx.clone(); thread::spawn(move || { let _ = tx.send(Event::Input(Key::Char( std::char::from_digit(i, 10).unwrap_or('x'), ))); }); i += 1; match events.rx.recv()? { Event::Input(v) => { if v == Key::Char('9') { break; } } Event::Tick => thread::sleep(Duration::from_millis(100)), Event::Kernel(log) => assert!(!log.is_empty()), } } Ok(()) } } kmon-1.6.5/src/kernel/cmd.rs000064400000000000000000000137431046102023000137710ustar 00000000000000use crate::style::Symbol; /* Kernel module related command */ #[derive(Debug)] pub struct Command { pub cmd: String, pub desc: &'static str, pub title: String, pub symbol: Symbol, } impl Command { /** * Create a new command instance. * * @param command * @param description * @param command_title * @return Command */ fn new( cmd: String, desc: &'static str, mut title: String, symbol: Symbol, ) -> Self { /* Parse the command title if '!' is given. */ if title.contains('!') { title = (*title .split('!') .collect::>() .last() .unwrap_or(&"")) .to_string(); } Self { cmd, desc, title, symbol, } } } /* Kernel module management commands */ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ModuleCommand { None, Load, Unload, Reload, Blacklist, Clear, } impl TryFrom for ModuleCommand { type Error = (); fn try_from(s: String) -> Result { match s.as_ref() { "load" => Ok(Self::Load), "unload" => Ok(Self::Unload), "reload" => Ok(Self::Reload), "blacklist" => Ok(Self::Blacklist), "clear" => Ok(Self::Clear), _ => Err(()), } } } impl ModuleCommand { /** * Get Command struct from a enum element. * * @param module_name * @return Command */ pub fn get(self, module_name: &str) -> Command { match self { Self::None => Command::new(String::from(""), "", format!("Module: {module_name}"), Symbol::None), Self::Load => Command::new( if Self::is_module_filename(module_name) { format!("insmod {}", &module_name) } else { format!("modprobe {0} || insmod {0}.ko", &module_name) }, "Add and remove modules from the Linux Kernel\n This command inserts a module to the kernel.", format!("Load: {module_name}"), Symbol::Anchor), Self::Unload => Command::new( format!("modprobe -r {0} || rmmod {0}", &module_name), "modprobe/rmmod: Add and remove modules from the Linux Kernel modprobe -r, --remove or rmmod\n This option causes modprobe to remove rather than insert a module. \ If the modules it depends on are also unused, modprobe will try to \ remove them too. \ For modules loaded with insmod rmmod will be used instead. \ There is usually no reason to remove modules, but some buggy \ modules require it. Your distribution kernel may not have been \ built to support removal of modules at all.", format!("Remove: {module_name}"), Symbol::CircleX), Self::Reload => Command::new( format!("{} && {}", ModuleCommand::Unload.get(module_name).cmd, ModuleCommand::Load.get(module_name).cmd), "modprobe/insmod/rmmod: Add and remove modules from the Linux Kernel\n This command reloads a module, removes and inserts to the kernel.", format!("Reload: {module_name}"), Symbol::FuelPump), Self::Blacklist => Command::new( format!("if ! grep -q {module} /etc/modprobe.d/blacklist.conf; then echo 'blacklist {module}' >> /etc/modprobe.d/blacklist.conf echo 'install {module} /bin/false' >> /etc/modprobe.d/blacklist.conf fi", module = &module_name), "This command blacklists a module and any other module that depends on it.\n Blacklisting is a mechanism to prevent the kernel module from loading. \ This could be useful if, for example, the associated hardware is not needed, \ or if loading that module causes problems. The blacklist command will blacklist a module so that it will not be loaded \ automatically, but the module may be loaded if another non-blacklisted module \ depends on it or if it is loaded manually. However, there is a workaround for \ this behaviour; the install command instructs modprobe to run a custom command \ instead of inserting the module in the kernel as normal, so the module will \ always fail to load.", format!("Blacklist: {module_name}"), Symbol::SquareX), Self::Clear => Command::new( String::from("dmesg --clear"), "dmesg: Print or control the kernel ring buffer option: -C, --clear\n Clear the ring buffer.", String::from("Clear"), Symbol::Cloud), } } /** * Check if module command is set. * * @return bool */ pub fn is_none(self) -> bool { self == Self::None } /** * Check if module name is a filename with suffix 'ko' * * @return bool */ pub fn is_module_filename(module_name: &str) -> bool { match module_name.split('.').collect::>().last() { Some(v) => *v == "ko", None => false, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_module_command() { let module_command = ModuleCommand::None; assert!(module_command == ModuleCommand::None); assert_ne!("", ModuleCommand::None.get("test").title); assert_ne!("", ModuleCommand::Load.get("module").desc); assert_ne!("", ModuleCommand::Unload.get("!command").cmd); assert_ne!("", ModuleCommand::Blacklist.get("~").cmd); assert_eq!( "modprobe test-module || insmod test-module.ko", ModuleCommand::Load.get("test-module").cmd ); assert_eq!( "insmod test-module.ko", ModuleCommand::Load.get("test-module.ko").cmd ); assert_eq!( "modprobe -r test-module || rmmod test-module", ModuleCommand::Unload.get("test-module").cmd ); assert_eq!( "modprobe -r test-module.ko || rmmod test-module.ko", ModuleCommand::Unload.get("test-module.ko").cmd ); assert_eq!( format!( "{} && {}", ModuleCommand::Unload.get("test-module").cmd, ModuleCommand::Load.get("test-module").cmd ), ModuleCommand::Reload.get("test-module").cmd, ); assert_eq!( format!( "{} && {}", ModuleCommand::Unload.get("test-module.ko").cmd, ModuleCommand::Load.get("test-module.ko").cmd ), ModuleCommand::Reload.get("test-module.ko").cmd, ); } } kmon-1.6.5/src/kernel/info.rs000064400000000000000000000034171046102023000141560ustar 00000000000000use crate::util; use std::vec::IntoIter; /* Kernel and system information */ pub struct KernelInfo { pub current_info: Vec, uname_output: IntoIter>, } impl Default for KernelInfo { fn default() -> Self { Self::new() } } impl KernelInfo { /** * Create a new kernel info instance. * * @return KernelInfo */ pub fn new() -> Self { let mut kernel_info = Self { current_info: Vec::new(), uname_output: Vec::new().into_iter(), }; kernel_info.refresh(); kernel_info } /* Refresh the kernel information fields. */ pub fn refresh(&mut self) { self.uname_output = KernelInfo::get_infos(); self.next(); } /** * Select the next 'uname' output as kernel information. */ pub fn next(&mut self) { match self.uname_output.next() { Some(v) => self.current_info = v, None => self.refresh(), } } /** * Execute 'uname' command and return its output along with its description. * * @return Iterator */ fn get_infos() -> IntoIter> { vec![ vec![ String::from("Kernel Release"), util::exec_cmd("uname", &["-srn"]) .unwrap_or_else(|_| String::from("?")), ], vec![ String::from("Kernel Version"), util::exec_cmd("uname", &["-v"]) .unwrap_or_else(|_| String::from("?")), ], vec![ String::from("Kernel Platform"), util::exec_cmd("uname", &["-om"]) .unwrap_or_else(|_| String::from("?")), ], ] .into_iter() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_info() { let mut kernel_info = KernelInfo::default(); for _x in 0..kernel_info.uname_output.len() + 1 { kernel_info.next(); } assert_eq!("Kernel Release", kernel_info.current_info[0]); assert_eq!( util::exec_cmd("uname", &["-srn"]).unwrap(), kernel_info.current_info[1] ); } } kmon-1.6.5/src/kernel/lkm.rs000064400000000000000000000250321046102023000140030ustar 00000000000000use crate::app::ScrollDirection; use crate::kernel::cmd::{Command, ModuleCommand}; use crate::style::{Style, StyledText, Symbol}; use crate::util; use bytesize::ByteSize; use clap::ArgMatches; use ratatui::text::{Line, Span, Text}; use std::error::Error; use std::slice::Iter; /* Type of the sorting of module list */ #[derive(Clone, Copy, Debug)] enum SortType { None, Size, Name, Dependent, } impl SortType { /** * Return iterator for the sort types. * * @return Iter */ #[allow(dead_code)] pub fn iter() -> Iter<'static, SortType> { [ SortType::None, SortType::Size, SortType::Name, SortType::Dependent, ] .iter() } } /* Listing properties of module list */ pub struct ListArgs { sort: SortType, reverse: bool, } impl ListArgs { /** * Create a new list arguments instance. * * @param ArgMatches * @return ListArgs */ pub fn new(args: &ArgMatches) -> Self { let mut sort_type = SortType::None; if let Some(("sort", matches)) = args.subcommand() { if matches.get_flag("size") { sort_type = SortType::Size; } else if matches.get_flag("dependent") { sort_type = SortType::Dependent; } else { sort_type = SortType::Name; } } Self { sort: sort_type, reverse: args.try_get_one::("reverse").ok().flatten() == Some(&true), } } } /* Loadable kernel modules */ pub struct KernelModules<'a> { pub default_list: Vec>, pub list: Vec>, pub current_name: String, pub current_info: StyledText<'a>, pub command: ModuleCommand, pub index: usize, pub info_scroll_offset: usize, pub style: Style, pub args: ListArgs, } impl KernelModules<'_> { /** * Create a new kernel modules instance. * * @param ListArgs * @param Style * @return KernelModules */ pub fn new(args: ListArgs, style: Style) -> Self { let mut kernel_modules = Self { default_list: Vec::new(), list: Vec::new(), current_name: String::new(), current_info: StyledText::default(), command: ModuleCommand::None, index: 0, info_scroll_offset: 0, args, style, }; if let Err(e) = kernel_modules.refresh() { eprintln!("{e}"); } kernel_modules } /* Parse kernel modules from '/proc/modules'. */ pub fn refresh(&mut self) -> Result<(), Box> { let mut module_list: Vec> = Vec::new(); /* Set the command for reading kernel modules and execute it. */ let mut module_read_cmd = String::from("cat /proc/modules"); match self.args.sort { SortType::Size => module_read_cmd += " | sort -n -r -t ' ' -k2", SortType::Name => module_read_cmd += " | sort -t ' ' -k1", SortType::Dependent => module_read_cmd += " | sort -n -r -t ' ' -k3", _ => {} } let modules_content = util::exec_cmd("sh", &["-c", &module_read_cmd])?; /* Parse content for module name, size and related information. */ for line in modules_content.lines() { let columns: Vec<&str> = line.split_whitespace().collect(); let mut module_name = format!(" {}", columns[0]); if columns.len() >= 7 { module_name = format!("{} {}", module_name, columns[6]); } let mut used_modules = format!("{} {}", columns[2], columns[3]); if used_modules.ends_with(',') { used_modules.pop(); } let module_size = ByteSize::b(columns[1].to_string().parse().unwrap_or(0)).to_string(); module_list.push(vec![module_name, module_size, used_modules]); } /* Reverse the kernel modules if the argument is provided. */ if self.args.reverse { module_list.reverse(); } self.default_list = module_list.clone(); self.list = module_list; self.scroll_list(ScrollDirection::Top); Ok(()) } /** * Get the current command using current module name. * * @return Command */ pub fn get_current_command(&self) -> Command { self.command.get(&self.current_name) } /** * Set the current module command and show confirmation message. * * @param module_command * @param command_name */ pub fn set_current_command( &mut self, module_command: ModuleCommand, command_name: String, ) { if !command_name.contains(' ') && !self.current_name.starts_with('!') { if !command_name.is_empty() { self.current_name = command_name; } self.command = module_command; self.current_info.set( Text::from({ let mut spans = vec![ Line::from(Span::styled( "Execute the following command? [y/N]:", self.style.colored, )), Line::from(Span::styled( self.get_current_command().cmd, self.style.default, )), Line::default(), ]; spans.append( &mut Text::styled( self.get_current_command().desc, self.style.colored, ) .lines, ); spans }), self.get_current_command().cmd, ); self.info_scroll_offset = 0; } } /** * Execute the current module command. * * @return command_executed */ pub fn execute_command(&mut self) -> bool { let mut command_executed = false; if !self.command.is_none() { match util::exec_cmd("sh", &["-c", &self.get_current_command().cmd]) { Ok(_) => command_executed = true, Err(e) => { self.current_info.set( Text::from({ let mut spans = vec![ Line::from(Span::styled( "Failed to execute command:", self.style.colored, )), Line::from(Span::styled( format!("'{}'", self.get_current_command().cmd), self.style.default, )), Line::default(), ]; spans.append( &mut Text::styled(e.to_string(), self.style.default) .lines, ); spans }), format!( "Execution Error\n'{}'\n{}", self.get_current_command().cmd, e ), ); self.current_name = format!("!Error{}", self.style.unicode.get(Symbol::NoEntry)); } } self.command = ModuleCommand::None; } command_executed } /** * Cancel the execution of the current command. * * @return cancelled */ pub fn cancel_execution(&mut self) -> bool { if !self.command.is_none() { self.command = ModuleCommand::None; if self.index != 0 { self.index -= 1; self.scroll_list(ScrollDirection::Down); } else { self.index += 1; self.scroll_list(ScrollDirection::Up); }; true } else { false } } /** * Scroll to the position of used module at given index. * * @param mod_index */ pub fn show_used_module(&mut self, mod_index: usize) { if let Some(used_module) = self.list[self.index][2] .split(' ') .collect::>() .get(1) .unwrap_or(&"") .split(',') .collect::>() .get(mod_index) { if let Some(v) = self .list .iter() .position(|module| module[0] == format!(" {used_module}")) { match v { 0 => { self.index = v + 1; self.scroll_list(ScrollDirection::Up); } v if v > 0 => { self.index = v - 1; self.scroll_list(ScrollDirection::Down); } _ => {} } } } } /** * Scroll module list up/down and select module. * * @param direction */ pub fn scroll_list(&mut self, direction: ScrollDirection) { self.info_scroll_offset = 0; if self.list.is_empty() { self.index = 0; } else { /* Scroll module list. */ match direction { ScrollDirection::Up => self.previous_module(), ScrollDirection::Down => self.next_module(), ScrollDirection::Top => self.index = 0, ScrollDirection::Bottom => self.index = self.list.len() - 1, _ => {} } /* Set current module name. */ self.current_name = self.list[self.index][0] .split_whitespace() .next() .unwrap_or("?") .trim() .to_string(); /* Execute 'modinfo' and add style to its output. */ self.current_info.stylize_data( Box::leak( util::exec_cmd("modinfo", &[&self.current_name]) .unwrap_or_else(|_| { String::from("module information not available") }) .replace("signature: ", "signature: \n") .into_boxed_str(), ), ":", self.style.clone(), ); /* Clear the current command. */ if !self.command.is_none() { self.command = ModuleCommand::None; } } } /** * Select the next module. */ pub fn next_module(&mut self) { self.index += 1; if self.index > self.list.len() - 1 { self.index = 0; } } /** * Select the previous module. */ pub fn previous_module(&mut self) { if self.index > 0 { self.index -= 1; } else { self.index = self.list.len() - 1; } } /** * Scroll the module information text up/down. * * @param direction * @param smooth_scroll */ pub fn scroll_mod_info( &mut self, direction: ScrollDirection, smooth_scroll: bool, ) { let scroll_amount = if smooth_scroll { 1 } else { 2 }; match direction { ScrollDirection::Up => { if self.info_scroll_offset > scroll_amount - 1 { self.info_scroll_offset -= scroll_amount; } } ScrollDirection::Down => { if self.current_info.lines() > 0 { self.info_scroll_offset += scroll_amount; self.info_scroll_offset %= self.current_info.lines() * 2; } } _ => {} } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_kernel_modules() { let args = ArgMatches::default(); let mut list_args = ListArgs::new(&args); list_args.sort = SortType::Size; list_args.reverse = true; let mut kernel_modules = KernelModules::new(list_args, Style::new(&args)); for sort_type in SortType::iter().rev().chain(SortType::iter()) { kernel_modules.args.sort = *sort_type; kernel_modules.refresh(); } for direction in ScrollDirection::iter().rev().chain(ScrollDirection::iter()) { kernel_modules.show_used_module(0); kernel_modules.scroll_list(*direction); kernel_modules .scroll_mod_info(*direction, *direction == ScrollDirection::Up); } kernel_modules.scroll_list(ScrollDirection::Down); assert_eq!(0, kernel_modules.index); kernel_modules.scroll_list(ScrollDirection::Up); assert_eq!(kernel_modules.default_list.len() - 1, kernel_modules.index); assert_ne!(0, kernel_modules.default_list.len()); assert_ne!(0, kernel_modules.current_name.len()); assert_ne!(0, kernel_modules.current_info.lines()); kernel_modules .set_current_command(ModuleCommand::Load, String::from("test")); assert_eq!("test", kernel_modules.current_name); assert!(!kernel_modules.execute_command()); kernel_modules.set_current_command(ModuleCommand::Load, String::new()); kernel_modules.scroll_list(ScrollDirection::Top); for command in [ ModuleCommand::Unload, ModuleCommand::Blacklist, ModuleCommand::None, ] { kernel_modules.set_current_command(command, String::new()); assert_eq!(!command.is_none(), kernel_modules.cancel_execution()); } } } kmon-1.6.5/src/kernel/log.rs000064400000000000000000000054661046102023000140120ustar 00000000000000use crate::app::ScrollDirection; use crate::util; use std::fmt::Write as _; /* Kernel activity logs */ #[derive(Clone, Debug, Default)] pub struct KernelLogs { pub output: String, pub selected_output: String, last_line: String, crop_offset: usize, pub index: usize, } impl KernelLogs { /** * Update the output variable value if 'dmesg' logs changed. * * @return logs_updated */ pub fn update(&mut self) -> bool { self.output = util::exec_cmd( "dmesg", &["--kernel", "--human", "--ctime", "--color=never"], ) .unwrap_or_else(|_| String::from("failed to retrieve dmesg output")); let logs_updated = self.output.lines().next_back().unwrap_or_default() != self.last_line; self.last_line = self .output .lines() .next_back() .unwrap_or_default() .to_string(); logs_updated } /* Refresh the kernel logs. */ pub fn refresh(&mut self) { self.last_line = String::new(); self.index = 0; self.crop_offset = 0; self.update(); } /** * Select a part of the output depending on the area properties. * * @param area_height * @param area_sub * @return selected_output */ pub fn select(&mut self, area_height: u16, area_sub: u16) -> &str { self.selected_output = self .output .lines() .map(|line| match line.char_indices().nth(self.crop_offset) { Some((pos, _)) => &line[pos..], None => "", }) .skip( area_height .checked_sub(area_sub) .and_then(|height| { (self.output.lines().count() - self.index) .checked_sub(height as usize) }) .unwrap_or(0), ) .fold(String::new(), |mut s, i| { let _ = writeln!(s, "{i}"); s }); &self.selected_output } /** * Scroll the kernel logs up/down. * * @param direction * @param smooth_scroll */ pub fn scroll(&mut self, direction: ScrollDirection, smooth_scroll: bool) { let scroll_amount = if smooth_scroll { 1 } else { 3 }; match direction { ScrollDirection::Up => { if self.index + scroll_amount <= self.output.lines().count() { self.index += scroll_amount; } } ScrollDirection::Down => { if self.index > scroll_amount - 1 { self.index -= scroll_amount; } else { self.index = 0; } } ScrollDirection::Left => { self.crop_offset = self.crop_offset.saturating_sub(10) } ScrollDirection::Right => { self.crop_offset = self.crop_offset.checked_add(10).unwrap_or(0) } _ => {} } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_kernel_logs() { let mut kernel_logs = KernelLogs::default(); for direction in ScrollDirection::iter().rev().chain(ScrollDirection::iter()) { kernel_logs.scroll(*direction, *direction == ScrollDirection::Top); } assert!(kernel_logs.update()); assert_ne!(0, kernel_logs.output.lines().count()); assert_ne!(0, kernel_logs.select(10, 2).len()); } } kmon-1.6.5/src/kernel/mod.rs000064400000000000000000000014451046102023000140010ustar 00000000000000pub mod cmd; pub mod info; pub mod lkm; pub mod log; use crate::style::Style; use clap::ArgMatches; use info::KernelInfo; use lkm::{KernelModules, ListArgs}; use log::KernelLogs; /* Kernel struct for logs, information and modules */ pub struct Kernel { pub logs: KernelLogs, pub info: KernelInfo, pub modules: KernelModules<'static>, } impl Kernel { /** * Create a new kernel instance. * * @param ArgMatches * @return Kernel */ pub fn new(args: &ArgMatches) -> Self { Self { logs: KernelLogs::default(), info: KernelInfo::default(), modules: KernelModules::new(ListArgs::new(args), Style::new(args)), } } /* Refresh kernel logs, modules and information. */ pub fn refresh(&mut self) { self.logs.refresh(); self.info.refresh(); let _ = self.modules.refresh(); } } kmon-1.6.5/src/lib.rs000064400000000000000000000430221046102023000125050ustar 00000000000000#![allow(clippy::tabs_in_doc_comments)] pub mod app; pub mod event; pub mod kernel; pub mod widgets; #[macro_use] pub mod util; pub mod args; pub mod style; use crate::app::{App, Block, InputMode, ScrollDirection}; use crate::kernel::cmd::ModuleCommand; use crate::kernel::Kernel; use enum_iterator::Sequence; use event::{Event, Events}; use ratatui::backend::Backend; use ratatui::layout::{Constraint, Direction, Layout}; use ratatui::Terminal; use std::error::Error; use termion::event::Key; use unicode_width::UnicodeWidthStr; /** * Configure the terminal and draw its widgets. * * @param Terminal * @param Kernel * @param Events * @return Result */ pub fn start_tui( mut terminal: Terminal, mut kernel: Kernel, events: &Events, ) -> Result<(), Box> where B: Backend, { /* Configure the application. */ let mut app = App::new(Block::ModuleTable, kernel.modules.style.clone()); /* Draw terminal and render the widgets. */ loop { terminal.draw(|frame| { let chunks = Layout::default() .direction(Direction::Vertical) .constraints( [ Constraint::Percentage(100 - app.block_size.activities), Constraint::Percentage(app.block_size.activities), ] .as_ref(), ) .split(frame.size()); { let chunks = Layout::default() .direction(Direction::Horizontal) .constraints( [ Constraint::Percentage(100 - app.block_size.info), Constraint::Percentage(app.block_size.info), ] .as_ref(), ) .split(chunks[0]); { let chunks = Layout::default() .direction(Direction::Vertical) .constraints( [Constraint::Length(3), Constraint::Percentage(100)] .as_ref(), ) .split(chunks[0]); { let chunks = Layout::default() .direction(Direction::Horizontal) .constraints( [ Constraint::Percentage(app.block_size.input), Constraint::Percentage( 100 - app.block_size.input, ), ] .as_ref(), ) .split(chunks[0]); app.draw_user_input(frame, chunks[0], &events.tx); app.draw_kernel_info( frame, chunks[1], &kernel.info.current_info, ); } if app.block_size.info != 100 { app.draw_dynamic_block(frame, chunks[1], &mut kernel); } else { app.block_index += 1; } } app.draw_dynamic_block(frame, chunks[1], &mut kernel); } app.draw_dynamic_block(frame, chunks[1], &mut kernel); if !app.input_mode.is_none() { frame.set_cursor(1 + app.input_query.width() as u16, 1); } })?; /* Handle terminal events. */ match events.rx.recv()? { /* Key input events. */ Event::Input(input) => { let mut hide_options = true; if app.input_mode.is_none() { /* Default input mode. */ match input { /* Quit. */ Key::Char('q') | Key::Char('Q') | Key::Ctrl('c') | Key::Ctrl('d') | Key::Esc => { if app.show_options { app.show_options = false; } else { break; } } /* Refresh. */ Key::Char('r') | Key::Char('R') | Key::F(5) => { app.refresh(); kernel.refresh(); } /* Show help message. */ Key::Char('?') | Key::F(1) => { app.show_help_message(&mut kernel.modules); } Key::Char('m') | Key::Char('o') => { app.show_options = true; hide_options = false; } /* Scroll the selected block up. */ Key::Up | Key::Char('k') | Key::Char('K') | Key::Alt('k') | Key::Alt('K') => { if app.show_options { app.options.previous(); continue; } else { app.options.state.select(Some(0)); } match app.selected_block { Block::ModuleTable => { kernel.modules.scroll_list(ScrollDirection::Up) } Block::ModuleInfo => kernel.modules.scroll_mod_info( ScrollDirection::Up, input == Key::Alt('k') || input == Key::Alt('K'), ), Block::Activities => { kernel.logs.scroll( ScrollDirection::Up, input == Key::Alt('k') || input == Key::Alt('K'), ); } _ => {} } } /* Scroll the selected block down. */ Key::Down | Key::Char('j') | Key::Char('J') | Key::Alt('j') | Key::Alt('J') => { if app.show_options { app.options.next(); continue; } else { app.options.state.select(Some(0)); } match app.selected_block { Block::ModuleTable => { kernel.modules.scroll_list(ScrollDirection::Down) } Block::ModuleInfo => kernel.modules.scroll_mod_info( ScrollDirection::Down, input == Key::Alt('j') || input == Key::Alt('J'), ), Block::Activities => { kernel.logs.scroll( ScrollDirection::Down, input == Key::Alt('j') || input == Key::Alt('J'), ); } _ => {} } } /* Select the next terminal block. */ Key::Left | Key::Char('h') | Key::Char('H') => { app.selected_block = match app.selected_block.previous() { Some(v) => v, None => Block::last().unwrap(), } } /* Select the previous terminal block. */ Key::Right | Key::Char('l') | Key::Char('L') => { app.selected_block = match app.selected_block.next() { Some(v) => v, None => Block::first().unwrap(), } } /* Expand the selected block. */ Key::Alt('e') => { let block_size = app.block_size(); if *block_size < 95 { *block_size += 5; } else { *block_size = 100; } } /* Shrink the selected block. */ Key::Alt('s') => { let block_size = app.block_size(); *block_size = (*block_size).checked_sub(5).unwrap_or_default() } /* Change the block position. */ Key::Ctrl('x') => { if app.block_index == 2 { app.block_index = 0; } else { app.block_index += 1; } } /* Scroll to the top of the module list. */ Key::Ctrl('t') | Key::Home => { app.options.state.select(Some(0)); app.selected_block = Block::ModuleTable; kernel.modules.scroll_list(ScrollDirection::Top) } /* Scroll to the bottom of the module list. */ Key::Ctrl('b') | Key::End => { app.options.state.select(Some(0)); app.selected_block = Block::ModuleTable; kernel.modules.scroll_list(ScrollDirection::Bottom) } /* Scroll kernel activities up. */ Key::PageUp => { app.selected_block = Block::Activities; kernel.logs.scroll(ScrollDirection::Up, false); } /* Scroll kernel activities down. */ Key::PageDown => { app.selected_block = Block::Activities; kernel.logs.scroll(ScrollDirection::Down, false); } /* Scroll kernel activities left. */ Key::Alt('h') | Key::Alt('H') => { app.selected_block = Block::Activities; kernel.logs.scroll(ScrollDirection::Left, false); } /* Scroll kernel activities right. */ Key::Alt('l') | Key::Alt('L') => { app.selected_block = Block::Activities; kernel.logs.scroll(ScrollDirection::Right, false); } /* Scroll module information up. */ Key::Char('<') | Key::Alt(' ') => { app.selected_block = Block::ModuleInfo; kernel .modules .scroll_mod_info(ScrollDirection::Up, false) } /* Scroll module information down. */ Key::Char('>') | Key::Char(' ') => { app.selected_block = Block::ModuleInfo; kernel .modules .scroll_mod_info(ScrollDirection::Down, false) } /* Show the next kernel information. */ Key::Char('\\') | Key::Char('\t') | Key::BackTab => { kernel.info.next(); } /* Display the dependent modules. */ Key::Char('d') | Key::Alt('d') => { app.show_dependent_modules(&mut kernel.modules); } /* Clear the kernel ring buffer. */ Key::Ctrl('l') | Key::Ctrl('u') | Key::Alt('c') | Key::Alt('C') => { kernel.modules.set_current_command( ModuleCommand::Clear, String::new(), ); } /* Unload kernel module. */ Key::Char('u') | Key::Char('U') | Key::Char('-') | Key::Backspace | Key::Ctrl('h') => { kernel.modules.set_current_command( ModuleCommand::Unload, String::new(), ); } /* Blacklist kernel module. */ Key::Char('x') | Key::Char('X') | Key::Char('b') | Key::Char('B') | Key::Delete => { kernel.modules.set_current_command( ModuleCommand::Blacklist, String::new(), ); } /* Reload kernel module. */ Key::Ctrl('r') | Key::Ctrl('R') | Key::Alt('r') | Key::Alt('R') => { kernel.modules.set_current_command( ModuleCommand::Reload, String::new(), ); } /* Execute the current command. */ Key::Char('y') | Key::Char('Y') => { if kernel.modules.execute_command() { events .tx .send(Event::Input(Key::Char('r'))) .unwrap(); } } /* Cancel the execution of current command. */ Key::Char('n') | Key::Char('N') => { if kernel.modules.cancel_execution() { app.selected_block = Block::ModuleTable; } } /* Copy the data in selected block to clipboard. */ Key::Char('c') | Key::Char('C') => { app.set_clipboard_contents(match app.selected_block { Block::ModuleTable => &kernel.modules.current_name, Block::ModuleInfo => { &kernel.modules.current_info.raw_text } Block::Activities => { kernel.logs.selected_output.trim() } _ => "", }); } /* Paste the clipboard contents and switch to search mode. */ Key::Char('v') | Key::Ctrl('V') | Key::Ctrl('v') => { let clipboard_contents = app.get_clipboard_contents(); app.input_query += &clipboard_contents; events.tx.send(Event::Input(Key::Char('\n'))).unwrap(); kernel.modules.index = 0; } /* User input mode. */ Key::Char('\n') | Key::Char('s') | Key::Char('S') | Key::Char('i') | Key::Char('I') | Key::Char('+') | Key::Char('/') | Key::Insert => { if input == Key::Char('\n') && app.show_options { if let Ok(command) = ModuleCommand::try_from( app.options .selected() .map(|(v, _)| v.to_string()) .unwrap_or_default(), ) { if command == ModuleCommand::Load { events .tx .send(Event::Input(Key::Char('+'))) .unwrap(); } else { kernel.modules.set_current_command( command, String::new(), ); } } else { match app .options .selected() .map(|(v, _)| v.as_ref()) { Some("dependent") => { app.show_dependent_modules( &mut kernel.modules, ); } Some("copy") => app.set_clipboard_contents( &kernel.modules.current_name, ), _ => {} } } } else { app.selected_block = Block::UserInput; app.input_mode = match input { Key::Char('+') | Key::Char('i') | Key::Char('I') | Key::Insert => InputMode::Load, _ => InputMode::Search, }; if input != Key::Char('\n') { app.input_query = String::new(); } } } /* Other character input. */ Key::Char(v) => { /* Check if input is a number except zero. */ let index = v.to_digit(10).unwrap_or(0); /* Show the used module info at given index. */ if index != 0 && !kernel.modules.list.is_empty() { app.selected_block = Block::ModuleTable; kernel.modules.show_used_module(index as usize - 1); } } _ => {} } } else { /* User input mode. */ match input { /* Quit with ctrl-d. */ Key::Ctrl('d') => { break; } /* Switch to the previous input mode. */ Key::Up => { app.input_mode = match app.input_mode.previous() { Some(v) => v, None => InputMode::last().unwrap(), }; if app.input_mode.is_none() { app.input_mode = InputMode::last().unwrap(); } app.input_query = String::new(); } /* Switch to the next input mode. */ Key::Down => { app.input_mode = match app.input_mode.next() { Some(v) => v, None => InputMode::first() .and_then(|v| v.next()) .unwrap(), }; app.input_query = String::new(); } /* Copy input query to the clipboard. */ Key::Ctrl('c') => { let query = app.input_query.clone(); app.set_clipboard_contents(&query); } /* Paste the clipboard contents. */ Key::Ctrl('v') => { let clipboard_contents = app.get_clipboard_contents(); app.input_query += &clipboard_contents; } /* Exit user input mode. */ Key::Char('\n') | Key::Char('\t') | Key::Char('?') | Key::F(1) | Key::Right | Key::Left => { /* Select the next eligible block for action. */ app.selected_block = match input { Key::Left => match app.selected_block.previous() { Some(v) => v, None => Block::last().unwrap(), }, Key::Char('\n') => match app.input_mode { InputMode::Load if !app.input_query.is_empty() => { Block::ModuleInfo } _ => Block::ModuleTable, }, Key::Char('?') | Key::F(1) => { app.show_help_message(&mut kernel.modules); app.input_mode = InputMode::None; Block::ModuleTable } _ => Block::ModuleTable, }; /* Show the first modules information if the search mode is set. */ if app.input_mode == InputMode::Search && kernel.modules.index == 0 { kernel.modules.scroll_list(ScrollDirection::Top); /* Load kernel module. */ } else if app.input_mode == InputMode::Load && !app.input_query.is_empty() { kernel.modules.set_current_command( ModuleCommand::Load, app.input_query, ); app.input_query = String::new(); } /* Set the input mode flag. */ app.input_mode = InputMode::None; } /* Append character to input query. */ Key::Char(c) => { app.input_query.push(c); kernel.modules.index = 0; } /* Delete the last character from input query. */ Key::Backspace | Key::Ctrl('h') => { app.input_query.pop(); kernel.modules.index = 0; } /* Clear the input query. */ Key::Delete | Key::Ctrl('l') => { app.input_query = String::new(); kernel.modules.index = 0; } /* Clear the input query and exit user input mode. */ Key::Esc => { events.tx.send(Event::Input(Key::Delete)).unwrap(); events.tx.send(Event::Input(Key::Char('\n'))).unwrap(); } _ => {} } } if hide_options { app.show_options = false; } } /* Kernel events. */ Event::Kernel(logs) => { kernel.logs.output = logs; } _ => {} } } Ok(()) } #[cfg(test)] mod tests { use super::*; use clap::ArgMatches; use ratatui::backend::TestBackend; use std::sync::mpsc::Sender; use std::thread; use std::time::Duration; #[test] fn test_tui() -> Result<(), Box> { let args = ArgMatches::default(); let kernel = Kernel::new(&args); let events = Events::new(100, &kernel.logs); let tx = events.tx.clone(); thread::spawn(move || { /* Test the general keys. */ for key in [ Key::Char('?'), Key::Ctrl('t'), Key::Ctrl('b'), Key::Alt('e'), Key::Alt('s'), Key::Ctrl('x'), Key::Ctrl('x'), Key::Ctrl('x'), Key::Char('x'), Key::Char('n'), Key::Char('d'), Key::Ctrl('l'), Key::Char('u'), Key::Ctrl('r'), Key::Char('y'), Key::PageUp, Key::PageDown, Key::Alt('l'), Key::Alt('h'), Key::Char('<'), Key::Char('>'), Key::Char('\t'), Key::Char('m'), Key::Down, Key::Char('\n'), ] { send_key(&tx, key); } send_key(&tx, Key::Char('r')); /* Test the switch keys. */ for arrow_key in [Key::Right, Key::Left] { for selected_key in [arrow_key; Block::CARDINALITY] { send_key(&tx, selected_key); for key in [ Key::Up, Key::Down, Key::Down, Key::Up, Key::Char('c'), Key::Char('~'), Key::Char('1'), ] { send_key(&tx, key); } } } /* Test the input mode keys. */ for key in [ Key::Char('v'), Key::Delete, Key::Char('~'), Key::Backspace, Key::Ctrl('c'), Key::Ctrl('v'), Key::Char('a'), Key::Char('\n'), Key::Char('\n'), Key::Char('?'), Key::Char('\n'), Key::Esc, Key::Char('i'), Key::Char('x'), Key::Char('\n'), ] { send_key(&tx, key); } /* Exit. */ send_key(&tx, Key::Esc) }); start_tui(Terminal::new(TestBackend::new(20, 10))?, kernel, &events) } /** * Try to send a key event until Sender succeeds. * * @param Sender * @param Key */ fn send_key(tx: &Sender>, key: Key) { let mut x = true; while x { x = tx.send(Event::Input(key)).is_err(); thread::sleep(Duration::from_millis(10)); } } } kmon-1.6.5/src/main.rs000064400000000000000000000015611046102023000126650ustar 00000000000000use kmon::args; use kmon::event::Events; use kmon::kernel::Kernel; use kmon::util; use ratatui::backend::TermionBackend; use ratatui::Terminal; use std::error::Error; use std::io::stdout; use termion::input::MouseTerminal; use termion::raw::IntoRawMode; use termion::screen::IntoAlternateScreen; /** * Entry point. * * @return Result */ fn main() -> Result<(), Box> { let args = args::get_args().get_matches(); let kernel = Kernel::new(&args); let events = Events::new( args.get_one::("rate") .unwrap() .parse::() .unwrap_or(250), &kernel.logs, ); if !cfg!(test) { util::setup_panic_hook()?; let stdout = stdout().into_raw_mode()?.into_alternate_screen()?; let stdout = MouseTerminal::from(stdout); let backend = TermionBackend::new(stdout); kmon::start_tui(Terminal::new(backend)?, kernel, &events) } else { Ok(()) } } kmon-1.6.5/src/style.rs000064400000000000000000000135441046102023000131050ustar 00000000000000use clap::ArgMatches; use colorsys::Rgb; use ratatui::style::{Color, Modifier, Style as TuiStyle}; use ratatui::text::{Line, Span, Text}; use std::collections::HashMap; /* Unicode symbol */ #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub enum Symbol { None, Blank, Gear, Cloud, Anchor, Helmet, CircleX, SquareX, NoEntry, FuelPump, Magnifier, HighVoltage, LeftBracket, RightBracket, HistoricSite, } /* Supported Unicode symbols */ #[derive(Clone, Debug)] pub struct Unicode<'a> { symbols: HashMap, replace: bool, } impl Unicode<'_> { /** * Create a new Unicode instance. * * @param replace * @return Unicode */ pub fn new(replace: bool) -> Self { Self { symbols: map! { Symbol::None => &["", ""], Symbol::Blank => &["\u{2800} ", "\u{2800} "], Symbol::Gear => &[" \u{2699} ", ""], Symbol::Cloud => &[" \u{26C5} ", ""], Symbol::Anchor => &[" \u{2693}", ""], Symbol::Helmet => &[" \u{26D1} ", ""], Symbol::CircleX => &[" \u{1F167} ", ""], Symbol::SquareX => &[" \u{1F187} ", ""], Symbol::NoEntry => &[" \u{26D4}", ""], Symbol::FuelPump => &[" \u{26FD}", ""], Symbol::Magnifier => &[" \u{1F50D}", ""], Symbol::HighVoltage => &[" \u{26A1}", ""], Symbol::LeftBracket => &["\u{2997}", "("], Symbol::RightBracket => &["\u{2998}", ")"], Symbol::HistoricSite => &[" \u{26EC} ", ""] }, replace, } } /** * Get string from a Unicode symbol. * * @param Symbol * @return str */ pub fn get(&self, symbol: Symbol) -> &str { self.symbols[&symbol][self.replace as usize] } } /* Style properties */ #[derive(Clone, Debug)] pub struct Style { pub default: TuiStyle, pub bold: TuiStyle, pub colored: TuiStyle, pub unicode: Unicode<'static>, } impl Style { /** * Create a new style instance from given arguments. * * @param args * @return Style */ pub fn new(args: &ArgMatches) -> Self { let mut default = TuiStyle::reset(); if let Ok(true) = args.try_contains_id("accent-color") { default = default.fg(Self::get_color(args, "accent-color", Color::White)); } Self { default, bold: TuiStyle::reset().add_modifier(Modifier::BOLD), colored: TuiStyle::reset().fg(Self::get_color( args, "color", Color::DarkGray, )), unicode: Unicode::new( args.try_get_one::("unicode").ok().flatten() == Some(&false), ), } } /** * Parse a color value from arguments. * * @param args * @param arg_name * @param default_color * @return Color */ fn get_color(args: &ArgMatches, arg_name: &str, default_color: Color) -> Color { let colors = map![ "black" => Color::Black, "red" => Color::Red, "green" => Color::Green, "yellow" => Color::Yellow, "blue" => Color::Blue, "magenta" => Color::Magenta, "cyan" => Color::Cyan, "gray" => Color::Gray, "darkgray" => Color::DarkGray, "lightred" => Color::LightRed, "lightgreen" => Color::LightGreen, "lightyellow" => Color::LightYellow, "lightblue" => Color::LightBlue, "lightmagenta" => Color::LightMagenta, "lightcyan" => Color::LightCyan, "white" => Color::White ]; match args.try_get_one::(arg_name) { Ok(Some(v)) => *colors.get::(&v.to_lowercase()).unwrap_or({ if let Ok(rgb) = Rgb::from_hex_str(&format!("#{v}")) { Box::leak(Box::new(Color::Rgb( rgb.red() as u8, rgb.green() as u8, rgb.blue() as u8, ))) } else { &default_color } }), _ => default_color, } } } /* Styled text that has raw and style parts */ #[derive(Debug, Default)] pub struct StyledText<'a> { pub raw_text: String, pub styled_text: Text<'a>, } impl<'a> StyledText<'a> { /** * Get a vector of Text widget from styled text. * * @return vector */ pub fn get(&'a self) -> Text<'a> { if self.styled_text.lines.is_empty() { Text::raw(&self.raw_text) } else { self.styled_text.clone() } } /** * Set a styled text. * * @param text * @param placeholder */ pub fn set(&mut self, text: Text<'static>, placeholder: String) { self.styled_text = text; self.raw_text = placeholder; } /** * Add style to given text depending on a delimiter. * * @param text * @param delimiter * @param style * @return vector */ pub fn stylize_data( &mut self, text: &'a str, delimiter: &str, style: Style, ) -> Text<'a> { self.styled_text = Text::default(); self.raw_text = text.to_string(); for line in text.lines() { let data = line.split(delimiter).collect::>(); if data.len() > 1 && data[0].trim().len() > 2 { self.styled_text.lines.push(Line::from(vec![ Span::styled(format!("{}{}", data[0], delimiter), style.colored), Span::styled(data[1..data.len()].join(delimiter), style.default), ])); } else { self.styled_text .lines .push(Line::from(Span::styled(line, style.default))) } } self.styled_text.clone() } /** * Return the line count of styled text. * * @return usize */ pub fn lines(&self) -> usize { if self.styled_text.lines.is_empty() { self.raw_text.lines().count() } else { self.styled_text.lines.len() } } } #[cfg(test)] mod tests { use super::*; use clap::ArgMatches; #[test] fn test_style() { let args = ArgMatches::default(); let style = Style::new(&args); let mut styled_text = StyledText::default(); styled_text.set( Text::styled("styled\ntext", style.colored), String::from("test"), ); assert_eq!( Text::styled("styled\ntext", style.colored), styled_text.get() ); assert_eq!(2, styled_text.lines()); assert_eq!("test", styled_text.raw_text); } #[test] fn test_unicode() { let mut unicode = Unicode::new(true); for symbol in unicode.symbols.clone() { if symbol.0 != Symbol::Blank { assert!(symbol.1[1].len() < 2) } } unicode.replace = false; for symbol in unicode.symbols { if symbol.0 != Symbol::None { assert_ne!("", symbol.1[0]); } } } } kmon-1.6.5/src/util.rs000064400000000000000000000060601046102023000127150ustar 00000000000000use std::error::Error; use std::io::{self, Write}; use std::panic; use std::process::Command; use termion::raw::IntoRawMode; /* Macro for concise initialization of hashmap */ macro_rules! map { ($( $key: expr => $val: expr ),*) => {{ let mut map = ::std::collections::HashMap::new(); $( map.insert($key, $val); )* map }} } /* Array of the key bindings */ pub const KEY_BINDINGS: &[(&str, &str)] = &[ ("'?', f1", "help"), ("right/left, h/l", "switch between blocks"), ("up/down, k/j, alt-k/j", "scroll up/down [selected block]"), ("pgup/pgdown", "scroll up/down [kernel activities]"), ("", "scroll up/down [module information]"), ("alt-h/l", "scroll right/left [kernel activities]"), ("ctrl-t/b, home/end", "scroll to top/bottom [module list]"), ("alt-e/s", "expand/shrink the selected block"), ("ctrl-x", "change the block position"), ("ctrl-l/u, alt-c", "clear the kernel ring buffer"), ("d, alt-d", "show the dependent modules"), ("1..9", "jump to the dependent module"), ("\\, tab, backtab", "show the next kernel information"), ("/, s, enter", "search a kernel module"), ("+, i, insert", "load a kernel module"), ("-, u, backspace", "unload the kernel module"), ("x, b, delete", "blacklist the kernel module"), ("ctrl-r, alt-r", "reload the kernel module"), ("m, o", "show the options menu"), ("y/n", "execute/cancel the command"), ("c/v", "copy/paste"), ("r, f5", "refresh"), ("q, ctrl-c/d, esc", "quit"), ]; /** * Execute a operating system command and return its output. * * @param cmd * @param cmd_args * @return Result */ pub fn exec_cmd(cmd: &str, cmd_args: &[&str]) -> Result { match Command::new(cmd).args(cmd_args).output() { Ok(output) => { if output.status.success() { Ok(String::from_utf8(output.stdout) .expect("not UTF-8") .trim_end() .to_string()) } else { Err(String::from_utf8(output.stderr) .expect("not UTF-8") .trim_end() .to_string()) } } Err(e) => Err(e.to_string()), } } /** * Sets up the panic hook for the terminal. * * See * * @return Result */ pub fn setup_panic_hook() -> Result<(), Box> { let raw_output = io::stdout().into_raw_mode()?; raw_output.suspend_raw_mode()?; let panic_hook = panic::take_hook(); panic::set_hook(Box::new(move |panic| { let panic_cleanup = || -> Result<(), Box> { let mut output = io::stdout(); write!( output, "{}{}{}", termion::clear::All, termion::screen::ToMainScreen, termion::cursor::Show )?; raw_output.suspend_raw_mode()?; output.flush()?; Ok(()) }; panic_cleanup().expect("failed to clean up for panic"); panic_hook(panic); })); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_exec_cmd() { assert_eq!("test", exec_cmd("printf", &["test"]).unwrap()); assert_eq!( "true", exec_cmd("sh", &["-c", "test 10 -eq 10 && echo 'true'"]).unwrap() ); assert_eq!( "err", exec_cmd("cat", &["-x"]).unwrap_or(String::from("err")) ); } } kmon-1.6.5/src/widgets.rs000064400000000000000000000030251046102023000134040ustar 00000000000000use ratatui::widgets::ListState; /// List widget with TUI controlled states. #[derive(Debug)] pub struct StatefulList { /// List items (states). pub items: Vec, /// State that can be modified by TUI. pub state: ListState, } impl StatefulList { /// Constructs a new instance of `StatefulList`. pub fn new(items: Vec, mut state: ListState) -> StatefulList { state.select(Some(0)); Self { items, state } } /// Construct a new `StatefulList` with given items. pub fn with_items(items: Vec) -> StatefulList { Self::new(items, ListState::default()) } /// Returns the selected item. pub fn selected(&self) -> Option<&T> { self.items.get(self.state.selected()?) } /// Selects the next item. pub fn next(&mut self) { let i = match self.state.selected() { Some(i) => { if i >= self.items.len() - 1 { 0 } else { i + 1 } } None => 0, }; self.state.select(Some(i)); } /// Selects the previous item. pub fn previous(&mut self) { let i = match self.state.selected() { Some(i) => { if i == 0 { self.items.len() - 1 } else { i - 1 } } None => 0, }; self.state.select(Some(i)); } } #[cfg(test)] mod tests { use super::*; #[test] fn test_stateful_list() { let mut list = StatefulList::with_items(vec!["data1", "data2", "data3"]); list.state.select(Some(1)); assert_eq!(Some(&"data2"), list.selected()); list.next(); assert_eq!(Some(2), list.state.selected()); list.previous(); assert_eq!(Some(1), list.state.selected()); } }