├── .gitignore ├── .travis.yml ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── rustfmt.toml └── src ├── main.rs ├── model.rs ├── providers ├── cpu.rs ├── fan.rs ├── memory.rs ├── mod.rs ├── network.rs └── temperature.rs ├── stream.rs ├── terminal.rs ├── theme.rs └── view.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | rust: 4 | - 1.34.0 # Oldest supported version 5 | - stable 6 | - beta 7 | - nightly 8 | 9 | matrix: 10 | allow_failures: 11 | - rust: nightly 12 | fast_finish: true 13 | 14 | before_install: 15 | - sudo apt-get install -y libsensors4-dev 16 | 17 | before_script: 18 | - if [ "$TRAVIS_RUST_VERSION" = "stable" ]; then rustup component add clippy; fi 19 | - if [ "$TRAVIS_RUST_VERSION" = "stable" ]; then rustup component add rustfmt; fi 20 | 21 | script: 22 | - cargo build --verbose 23 | - cargo test --verbose 24 | - if [ "$TRAVIS_RUST_VERSION" = "stable" ]; then cargo clippy --all-targets --all-features -- -D warnings; fi 25 | - if [ "$TRAVIS_RUST_VERSION" = "stable" ]; then cargo fmt --all -- --check; fi 26 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | [[package]] 4 | name = "aho-corasick" 5 | version = "0.7.6" 6 | source = "registry+https://github.com/rust-lang/crates.io-index" 7 | dependencies = [ 8 | "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 9 | ] 10 | 11 | [[package]] 12 | name = "ansi_term" 13 | version = "0.11.0" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | dependencies = [ 16 | "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 17 | ] 18 | 19 | [[package]] 20 | name = "arc-swap" 21 | version = "0.4.4" 22 | source = "registry+https://github.com/rust-lang/crates.io-index" 23 | 24 | [[package]] 25 | name = "atty" 26 | version = "0.2.14" 27 | source = "registry+https://github.com/rust-lang/crates.io-index" 28 | dependencies = [ 29 | "hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", 30 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 31 | "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 32 | ] 33 | 34 | [[package]] 35 | name = "autocfg" 36 | version = "0.1.7" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | 39 | [[package]] 40 | name = "bitflags" 41 | version = "1.2.1" 42 | source = "registry+https://github.com/rust-lang/crates.io-index" 43 | 44 | [[package]] 45 | name = "bytesize" 46 | version = "1.0.0" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | 49 | [[package]] 50 | name = "cfg-if" 51 | version = "0.1.10" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | 54 | [[package]] 55 | name = "chrono" 56 | version = "0.4.10" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | dependencies = [ 59 | "num-integer 0.1.41 (registry+https://github.com/rust-lang/crates.io-index)", 60 | "num-traits 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 61 | "time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", 62 | ] 63 | 64 | [[package]] 65 | name = "clap" 66 | version = "2.33.0" 67 | source = "registry+https://github.com/rust-lang/crates.io-index" 68 | dependencies = [ 69 | "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", 70 | "atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)", 71 | "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 72 | "strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", 73 | "textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", 74 | "unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 75 | "vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", 76 | ] 77 | 78 | [[package]] 79 | name = "crossbeam-channel" 80 | version = "0.4.0" 81 | source = "registry+https://github.com/rust-lang/crates.io-index" 82 | dependencies = [ 83 | "crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", 84 | ] 85 | 86 | [[package]] 87 | name = "crossbeam-utils" 88 | version = "0.7.0" 89 | source = "registry+https://github.com/rust-lang/crates.io-index" 90 | dependencies = [ 91 | "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 92 | "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", 93 | "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 94 | ] 95 | 96 | [[package]] 97 | name = "hegemon" 98 | version = "0.1.0" 99 | dependencies = [ 100 | "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", 101 | "crossbeam-channel 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 102 | "regex 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", 103 | "sensors 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 104 | "signal-hook 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", 105 | "systemstat 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", 106 | "termion 1.5.4 (registry+https://github.com/rust-lang/crates.io-index)", 107 | ] 108 | 109 | [[package]] 110 | name = "hermit-abi" 111 | version = "0.1.6" 112 | source = "registry+https://github.com/rust-lang/crates.io-index" 113 | dependencies = [ 114 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 115 | ] 116 | 117 | [[package]] 118 | name = "lazy_static" 119 | version = "1.4.0" 120 | source = "registry+https://github.com/rust-lang/crates.io-index" 121 | 122 | [[package]] 123 | name = "libc" 124 | version = "0.2.66" 125 | source = "registry+https://github.com/rust-lang/crates.io-index" 126 | 127 | [[package]] 128 | name = "libsensors-sys" 129 | version = "0.2.0" 130 | source = "registry+https://github.com/rust-lang/crates.io-index" 131 | 132 | [[package]] 133 | name = "memchr" 134 | version = "1.0.2" 135 | source = "registry+https://github.com/rust-lang/crates.io-index" 136 | dependencies = [ 137 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 138 | ] 139 | 140 | [[package]] 141 | name = "memchr" 142 | version = "2.2.1" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | 145 | [[package]] 146 | name = "nom" 147 | version = "3.2.1" 148 | source = "registry+https://github.com/rust-lang/crates.io-index" 149 | dependencies = [ 150 | "memchr 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", 151 | ] 152 | 153 | [[package]] 154 | name = "num-integer" 155 | version = "0.1.41" 156 | source = "registry+https://github.com/rust-lang/crates.io-index" 157 | dependencies = [ 158 | "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 159 | "num-traits 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)", 160 | ] 161 | 162 | [[package]] 163 | name = "num-traits" 164 | version = "0.2.10" 165 | source = "registry+https://github.com/rust-lang/crates.io-index" 166 | dependencies = [ 167 | "autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 168 | ] 169 | 170 | [[package]] 171 | name = "numtoa" 172 | version = "0.1.0" 173 | source = "registry+https://github.com/rust-lang/crates.io-index" 174 | 175 | [[package]] 176 | name = "redox_syscall" 177 | version = "0.1.56" 178 | source = "registry+https://github.com/rust-lang/crates.io-index" 179 | 180 | [[package]] 181 | name = "redox_termios" 182 | version = "0.1.1" 183 | source = "registry+https://github.com/rust-lang/crates.io-index" 184 | dependencies = [ 185 | "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", 186 | ] 187 | 188 | [[package]] 189 | name = "regex" 190 | version = "1.3.1" 191 | source = "registry+https://github.com/rust-lang/crates.io-index" 192 | dependencies = [ 193 | "aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)", 194 | "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 195 | "regex-syntax 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", 196 | "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", 197 | ] 198 | 199 | [[package]] 200 | name = "regex-syntax" 201 | version = "0.6.12" 202 | source = "registry+https://github.com/rust-lang/crates.io-index" 203 | 204 | [[package]] 205 | name = "sensors" 206 | version = "0.2.1" 207 | source = "registry+https://github.com/rust-lang/crates.io-index" 208 | dependencies = [ 209 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 210 | "libsensors-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", 211 | ] 212 | 213 | [[package]] 214 | name = "signal-hook" 215 | version = "0.1.12" 216 | source = "registry+https://github.com/rust-lang/crates.io-index" 217 | dependencies = [ 218 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 219 | "signal-hook-registry 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", 220 | ] 221 | 222 | [[package]] 223 | name = "signal-hook-registry" 224 | version = "1.2.0" 225 | source = "registry+https://github.com/rust-lang/crates.io-index" 226 | dependencies = [ 227 | "arc-swap 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)", 228 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 229 | ] 230 | 231 | [[package]] 232 | name = "strsim" 233 | version = "0.8.0" 234 | source = "registry+https://github.com/rust-lang/crates.io-index" 235 | 236 | [[package]] 237 | name = "systemstat" 238 | version = "0.1.5" 239 | source = "registry+https://github.com/rust-lang/crates.io-index" 240 | dependencies = [ 241 | "bytesize 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", 242 | "chrono 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", 243 | "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 244 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 245 | "nom 3.2.1 (registry+https://github.com/rust-lang/crates.io-index)", 246 | "time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)", 247 | "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 248 | ] 249 | 250 | [[package]] 251 | name = "termion" 252 | version = "1.5.4" 253 | source = "registry+https://github.com/rust-lang/crates.io-index" 254 | dependencies = [ 255 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 256 | "numtoa 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", 257 | "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", 258 | "redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", 259 | ] 260 | 261 | [[package]] 262 | name = "textwrap" 263 | version = "0.11.0" 264 | source = "registry+https://github.com/rust-lang/crates.io-index" 265 | dependencies = [ 266 | "unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", 267 | ] 268 | 269 | [[package]] 270 | name = "thread_local" 271 | version = "0.3.6" 272 | source = "registry+https://github.com/rust-lang/crates.io-index" 273 | dependencies = [ 274 | "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 275 | ] 276 | 277 | [[package]] 278 | name = "time" 279 | version = "0.1.42" 280 | source = "registry+https://github.com/rust-lang/crates.io-index" 281 | dependencies = [ 282 | "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", 283 | "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", 284 | "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", 285 | ] 286 | 287 | [[package]] 288 | name = "unicode-width" 289 | version = "0.1.7" 290 | source = "registry+https://github.com/rust-lang/crates.io-index" 291 | 292 | [[package]] 293 | name = "vec_map" 294 | version = "0.8.1" 295 | source = "registry+https://github.com/rust-lang/crates.io-index" 296 | 297 | [[package]] 298 | name = "winapi" 299 | version = "0.3.8" 300 | source = "registry+https://github.com/rust-lang/crates.io-index" 301 | dependencies = [ 302 | "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 303 | "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", 304 | ] 305 | 306 | [[package]] 307 | name = "winapi-i686-pc-windows-gnu" 308 | version = "0.4.0" 309 | source = "registry+https://github.com/rust-lang/crates.io-index" 310 | 311 | [[package]] 312 | name = "winapi-x86_64-pc-windows-gnu" 313 | version = "0.4.0" 314 | source = "registry+https://github.com/rust-lang/crates.io-index" 315 | 316 | [metadata] 317 | "checksum aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "58fb5e95d83b38284460a5fda7d6470aa0b8844d283a0b614b8535e880800d2d" 318 | "checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" 319 | "checksum arc-swap 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d7b8a9123b8027467bce0099fe556c628a53c8d83df0507084c31e9ba2e39aff" 320 | "checksum atty 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 321 | "checksum autocfg 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "1d49d90015b3c36167a20fe2810c5cd875ad504b39cff3d4eae7977e6b7c1cb2" 322 | "checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 323 | "checksum bytesize 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "716960a18f978640f25101b5cbf1c6f6b0d3192fab36a2d98ca96f0ecbe41010" 324 | "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 325 | "checksum chrono 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)" = "31850b4a4d6bae316f7a09e691c944c28299298837edc0a03f755618c23cbc01" 326 | "checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" 327 | "checksum crossbeam-channel 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "acec9a3b0b3559f15aee4f90746c4e5e293b701c0f7d3925d24e01645267b68c" 328 | "checksum crossbeam-utils 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ce446db02cdc3165b94ae73111e570793400d0794e46125cc4056c81cbb039f4" 329 | "checksum hermit-abi 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "eff2656d88f158ce120947499e971d743c05dbcbed62e5bd2f38f1698bbc3772" 330 | "checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 331 | "checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" 332 | "checksum libsensors-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a1730cc7164b96de1d460c1f87c993430a3dda88ee336f0d2ea9a52097243132" 333 | "checksum memchr 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "148fab2e51b4f1cfc66da2a7c32981d1d3c083a803978268bb11fe4b86925e7a" 334 | "checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e" 335 | "checksum nom 3.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05aec50c70fd288702bcd93284a8444607f3292dbdf2a30de5ea5dcdbe72287b" 336 | "checksum num-integer 0.1.41 (registry+https://github.com/rust-lang/crates.io-index)" = "b85e541ef8255f6cf42bbfe4ef361305c6c135d10919ecc26126c4e5ae94bc09" 337 | "checksum num-traits 0.2.10 (registry+https://github.com/rust-lang/crates.io-index)" = "d4c81ffc11c212fa327657cb19dd85eb7419e163b5b076bede2bdb5c974c07e4" 338 | "checksum numtoa 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef" 339 | "checksum redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)" = "2439c63f3f6139d1b57529d16bc3b8bb855230c8efcc5d3a896c8bea7c3b1e84" 340 | "checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76" 341 | "checksum regex 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dc220bd33bdce8f093101afe22a037b8eb0e5af33592e6a9caafff0d4cb81cbd" 342 | "checksum regex-syntax 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "11a7e20d1cce64ef2fed88b66d347f88bd9babb82845b2b858f3edbf59a4f716" 343 | "checksum sensors 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6993a8ec96ef1f96f4285b5fbe7f80d7c8b2674b20f0c9bbbdaab80d14f0c06e" 344 | "checksum signal-hook 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "7a9c17dd3ba2d36023a5c9472ecddeda07e27fd0b05436e8c1e0c8f178185652" 345 | "checksum signal-hook-registry 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94f478ede9f64724c5d173d7bb56099ec3e2d9fc2774aac65d34b8b890405f41" 346 | "checksum strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 347 | "checksum systemstat 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "2078da8d09c6202bffd5e075946e65bfad5ce2cfa161edb15c5f014a8440adee" 348 | "checksum termion 1.5.4 (registry+https://github.com/rust-lang/crates.io-index)" = "818ef3700c2a7b447dca1a1dd28341fe635e6ee103c806c636bb9c929991b2cd" 349 | "checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 350 | "checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" 351 | "checksum time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f" 352 | "checksum unicode-width 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "caaa9d531767d1ff2150b9332433f32a24622147e5ebb1f26409d5da67afd479" 353 | "checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" 354 | "checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" 355 | "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 356 | "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 357 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "hegemon" 3 | version = "0.1.0" 4 | authors = ["Philipp Emanuel Weidmann "] 5 | description = "A modular system monitor" 6 | repository = "https://github.com/p-e-w/hegemon" 7 | readme = "README.md" 8 | license = "GPL-3.0-or-later" 9 | edition = "2018" 10 | 11 | [[bin]] 12 | name = "hegemon" 13 | path = "src/main.rs" 14 | 15 | [dependencies] 16 | clap = "2.33.0" 17 | crossbeam-channel = "0.4.0" 18 | signal-hook = "0.1.12" 19 | regex = "1.3.1" 20 | termion = "1.5.4" 21 | systemstat = "0.1.5" 22 | sensors = "0.2.1" 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Introducing Hegemon 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/hegemon.svg)](https://crates.io/crates/hegemon) 4 | [![Build Status](https://travis-ci.org/p-e-w/hegemon.svg?branch=master)](https://travis-ci.org/p-e-w/hegemon) 5 | [**GitLab Mirror**](https://gitlab.com/p-e-w/hegemon) 6 | 7 | Hegemon is a **work-in-progress** [modular](#adding-new-data-streams) system monitor 8 | written in safe Rust. 9 | 10 | ![Screencast](https://user-images.githubusercontent.com/2702526/45913619-818f1100-be53-11e8-8138-6ddfe42e15af.gif) 11 | 12 | Currently, it has the following features: 13 | 14 | - Monitor CPU and memory usage, temperatures, and fan speeds 15 | - Expand any data stream to reveal a more detailed graph and additional information 16 | - Adjustable update interval 17 | - Clean MVC architecture with good code quality 18 | - Unit tests 19 | 20 | **Planned** features include: 21 | 22 | - macOS and BSD support (only Linux is supported at the moment) 23 | - Monitor disk and network I/O, GPU usage (maybe), and more 24 | - Select and reorder data streams 25 | - Mouse control 26 | 27 | Hegemon is built around the excellent 28 | [crossbeam-channel](https://github.com/crossbeam-rs/crossbeam/tree/master/crossbeam-channel), 29 | [termion](https://gitlab.redox-os.org/redox-os/termion), 30 | [systemstat](https://github.com/myfreeweb/systemstat), 31 | and [sensors](https://github.com/nyantec/sensors) crates. 32 | 33 | 34 | ## Building 35 | 36 | Hegemon is currently **Linux only** and requires **Rust 1.34 or later** and the 37 | **development files for [libsensors](https://github.com/lm-sensors/lm-sensors).** 38 | The latter can be found in the package repository of every major Linux distribution, 39 | e.g. `lm_sensors-devel` in Fedora and `libsensors4-dev` in Ubuntu. 40 | 41 | Once these requirements are met, Hegemon can be built and run with 42 | 43 | ``` 44 | git clone https://github.com/p-e-w/hegemon.git 45 | cd hegemon 46 | cargo run 47 | ``` 48 | 49 | 50 | ## Adding new data streams 51 | 52 | Unlike traditional system monitors such as `top`, which are tailor-made 53 | to display specific metrics like CPU and memory usage only, Hegemon shows 54 | the output of monitoring modules called *data streams,* whose behavior is 55 | defined by the [`Stream`](src/stream.rs) trait. 56 | 57 | Streams only need to supply basic properties such as name and description, 58 | and a method for retrieving a numeric data value. Everything else is managed 59 | by Hegemon, including update scheduling, layout and rendering, adaptive scaling, 60 | and computation of statistics. 61 | 62 | `Stream` objects are in turn generated by [`StreamProvider`](src/stream.rs)s. 63 | This makes it possible to have streams whose exact nature and number can only 64 | be determined at runtime, such as one stream per CPU core. 65 | 66 | Adding new streams, then, involves the following steps: 67 | 68 | 1. Create a `StreamProvider` 69 | 2. Make it return `Stream` objects from its `streams` method 70 | 3. Register the provider in [`providers/mod.rs`](src/providers/mod.rs) 71 | 72 | The [`providers`](src/providers) directory contains several working provider 73 | implementations that can be used as a reference. In particular, most providers 74 | will want to use the `Stream::new` helper function to create streams 75 | instead of manually implementing the `Stream` trait. 76 | 77 | **Ideas for, and implementations of, additional data streams are very welcome!** 78 | 79 | 80 | ## License 81 | 82 | Copyright © 2018-2020 Philipp Emanuel Weidmann () 83 | 84 | This program is free software: you can redistribute it and/or modify 85 | it under the terms of the GNU General Public License as published by 86 | the Free Software Foundation, either version 3 of the License, or 87 | (at your option) any later version. 88 | 89 | This program is distributed in the hope that it will be useful, 90 | but WITHOUT ANY WARRANTY; without even the implied warranty of 91 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 92 | GNU General Public License for more details. 93 | 94 | You should have received a copy of the GNU General Public License 95 | along with this program. If not, see . 96 | 97 | **By contributing to this project, you agree to release your 98 | contributions under the same license.** 99 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 120 2 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #[macro_use] 18 | extern crate clap; 19 | #[macro_use] 20 | extern crate crossbeam_channel; 21 | extern crate regex; 22 | extern crate sensors; 23 | extern crate signal_hook; 24 | extern crate systemstat; 25 | extern crate termion; 26 | 27 | mod model; 28 | mod providers; 29 | mod stream; 30 | mod terminal; 31 | mod theme; 32 | mod view; 33 | 34 | use crate::model::Application; 35 | use crate::terminal::Terminal; 36 | use crate::theme::Theme; 37 | 38 | fn main() { 39 | let _matches = app_from_crate!().get_matches(); 40 | 41 | let terminal = Terminal::new(); 42 | let (width, height) = terminal.size(); 43 | 44 | let mut application = Application::new(width, height, providers::streams()); 45 | application.update_streams(); 46 | 47 | let theme = Theme::default(); 48 | terminal.print(application.render(&theme)); 49 | 50 | let mut update = crossbeam_channel::tick(application.interval().duration); 51 | 52 | // Main event loop 53 | loop { 54 | select! { 55 | recv(terminal.input) -> event => { 56 | let interval_index = application.interval_index; 57 | 58 | if application.handle(&event.unwrap()) { 59 | if !application.running { 60 | break; 61 | } 62 | if application.interval_index != interval_index { 63 | application.reset_streams(); 64 | application.update_streams(); 65 | update = crossbeam_channel::tick(application.interval().duration); 66 | } 67 | terminal.print(application.render(&theme)); 68 | } else { 69 | // Bell 70 | terminal.print("\x07"); 71 | } 72 | }, 73 | recv(terminal.resize) -> _ => { 74 | let (width, height) = terminal.size(); 75 | application.resize(width, height); 76 | terminal.print(application.render(&theme)); 77 | }, 78 | recv(terminal.terminate) -> _ => { 79 | break; 80 | }, 81 | recv(update) -> _ => { 82 | application.update_streams(); 83 | terminal.print(application.render(&theme)); 84 | }, 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/model.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use std::collections::{HashMap, VecDeque}; 18 | use std::time::Duration; 19 | 20 | use termion::event::{Event, Key, MouseButton, MouseEvent}; 21 | 22 | use crate::stream::Stream; 23 | 24 | const VALUE_HISTORY_SIZE: usize = 512; 25 | 26 | pub struct Application { 27 | pub running: bool, 28 | pub width: usize, 29 | pub height: usize, 30 | pub screen: Screen, 31 | pub streams: Vec, 32 | pub selection_index: usize, 33 | pub scroll_index: usize, 34 | pub scroll_anchor: ScrollAnchor, 35 | intervals: Vec, 36 | pub interval_index: usize, 37 | // The two parts of the map value contain 38 | // the left/right-aligned menu items, respectively 39 | menus: HashMap, Vec)>, 40 | } 41 | 42 | impl Application { 43 | pub fn new(width: usize, height: usize, streams: Vec>) -> Self { 44 | let mut menus = HashMap::new(); 45 | 46 | menus.insert( 47 | Screen::Main, 48 | ( 49 | vec![ 50 | MenuItem::new("\u{1F805}\u{1F807}", "Select"), 51 | MenuItem::new("Space", "Expand"), 52 | MenuItem::new("S", "Streams"), 53 | MenuItem::new("+-", "Interval"), 54 | ], 55 | vec![MenuItem::new("Q", "Quit")], 56 | ), 57 | ); 58 | 59 | menus.insert( 60 | Screen::Streams, 61 | ( 62 | vec![ 63 | MenuItem::new("\u{1F805}\u{1F807}", "Select"), 64 | MenuItem::new("Space", "Toggle"), 65 | MenuItem::new("+-", "Reorder"), 66 | ], 67 | vec![MenuItem::new("Esc", "Done")], 68 | ), 69 | ); 70 | 71 | Application { 72 | running: true, 73 | width, 74 | height, 75 | screen: Screen::Main, 76 | streams: streams.into_iter().map(StreamWrapper::new).collect(), 77 | selection_index: 0, 78 | scroll_index: 0, 79 | scroll_anchor: ScrollAnchor::Top, 80 | intervals: vec![ 81 | Interval::new(100, 10), 82 | Interval::new(200, 10), 83 | Interval::new(500, 10), 84 | Interval::new(1_000, 10), 85 | Interval::new(2_000, 15), 86 | Interval::new(3_000, 10), 87 | Interval::new(5_000, 12), 88 | Interval::new(10_000, 12), 89 | Interval::new(30_000, 10), 90 | Interval::new(60_000, 10), 91 | Interval::new(300_000, 12), 92 | ], 93 | interval_index: 3, 94 | menus, 95 | } 96 | } 97 | 98 | pub fn interval(&self) -> Interval { 99 | self.intervals[self.interval_index] 100 | } 101 | 102 | pub fn menu(&self) -> (Vec, Vec) { 103 | self.menus[&self.screen].clone() 104 | } 105 | 106 | pub fn active_streams(&self) -> Vec<&StreamWrapper> { 107 | self.streams.iter().filter(|s| s.active).collect() 108 | } 109 | 110 | pub fn handle(&mut self, event: &Event) -> bool { 111 | match self.screen { 112 | Screen::Main => match event { 113 | Event::Key(key) => match key { 114 | Key::Up => { 115 | if self.selection_index > 0 { 116 | self.selection_index -= 1; 117 | self.scroll_to_stream(self.selection_index); 118 | return true; 119 | } 120 | } 121 | Key::Down => { 122 | if self.selection_index < self.active_streams().len() - 1 { 123 | self.selection_index += 1; 124 | self.scroll_to_stream(self.selection_index); 125 | return true; 126 | } 127 | } 128 | Key::Char(' ') => { 129 | let stream = self 130 | .streams 131 | .iter_mut() 132 | .filter(|s| s.active) 133 | .nth(self.selection_index) 134 | .unwrap(); 135 | stream.expanded = !stream.expanded; 136 | self.scroll_to_stream(self.selection_index); 137 | return true; 138 | } 139 | Key::Char('s') => { 140 | self.screen = Screen::Streams; 141 | return true; 142 | } 143 | Key::Char('+') => { 144 | if self.interval_index < self.intervals.len() - 1 { 145 | self.interval_index += 1; 146 | return true; 147 | } 148 | } 149 | Key::Char('-') => { 150 | if self.interval_index > 0 { 151 | self.interval_index -= 1; 152 | return true; 153 | } 154 | } 155 | Key::Char('q') => { 156 | self.running = false; 157 | return true; 158 | } 159 | _ => {} 160 | }, 161 | Event::Mouse(MouseEvent::Press(mouse_button, _, _)) => match mouse_button { 162 | MouseButton::WheelUp => { 163 | return self.handle(&Event::Key(Key::Down)); 164 | } 165 | MouseButton::WheelDown => { 166 | return self.handle(&Event::Key(Key::Up)); 167 | } 168 | _ => {} 169 | }, 170 | _ => {} 171 | }, 172 | 173 | Screen::Streams => match event { 174 | Event::Key(key) => match key { 175 | Key::Up => {} 176 | Key::Down => {} 177 | Key::Char(' ') => {} 178 | Key::Char('+') => {} 179 | Key::Char('-') => {} 180 | Key::Esc => { 181 | self.screen = Screen::Main; 182 | return true; 183 | } 184 | _ => {} 185 | }, 186 | Event::Mouse(MouseEvent::Press(mouse_button, _, _)) => match mouse_button { 187 | MouseButton::WheelUp => {} 188 | MouseButton::WheelDown => {} 189 | _ => {} 190 | }, 191 | _ => {} 192 | }, 193 | } 194 | 195 | false 196 | } 197 | 198 | pub fn resize(&mut self, width: usize, height: usize) { 199 | self.width = width; 200 | self.height = height; 201 | } 202 | 203 | fn scroll_to_stream(&mut self, index: usize) { 204 | let active_streams = self.active_streams(); 205 | 206 | let streams = match self.scroll_anchor { 207 | ScrollAnchor::Top => active_streams[self.scroll_index..].iter().collect::>(), 208 | ScrollAnchor::Bottom => active_streams[..=self.scroll_index].iter().rev().collect::>(), 209 | }; 210 | 211 | let mut stream_count = 0; 212 | let mut available_height = self.height - 2; 213 | 214 | for stream in streams { 215 | let height = stream.height(); 216 | if height > available_height { 217 | break; 218 | } 219 | stream_count += 1; 220 | available_height -= height; 221 | } 222 | 223 | // Only count streams beyond the first 224 | if stream_count > 0 { 225 | stream_count -= 1; 226 | } 227 | 228 | // Indices of the first and last streams that are *completely* visible 229 | let (top_index, bottom_index) = match self.scroll_anchor { 230 | ScrollAnchor::Top => (self.scroll_index, self.scroll_index + stream_count), 231 | ScrollAnchor::Bottom => (self.scroll_index - stream_count, self.scroll_index), 232 | }; 233 | 234 | if index < top_index { 235 | self.scroll_index = index; 236 | self.scroll_anchor = ScrollAnchor::Top; 237 | } else if index > bottom_index { 238 | self.scroll_index = index; 239 | self.scroll_anchor = ScrollAnchor::Bottom; 240 | } 241 | } 242 | 243 | pub fn update_streams(&mut self) { 244 | for stream in &mut self.streams { 245 | if stream.active { 246 | let value = stream.stream.value(); 247 | 248 | if let Some(number) = value { 249 | assert!(number.is_finite()); 250 | if let Some(min) = stream.stream.min() { 251 | assert!(number >= min); 252 | } 253 | if let Some(max) = stream.stream.max() { 254 | assert!(number <= max); 255 | } 256 | } 257 | 258 | stream.values.push_back(value); 259 | 260 | if stream.values.len() > VALUE_HISTORY_SIZE { 261 | stream.values.pop_front(); 262 | } 263 | } 264 | } 265 | } 266 | 267 | pub fn reset_streams(&mut self) { 268 | for stream in &mut self.streams { 269 | // TODO: Reset stream's internal state 270 | stream.values.clear(); 271 | } 272 | } 273 | } 274 | 275 | #[derive(PartialEq, Eq, Hash)] 276 | pub enum Screen { 277 | Main, 278 | Streams, 279 | } 280 | 281 | pub struct StreamWrapper { 282 | pub stream: Box, 283 | pub values: VecDeque>, 284 | pub active: bool, 285 | pub expanded: bool, 286 | } 287 | 288 | impl StreamWrapper { 289 | fn new(stream: Box) -> Self { 290 | StreamWrapper { 291 | stream, 292 | values: VecDeque::new(), 293 | active: true, 294 | expanded: false, 295 | } 296 | } 297 | } 298 | 299 | #[derive(PartialEq, Eq)] 300 | pub enum ScrollAnchor { 301 | Top, 302 | Bottom, 303 | } 304 | 305 | #[derive(Copy, Clone)] 306 | pub struct Interval { 307 | pub duration: Duration, 308 | pub tick_spacing: usize, 309 | } 310 | 311 | impl Interval { 312 | fn new(milliseconds: u64, tick_spacing: usize) -> Self { 313 | Interval { 314 | duration: Duration::from_millis(milliseconds), 315 | tick_spacing, 316 | } 317 | } 318 | } 319 | 320 | #[derive(Clone)] 321 | pub struct MenuItem { 322 | pub keys: String, 323 | pub label: String, 324 | } 325 | 326 | impl MenuItem { 327 | fn new(keys: impl Into, label: impl Into) -> Self { 328 | MenuItem { 329 | keys: keys.into(), 330 | label: label.into(), 331 | } 332 | } 333 | } 334 | -------------------------------------------------------------------------------- /src/providers/cpu.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use std::io::{self, Error, ErrorKind}; 18 | 19 | use systemstat::{CPULoad, DelayedMeasurement, Platform, System}; 20 | 21 | use crate::stream::{Stream, StreamProvider}; 22 | 23 | pub struct CPUStreamProvider {} 24 | 25 | impl StreamProvider for CPUStreamProvider { 26 | fn streams(&self) -> Vec> { 27 | let mut streams = Vec::new(); 28 | 29 | let mut load: io::Result> = Err(Error::new(ErrorKind::Other, "")); 30 | 31 | streams.push(Stream::new( 32 | "CPU", 33 | "Average utilization of all CPU cores during the past interval", 34 | move || { 35 | let value = if let Ok(ref load) = load { 36 | if let Ok(load) = load.done() { 37 | Some(f64::from((1.0 - load.idle) * 100.0)) 38 | } else { 39 | None 40 | } 41 | } else { 42 | None 43 | }; 44 | load = System::new().cpu_load_aggregate(); 45 | value 46 | }, 47 | Some(0.0), 48 | Some(100.0), 49 | "%", 50 | Some(3), 51 | 1, 52 | false, 53 | )); 54 | 55 | if let Ok(cpu) = System::new().cpu_load() { 56 | if let Ok(cpu) = cpu.done() { 57 | for i in 0..cpu.len() { 58 | let mut load: io::Result>> = Err(Error::new(ErrorKind::Other, "")); 59 | 60 | streams.push(Stream::new( 61 | format!("Core{}", i + 1), 62 | format!("Utilization of CPU core {} during the past interval", i + 1), 63 | move || { 64 | let value = if let Ok(ref load) = load { 65 | if let Ok(load) = load.done() { 66 | Some(f64::from((1.0 - load[i].idle) * 100.0)) 67 | } else { 68 | None 69 | } 70 | } else { 71 | None 72 | }; 73 | load = System::new().cpu_load(); 74 | value 75 | }, 76 | Some(0.0), 77 | Some(100.0), 78 | "%", 79 | Some(3), 80 | 1, 81 | false, 82 | )); 83 | } 84 | } 85 | } 86 | 87 | streams 88 | } 89 | } 90 | 91 | #[cfg(test)] 92 | mod tests { 93 | use super::*; 94 | 95 | #[test] 96 | fn test_cpu_stream_provider() { 97 | let streams = CPUStreamProvider {}.streams(); 98 | assert!(!streams.is_empty()); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/providers/fan.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use regex::Regex; 18 | use sensors::{FeatureType::SENSORS_FEATURE_FAN, SubfeatureType::SENSORS_SUBFEATURE_FAN_INPUT}; 19 | 20 | use crate::providers::subfeatures; 21 | use crate::stream::{Stream, StreamProvider}; 22 | 23 | pub struct FanStreamProvider {} 24 | 25 | impl StreamProvider for FanStreamProvider { 26 | fn streams(&self) -> Vec> { 27 | let mut streams = Vec::new(); 28 | 29 | let regex = Regex::new(r"(?i)fan").unwrap(); 30 | 31 | for (subfeature, feature_label, chip_name) in subfeatures(SENSORS_FEATURE_FAN, SENSORS_SUBFEATURE_FAN_INPUT) { 32 | let name = regex.replace_all(&feature_label, "").replace(" ", ""); 33 | 34 | streams.push(Stream::new( 35 | format!("{}Fan", name), 36 | format!("Fan speed (feature {} on chip {})", feature_label, chip_name), 37 | move || subfeature.get_value().ok(), 38 | None, 39 | None, 40 | "RPM", 41 | Some(4), 42 | 0, 43 | false, 44 | )); 45 | } 46 | 47 | streams 48 | } 49 | } 50 | 51 | #[cfg(test)] 52 | mod tests { 53 | use super::*; 54 | 55 | #[test] 56 | #[ignore] 57 | fn test_fan_stream_provider() { 58 | let streams = FanStreamProvider {}.streams(); 59 | assert!(!streams.is_empty()); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/providers/memory.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use systemstat::{Platform, System}; 18 | 19 | use crate::stream::{Stream, StreamProvider}; 20 | 21 | const SWAP_TOTAL: &str = "SwapTotal"; 22 | const SWAP_FREE: &str = "SwapFree"; 23 | 24 | pub struct MemoryStreamProvider {} 25 | 26 | impl StreamProvider for MemoryStreamProvider { 27 | fn streams(&self) -> Vec> { 28 | let mut streams = Vec::new(); 29 | 30 | if let Ok(memory) = System::new().memory() { 31 | streams.push(Stream::new( 32 | "Mem", 33 | "Amount of physical memory (RAM) in use", 34 | move || { 35 | if let Ok(memory) = System::new().memory() { 36 | Some((memory.total.as_u64() - memory.free.as_u64()) as f64) 37 | } else { 38 | None 39 | } 40 | }, 41 | Some(0.0), 42 | Some(memory.total.as_u64() as f64), 43 | "B", 44 | None, 45 | 1, 46 | false, 47 | )); 48 | 49 | let meminfo = memory.platform_memory.meminfo; 50 | if meminfo.contains_key(SWAP_TOTAL) && meminfo.contains_key(SWAP_FREE) { 51 | streams.push(Stream::new( 52 | "Swap", 53 | "Amount of swap space in use", 54 | move || { 55 | if let Ok(memory) = System::new().memory() { 56 | let meminfo = memory.platform_memory.meminfo; 57 | Some((meminfo[SWAP_TOTAL].as_u64() - meminfo[SWAP_FREE].as_u64()) as f64) 58 | } else { 59 | None 60 | } 61 | }, 62 | Some(0.0), 63 | Some(meminfo[SWAP_TOTAL].as_u64() as f64), 64 | "B", 65 | None, 66 | 1, 67 | false, 68 | )); 69 | } 70 | } 71 | 72 | streams 73 | } 74 | } 75 | 76 | #[cfg(test)] 77 | mod tests { 78 | use super::*; 79 | 80 | #[test] 81 | fn test_memory_stream_provider() { 82 | let streams = MemoryStreamProvider {}.streams(); 83 | assert!(!streams.is_empty()); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/providers/mod.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | mod cpu; 18 | mod fan; 19 | mod memory; 20 | mod network; 21 | mod temperature; 22 | 23 | use sensors::{FeatureType, Sensors, Subfeature, SubfeatureType}; 24 | 25 | use self::cpu::CPUStreamProvider; 26 | use self::fan::FanStreamProvider; 27 | use self::memory::MemoryStreamProvider; 28 | use self::network::BandwidthStreamProvider; 29 | use self::temperature::TemperatureStreamProvider; 30 | use crate::stream::{Stream, StreamProvider}; 31 | 32 | pub fn streams() -> Vec> { 33 | let providers: Vec> = vec![ 34 | Box::new(CPUStreamProvider {}), 35 | Box::new(MemoryStreamProvider {}), 36 | Box::new(TemperatureStreamProvider {}), 37 | Box::new(FanStreamProvider {}), 38 | Box::new(BandwidthStreamProvider {}), 39 | ]; 40 | 41 | providers.iter().flat_map(|p| p.streams()).collect() 42 | } 43 | 44 | fn subfeatures(feature_type: FeatureType, subfeature_type: SubfeatureType) -> Vec<(Subfeature, String, String)> { 45 | let mut subfeatures = Vec::new(); 46 | 47 | for chip in Sensors::new() { 48 | if let Ok(chip_name) = chip.get_name() { 49 | for feature in chip { 50 | if *feature.feature_type() == feature_type { 51 | if let Ok(feature_label) = feature.get_label() { 52 | for subfeature in feature { 53 | if *subfeature.subfeature_type() == subfeature_type { 54 | subfeatures.push((subfeature, feature_label.clone(), chip_name.clone())); 55 | } 56 | } 57 | } 58 | } 59 | } 60 | } 61 | } 62 | 63 | subfeatures 64 | } 65 | -------------------------------------------------------------------------------- /src/providers/network.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // Copyright (C) 2020 Astro 4 | // 5 | // This program is free software: you can redistribute it and/or modify 6 | // it under the terms of the GNU General Public License as published by 7 | // the Free Software Foundation, either version 3 of the License, or 8 | // (at your option) any later version. 9 | // 10 | // This program is distributed in the hope that it will be useful, 11 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | // GNU General Public License for more details. 14 | // 15 | // You should have received a copy of the GNU General Public License 16 | // along with this program. If not, see . 17 | 18 | use std::time::Instant; 19 | 20 | use systemstat::{Platform, System}; 21 | 22 | use crate::stream::{Stream, StreamProvider}; 23 | 24 | pub struct BandwidthStreamProvider {} 25 | 26 | impl StreamProvider for BandwidthStreamProvider { 27 | fn streams(&self) -> Vec> { 28 | let mut streams = Vec::new(); 29 | let platform = System::new(); 30 | 31 | if let Ok(networks) = platform.networks() { 32 | for network in networks.values() { 33 | let name = network.name.clone(); 34 | streams.push(Stream::new( 35 | format!("{}Rx", name), 36 | format!("Ingress bandwidth on {} during the past interval", network.name), 37 | rate_calculator(move || { 38 | System::new() 39 | .network_stats(&name) 40 | .ok() 41 | .map(|stats| stats.rx_bytes.as_u64() as f64) 42 | }), 43 | Some(0.0), 44 | None, 45 | "B", 46 | None, 47 | 1, 48 | false, 49 | )); 50 | let name = network.name.clone(); 51 | streams.push(Stream::new( 52 | format!("{}Tx", name), 53 | format!("Egress bandwidth on {} during the past interval", network.name), 54 | rate_calculator(move || { 55 | System::new() 56 | .network_stats(&name) 57 | .ok() 58 | .map(|stats| stats.tx_bytes.as_u64() as f64) 59 | }), 60 | Some(0.0), 61 | None, 62 | "B", 63 | None, 64 | 1, 65 | false, 66 | )); 67 | } 68 | } 69 | 70 | streams 71 | } 72 | } 73 | 74 | fn rate_calculator(mut value: F) -> impl FnMut() -> Option + 'static 75 | where 76 | F: FnMut() -> Option + 'static, 77 | { 78 | let mut last_time = Instant::now(); 79 | let mut last_input = None; 80 | move || match value() { 81 | Some(input) => { 82 | let now = Instant::now(); 83 | let dt = ((now - last_time).as_millis() as f64) / 1000.0; 84 | let value = last_input.map(|last_input| { 85 | if input > last_input { 86 | (input - last_input) / dt 87 | } else { 88 | 0.0 89 | } 90 | }); 91 | last_input = Some(input); 92 | last_time = now; 93 | value 94 | } 95 | None => { 96 | last_input = None; 97 | None 98 | } 99 | } 100 | } 101 | 102 | #[cfg(test)] 103 | mod tests { 104 | use super::*; 105 | 106 | #[test] 107 | fn test_bandwidth_stream_provider() { 108 | let streams = BandwidthStreamProvider {}.streams(); 109 | assert!(!streams.is_empty()); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/providers/temperature.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use sensors::{FeatureType::SENSORS_FEATURE_TEMP, SubfeatureType::SENSORS_SUBFEATURE_TEMP_INPUT}; 18 | 19 | use crate::providers::subfeatures; 20 | use crate::stream::{Stream, StreamProvider}; 21 | 22 | pub struct TemperatureStreamProvider {} 23 | 24 | impl StreamProvider for TemperatureStreamProvider { 25 | fn streams(&self) -> Vec> { 26 | let mut streams = Vec::new(); 27 | 28 | let mut core_index = 0; 29 | let mut package_index = 0; 30 | 31 | for (subfeature, feature_label, chip_name) in subfeatures(SENSORS_FEATURE_TEMP, SENSORS_SUBFEATURE_TEMP_INPUT) { 32 | let name_description = if feature_label.to_lowercase() == "cpu" { 33 | Some((String::from("CPU"), String::from("Temperature of CPU"))) 34 | } else if feature_label.to_lowercase().contains("core") { 35 | core_index += 1; 36 | Some(( 37 | format!("Core{}", core_index), 38 | format!("Temperature of CPU core {}", core_index), 39 | )) 40 | } else if feature_label.to_lowercase().contains("package id") { 41 | package_index += 1; 42 | Some(( 43 | format!("Package {}", package_index), 44 | format!("Temperature of CPU package {}", package_index), 45 | )) 46 | } else { 47 | None 48 | }; 49 | 50 | if let Some((name, description)) = name_description { 51 | streams.push(Stream::new( 52 | format!("{}Temp", name), 53 | format!("{} (feature {} on chip {})", description, feature_label, chip_name), 54 | move || subfeature.get_value().ok(), 55 | None, 56 | None, 57 | "°C", 58 | Some(3), 59 | 1, 60 | true, 61 | )); 62 | } 63 | } 64 | 65 | streams 66 | } 67 | } 68 | 69 | #[cfg(test)] 70 | mod tests { 71 | use super::*; 72 | 73 | #[test] 74 | #[ignore] 75 | fn test_temperature_stream_provider() { 76 | let streams = TemperatureStreamProvider {}.streams(); 77 | assert!(!streams.is_empty()); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/stream.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use termion::color::Fg; 18 | 19 | use crate::theme::Theme; 20 | use crate::view::{format_quantity, printed_width}; 21 | 22 | pub trait StreamProvider { 23 | /// Returns a list of data stream objects. 24 | fn streams(&self) -> Vec>; 25 | } 26 | 27 | pub trait Stream { 28 | /// Returns the name of this data stream, to be used both as an identifier 29 | /// and for labeling the stream in the user interface. 30 | /// This method **must** return the same value each time it is called, 31 | /// and that value **must** be unique among all data streams. 32 | fn name(&self) -> String; 33 | 34 | /// Returns a detailed description of this data stream. 35 | /// This method **must** return the same value each time it is called. 36 | fn description(&self) -> String; 37 | 38 | /// Returns the current value of the quantity represented by this data stream, 39 | /// or `None` if no value can be determined at this time. 40 | fn value(&mut self) -> Option; 41 | 42 | /// Returns the minimum value of the quantity represented by this data stream, 43 | /// or `None` to have the minimum dynamically calculated from all value samples. 44 | /// This method **must** return the same value each time it is called. 45 | fn min(&self) -> Option { 46 | None 47 | } 48 | 49 | /// Returns the maximum value of the quantity represented by this data stream, 50 | /// or `None` to have the maximum dynamically calculated from all value samples. 51 | /// This method **must** return the same value each time it is called. 52 | fn max(&self) -> Option { 53 | None 54 | } 55 | 56 | /// Returns a human-readable representation of the given value. 57 | /// The result should make use of the appropriate colors from the given theme. 58 | fn format(&self, value: f64, theme: &Theme) -> String; 59 | 60 | /// Returns the maximum width, in characters when printed to the terminal, 61 | /// of all values that the `format` method can return. 62 | /// This method **must** return the same value each time it is called. 63 | fn format_width(&self) -> usize; 64 | } 65 | 66 | impl dyn Stream { 67 | #[allow(clippy::too_many_arguments)] 68 | pub fn new( 69 | name: impl Into, 70 | description: impl Into, 71 | value: impl FnMut() -> Option + 'static, 72 | min: Option, 73 | max: Option, 74 | unit: impl Into, 75 | digits_before_decimal: Option, 76 | precision: usize, 77 | signed: bool, 78 | ) -> Box { 79 | let unit_1 = unit.into(); 80 | let unit_2 = unit_1.clone(); 81 | 82 | let use_prefix = digits_before_decimal.is_none(); 83 | 84 | Box::new(SimpleStream { 85 | name: name.into(), 86 | description: description.into(), 87 | value: Box::new(value), 88 | min, 89 | max, 90 | format: Box::new(move |value: f64, theme: &Theme| { 91 | format_quantity( 92 | value, 93 | &unit_1, 94 | use_prefix, 95 | precision, 96 | Fg(theme.stream_number_color), 97 | Fg(theme.stream_unit_color), 98 | ) 99 | }), 100 | format_width: 101 | // Sign 102 | (if signed { 1 } else { 0 }) + 103 | // Digits before decimal point 104 | digits_before_decimal.unwrap_or(3) + 105 | // Decimal point and digits after it 106 | (if precision > 0 { 1 + precision } else { 0 }) + 107 | // Unit prefix 108 | (if use_prefix { 1 } else { 0 }) + 109 | // Unit 110 | printed_width(unit_2), 111 | }) 112 | } 113 | } 114 | 115 | struct SimpleStream { 116 | name: String, 117 | description: String, 118 | value: Box Option>, 119 | min: Option, 120 | max: Option, 121 | format: Box String>, 122 | format_width: usize, 123 | } 124 | 125 | impl Stream for SimpleStream { 126 | fn name(&self) -> String { 127 | self.name.clone() 128 | } 129 | 130 | fn description(&self) -> String { 131 | self.description.clone() 132 | } 133 | 134 | fn value(&mut self) -> Option { 135 | (self.value)() 136 | } 137 | 138 | fn min(&self) -> Option { 139 | self.min 140 | } 141 | 142 | fn max(&self) -> Option { 143 | self.max 144 | } 145 | 146 | fn format(&self, value: f64, theme: &Theme) -> String { 147 | (self.format)(value, theme) 148 | } 149 | 150 | fn format_width(&self) -> usize { 151 | self.format_width 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /src/terminal.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use std::io::{self, Write}; 18 | use std::thread; 19 | 20 | use crossbeam_channel::{self, Receiver}; 21 | use signal_hook::{iterator::Signals, SIGINT, SIGTERM, SIGWINCH}; 22 | use termion::event::Event; 23 | use termion::input::{MouseTerminal, TermRead}; 24 | use termion::raw::IntoRawMode; 25 | use termion::screen::AlternateScreen; 26 | use termion::{self, clear, cursor}; 27 | 28 | // See https://vt100.net/docs/vt102-ug/chapter5.html#S5.5.2.8 29 | const ENABLE_AUTO_WRAP: &str = "\x1B[?7h"; 30 | const DISABLE_AUTO_WRAP: &str = "\x1B[?7l"; 31 | 32 | pub struct Terminal { 33 | #[allow(dead_code)] 34 | wrapper: Box, 35 | pub input: Receiver, 36 | pub resize: Receiver, 37 | pub terminate: Receiver, 38 | } 39 | 40 | impl Terminal { 41 | pub fn new() -> Self { 42 | // "If you want to avoid the race condition completely, 43 | // initialize all signal handling before starting any threads." 44 | // (`signal_hook` documentation) 45 | let signals = Signals::new(&[SIGWINCH, SIGINT, SIGTERM]).unwrap(); 46 | 47 | let (resize_sender, resize) = crossbeam_channel::unbounded(); 48 | let (terminate_sender, terminate) = crossbeam_channel::unbounded(); 49 | 50 | thread::spawn(move || { 51 | for signal in &signals { 52 | match signal { 53 | SIGWINCH => resize_sender.send(true).unwrap(), 54 | SIGINT | SIGTERM => terminate_sender.send(true).unwrap(), 55 | _ => unreachable!(), 56 | } 57 | } 58 | }); 59 | 60 | let (input_sender, input) = crossbeam_channel::unbounded(); 61 | 62 | thread::spawn(move || { 63 | for event in io::stdin().events() { 64 | input_sender.send(event.unwrap()).unwrap(); 65 | } 66 | }); 67 | 68 | let terminal = Terminal { 69 | wrapper: Box::new(MouseTerminal::from(AlternateScreen::from( 70 | io::stdout().into_raw_mode().unwrap(), 71 | ))), 72 | input, 73 | resize, 74 | terminate, 75 | }; 76 | 77 | terminal.print(format!( 78 | "{}{}{}{}", 79 | cursor::Hide, 80 | clear::All, 81 | cursor::Goto(1, 1), 82 | DISABLE_AUTO_WRAP, 83 | )); 84 | 85 | terminal 86 | } 87 | 88 | pub fn print(&self, output: impl AsRef<[u8]>) { 89 | io::stdout().write_all(output.as_ref()).unwrap(); 90 | io::stdout().flush().unwrap(); 91 | } 92 | 93 | pub fn size(&self) -> (usize, usize) { 94 | let (width, height) = termion::terminal_size().unwrap(); 95 | (width as usize, height as usize) 96 | } 97 | } 98 | 99 | // NOTE: This could be simplified if https://github.com/redox-os/termion/pull/113 were merged 100 | impl Drop for Terminal { 101 | fn drop(&mut self) { 102 | self.print(format!("{}{}", ENABLE_AUTO_WRAP, cursor::Show)); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/theme.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use termion::color::AnsiValue; 18 | 19 | pub struct Theme { 20 | /// Background color of the main screen's top bar 21 | pub top_bar_color: AnsiValue, 22 | /// Color of numbers in the top bar's interval tick labels 23 | pub top_bar_number_color: AnsiValue, 24 | /// Color of units in the top bar's interval tick labels 25 | pub top_bar_unit_color: AnsiValue, 26 | /// Color of vertical lines intersecting the graphs 27 | pub tick_color: AnsiValue, 28 | /// Background color of even-numbered streams (count starts at zero) 29 | pub stream_even_background_color: AnsiValue, 30 | /// Background color of odd-numbered streams (count starts at zero) 31 | pub stream_odd_background_color: AnsiValue, 32 | /// Background color of the selected stream 33 | pub stream_selected_background_color: AnsiValue, 34 | /// Color of stream names in unselected streams 35 | pub stream_name_color: AnsiValue, 36 | /// Foreground color of the selected stream's name 37 | pub stream_name_selected_text_color: AnsiValue, 38 | /// Background color of the selected stream's name 39 | pub stream_name_selected_background_color: AnsiValue, 40 | /// Color of stream descriptions 41 | pub stream_description_color: AnsiValue, 42 | /// Color of numbers in stream values 43 | pub stream_number_color: AnsiValue, 44 | /// Color of units in stream values 45 | pub stream_unit_color: AnsiValue, 46 | /// Colors of stream graphs, to be repeated cyclically. 47 | /// The first element in each pair is the regular color, 48 | /// the second the color for tick intersections. 49 | pub stream_graph_colors: Vec<(AnsiValue, AnsiValue)>, 50 | /// Background color of the bottom bar 51 | pub bottom_bar_color: AnsiValue, 52 | /// Foreground color of key labels in the bottom bar's menu items 53 | pub bottom_bar_key_text_color: AnsiValue, 54 | /// Background color of key labels in the bottom bar's menu items 55 | pub bottom_bar_key_background_color: AnsiValue, 56 | /// Color of labels in the bottom bar's menu items 57 | pub bottom_bar_label_color: AnsiValue, 58 | /// Color of numbers in the bottom bar's interval label 59 | pub bottom_bar_number_color: AnsiValue, 60 | /// Color of units in the bottom bar's interval label 61 | pub bottom_bar_unit_color: AnsiValue, 62 | } 63 | 64 | impl Theme { 65 | pub fn default() -> Self { 66 | Theme { 67 | top_bar_color: AnsiValue::grayscale(4), 68 | top_bar_number_color: AnsiValue::grayscale(18), 69 | top_bar_unit_color: AnsiValue::grayscale(12), 70 | tick_color: AnsiValue::grayscale(3), 71 | stream_even_background_color: AnsiValue::grayscale(0), 72 | stream_odd_background_color: AnsiValue::grayscale(1), 73 | stream_selected_background_color: AnsiValue::grayscale(2), 74 | stream_name_color: AnsiValue::grayscale(23), 75 | stream_name_selected_text_color: AnsiValue::grayscale(0), 76 | stream_name_selected_background_color: AnsiValue::grayscale(18), 77 | stream_description_color: AnsiValue::grayscale(16), 78 | stream_number_color: AnsiValue::grayscale(20), 79 | stream_unit_color: AnsiValue::grayscale(12), 80 | stream_graph_colors: vec![ 81 | (AnsiValue::rgb(4, 0, 0), AnsiValue::rgb(5, 1, 1)), 82 | (AnsiValue::rgb(0, 4, 0), AnsiValue::rgb(1, 5, 1)), 83 | (AnsiValue::rgb(1, 1, 5), AnsiValue::rgb(2, 2, 5)), 84 | (AnsiValue::rgb(4, 4, 0), AnsiValue::rgb(5, 5, 1)), 85 | (AnsiValue::rgb(5, 0, 5), AnsiValue::rgb(5, 1, 5)), 86 | (AnsiValue::rgb(0, 4, 3), AnsiValue::rgb(1, 5, 4)), 87 | ], 88 | bottom_bar_color: AnsiValue::grayscale(15), 89 | bottom_bar_key_text_color: AnsiValue::grayscale(0), 90 | bottom_bar_key_background_color: AnsiValue::grayscale(20), 91 | bottom_bar_label_color: AnsiValue::grayscale(0), 92 | bottom_bar_number_color: AnsiValue::rgb(0, 0, 5), 93 | bottom_bar_unit_color: AnsiValue::rgb(0, 0, 2), 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/view.rs: -------------------------------------------------------------------------------- 1 | // Hegemon - A modular system monitor 2 | // Copyright (C) 2018-2020 Philipp Emanuel Weidmann 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | use std::cmp::max; 18 | use std::f64; 19 | use std::fmt::Display; 20 | use std::time::Duration; 21 | 22 | use regex::Regex; 23 | use termion::color::{Bg, Fg}; 24 | use termion::cursor; 25 | use termion::style::Reset; 26 | 27 | use crate::model::{Application, MenuItem, Screen, ScrollAnchor, StreamWrapper}; 28 | use crate::theme::Theme; 29 | 30 | const EXPANDED_GRAPH_HEIGHT: usize = 5; 31 | 32 | const STATS_LABEL: &str = "lo/hi/avg"; 33 | 34 | const DOT: &str = "\u{2022}"; 35 | const BARS: &[&str] = &[ 36 | "\u{2581}", "\u{2582}", "\u{2583}", "\u{2584}", "\u{2585}", "\u{2586}", "\u{2587}", "\u{2588}", 37 | ]; 38 | 39 | impl Application { 40 | pub fn render(&self, theme: &Theme) -> String { 41 | let mut string = format!("{}{}", cursor::Goto(1, 1), Reset); 42 | 43 | match self.screen { 44 | Screen::Main => { 45 | let name_width = self.name_width(); 46 | let value_width = self.value_width(); 47 | 48 | let width = max(self.width, name_width + 3 + value_width); 49 | let height = max(self.height, 3); 50 | 51 | let graph_width = width - name_width - value_width - 2; 52 | 53 | let interval = self.interval(); 54 | let full_intervals = (graph_width - 1) / interval.tick_spacing; 55 | let first_tick_padding = name_width + 1 + (graph_width - 1 - (full_intervals * interval.tick_spacing)); 56 | 57 | // Render top bar 58 | string.push_str(&format!("{}", Bg(theme.top_bar_color))); 59 | string.push_str(&" ".repeat(first_tick_padding)); 60 | 61 | for i in (1..=full_intervals).rev() { 62 | let time = interval.duration * ((i * interval.tick_spacing) as u32); 63 | let time_string = 64 | format_duration(time, Fg(theme.top_bar_number_color), Fg(theme.top_bar_unit_color)); 65 | string.push_str(&pad_right(time_string, interval.tick_spacing)); 66 | } 67 | 68 | string.push_str(&format!("{}Now", Fg(theme.top_bar_unit_color))); 69 | string.push_str(&" ".repeat(value_width - 1)); 70 | 71 | let max_lines = height - 2; 72 | 73 | let streams = self.active_streams(); 74 | 75 | let indices = match self.scroll_anchor { 76 | ScrollAnchor::Top => (self.scroll_index..streams.len()).collect::>(), 77 | ScrollAnchor::Bottom => (0..=self.scroll_index).rev().collect::>(), 78 | }; 79 | 80 | let mut lines = Vec::new(); 81 | 82 | // Render data streams 83 | 'outer: for i in indices { 84 | let mut stream_lines = streams[i].render( 85 | i, 86 | i == self.selection_index, 87 | name_width, 88 | graph_width, 89 | value_width, 90 | interval.tick_spacing, 91 | theme, 92 | ); 93 | 94 | if self.scroll_anchor == ScrollAnchor::Bottom { 95 | stream_lines.reverse(); 96 | } 97 | 98 | for line in stream_lines { 99 | if lines.len() >= max_lines { 100 | break 'outer; 101 | } 102 | 103 | match self.scroll_anchor { 104 | ScrollAnchor::Top => lines.push(line), 105 | ScrollAnchor::Bottom => lines.insert(0, line), 106 | } 107 | } 108 | } 109 | 110 | if !lines.is_empty() { 111 | string.push_str("\n\r"); 112 | string.push_str(&lines.join("\n\r")); 113 | } 114 | 115 | // Render empty lines below data streams 116 | if lines.len() < max_lines { 117 | let background_color = if streams.len() % 2 == 0 { 118 | theme.stream_even_background_color 119 | } else { 120 | theme.stream_odd_background_color 121 | }; 122 | 123 | let tick = format!("{} {}", Bg(theme.tick_color), Bg(background_color)); 124 | 125 | let empty_line = format!( 126 | "\n\r{}{}{}{}{}", 127 | Bg(background_color), 128 | " ".repeat(first_tick_padding), 129 | format!("{}{}", tick, " ".repeat(interval.tick_spacing - 1)).repeat(full_intervals), 130 | tick, 131 | " ".repeat(1 + value_width), 132 | ); 133 | 134 | string.push_str(&empty_line.repeat(max_lines - lines.len())); 135 | } 136 | } 137 | 138 | Screen::Streams => { 139 | let message = ellipsize("Stream selection is not implemented yet", self.width); 140 | 141 | string.push_str(&format!( 142 | "{}{}{}", 143 | Fg(theme.stream_name_color), 144 | Bg(theme.stream_odd_background_color), 145 | pad_right(message, self.width), 146 | )); 147 | 148 | string.push_str(&format!("\n\r{}", " ".repeat(self.width)).repeat(max(self.height, 2) - 2)); 149 | } 150 | } 151 | 152 | // Render bottom bar 153 | let (left_menu, right_menu) = self.menu(); 154 | let left_menu_string = left_menu.iter().map(|m| m.render(theme)).collect::>().join(" "); 155 | let right_menu_string = right_menu 156 | .iter() 157 | .map(|m| m.render(theme)) 158 | .collect::>() 159 | .join(" "); 160 | 161 | let mut menu_width = printed_width(&left_menu_string) + 2 + printed_width(&right_menu_string) + 1; 162 | 163 | string.push_str(&format!("\n\r{}", left_menu_string)); 164 | if self.screen == Screen::Main { 165 | let interval_string = format_duration( 166 | self.interval().duration, 167 | Fg(theme.bottom_bar_number_color), 168 | Fg(theme.bottom_bar_unit_color), 169 | ); 170 | string.push_str(&format!(" {}", interval_string)); 171 | menu_width += 1 + printed_width(&interval_string); 172 | } 173 | 174 | string.push_str(" "); 175 | if menu_width < self.width { 176 | string.push_str(&" ".repeat(self.width - menu_width)); 177 | } 178 | 179 | string.push_str(&format!("{} {}", right_menu_string, Reset)); 180 | 181 | string 182 | } 183 | 184 | fn name_width(&self) -> usize { 185 | self.active_streams() 186 | .iter() 187 | .map(|s| { 188 | max( 189 | // Any name ... 190 | printed_width(s.stream.name()), 191 | // ... and any value must fit, because the name column 192 | // also displays values (tick labels) for expanded streams 193 | s.stream.format_width(), 194 | ) 195 | }) 196 | .max() 197 | .unwrap_or(0) 198 | } 199 | 200 | fn value_width(&self) -> usize { 201 | max( 202 | // Any value ... 203 | self.active_streams() 204 | .iter() 205 | .map(|s| s.stream.format_width()) 206 | .max() 207 | .unwrap_or(0), 208 | // ... and the stats label must fit 209 | printed_width(STATS_LABEL), 210 | ) 211 | } 212 | } 213 | 214 | impl StreamWrapper { 215 | #[allow(clippy::too_many_arguments)] 216 | fn render( 217 | &self, 218 | index: usize, 219 | selected: bool, 220 | name_width: usize, 221 | graph_width: usize, 222 | value_width: usize, 223 | tick_spacing: usize, 224 | theme: &Theme, 225 | ) -> Vec { 226 | let mut lines = Vec::new(); 227 | 228 | let graph_color = theme.stream_graph_colors[index % theme.stream_graph_colors.len()]; 229 | 230 | let background_color = if selected { 231 | theme.stream_selected_background_color 232 | } else if index % 2 == 0 { 233 | theme.stream_even_background_color 234 | } else { 235 | theme.stream_odd_background_color 236 | }; 237 | 238 | let graph = |values: Vec>, min: f64, max: f64| { 239 | let mut graph = format!("{}{}", Fg(graph_color.0), Bg(background_color)); 240 | 241 | for (i, value) in values.iter().enumerate() { 242 | let symbol = match value { 243 | Some(number) => { 244 | let bar_index = if min < max { 245 | let level = (number - min) / (max - min); 246 | let bucket = (level * (BARS.len() as f64)).ceil() as usize; 247 | if bucket == 0 { 248 | 0 249 | } else { 250 | bucket - 1 251 | } 252 | } else { 253 | 0 254 | }; 255 | BARS[bar_index] 256 | } 257 | None => DOT, 258 | }; 259 | 260 | if ((graph_width - 1) - i) % tick_spacing == 0 { 261 | // Tick intersection 262 | graph.push_str(&format!( 263 | "{}{}{}{}{}", 264 | Fg(graph_color.1), 265 | Bg(theme.tick_color), 266 | symbol, 267 | Fg(graph_color.0), 268 | Bg(background_color), 269 | )); 270 | } else { 271 | graph.push_str(symbol); 272 | } 273 | } 274 | 275 | graph 276 | }; 277 | 278 | let values = (1..=graph_width) 279 | .rev() 280 | .map(|i| { 281 | if i <= self.values.len() { 282 | self.values[self.values.len() - i] 283 | } else { 284 | None 285 | } 286 | }) 287 | .collect::>(); 288 | 289 | let numbers = values.iter().cloned().filter_map(|v| v).collect::>(); 290 | 291 | let numbers_min = numbers.iter().cloned().fold(f64::NAN, f64::min); 292 | let numbers_max = numbers.iter().cloned().fold(f64::NAN, f64::max); 293 | let numbers_avg = numbers.iter().cloned().sum::() / (numbers.len() as f64); 294 | 295 | let min = self.stream.min().unwrap_or(numbers_min); 296 | let max = self.stream.max().unwrap_or(numbers_max); 297 | 298 | let value_string = if numbers.is_empty() { 299 | String::new() 300 | } else { 301 | self.stream.format(numbers[numbers.len() - 1], theme) 302 | }; 303 | 304 | let mut line = format!( 305 | "{}{}", 306 | Fg(if selected { 307 | theme.stream_name_selected_text_color 308 | } else { 309 | theme.stream_name_color 310 | }), 311 | Bg(if selected { 312 | theme.stream_name_selected_background_color 313 | } else { 314 | background_color 315 | }), 316 | ); 317 | 318 | line.push_str(&pad_left(self.stream.name(), name_width)); 319 | line.push_str(&format!("{} ", Bg(background_color))); 320 | 321 | if self.expanded { 322 | line.push_str(&format!( 323 | "{}{} {}", 324 | Fg(theme.stream_description_color), 325 | pad_right(ellipsize(self.stream.description(), graph_width), graph_width), 326 | pad_right(value_string, value_width), 327 | )); 328 | 329 | lines.push(line); 330 | 331 | let mut graph_rows = Vec::new(); 332 | 333 | for i in (0..EXPANDED_GRAPH_HEIGHT).rev() { 334 | let row_height = (max - min) / (EXPANDED_GRAPH_HEIGHT as f64); 335 | let row_min = min + (row_height * (i as f64)); 336 | let row_max = row_min + row_height; 337 | 338 | let row_values = values 339 | .iter() 340 | .map(|v| { 341 | v.and_then(|number| { 342 | if number < row_min { 343 | None 344 | } else if number > row_max { 345 | Some(row_max) 346 | } else { 347 | Some(number) 348 | } 349 | }) 350 | }) 351 | .collect::>(); 352 | 353 | graph_rows.push(graph(row_values, row_min, row_max)); 354 | } 355 | 356 | let (min_string, mid_string, max_string) = if min.is_finite() && max.is_finite() { 357 | ( 358 | self.stream.format(min, theme), 359 | self.stream.format((min + max) / 2.0, theme), 360 | self.stream.format(max, theme), 361 | ) 362 | } else { 363 | (String::new(), String::new(), String::new()) 364 | }; 365 | 366 | let (stats_label, low_string, high_string, avg_string) = 367 | if numbers_min.is_finite() && numbers_max.is_finite() && numbers_avg.is_finite() { 368 | ( 369 | String::from(STATS_LABEL), 370 | self.stream.format(numbers_min, theme), 371 | self.stream.format(numbers_max, theme), 372 | self.stream.format(numbers_avg, theme), 373 | ) 374 | } else { 375 | (String::new(), String::new(), String::new(), String::new()) 376 | }; 377 | 378 | let y_mid = EXPANDED_GRAPH_HEIGHT / 2; 379 | let y_max = EXPANDED_GRAPH_HEIGHT - 1; 380 | 381 | for (y, row) in graph_rows.iter().enumerate() { 382 | let left_axis = if y == 0 { 383 | &max_string 384 | } else if y == y_mid { 385 | &mid_string 386 | } else if y == y_max { 387 | &min_string 388 | } else { 389 | "" 390 | }; 391 | let right_axis = if y == y_max - 3 { 392 | &stats_label 393 | } else if y == y_max - 2 { 394 | &low_string 395 | } else if y == y_max - 1 { 396 | &high_string 397 | } else if y == y_max { 398 | &avg_string 399 | } else { 400 | "" 401 | }; 402 | 403 | lines.push(format!( 404 | "{}{} {} {}{}", 405 | Bg(background_color), 406 | pad_left(left_axis, name_width), 407 | row, 408 | Fg(theme.stream_description_color), 409 | pad_right(right_axis, value_width) 410 | )); 411 | } 412 | } else { 413 | line.push_str(&format!( 414 | "{} {}", 415 | graph(values, min, max), 416 | pad_right(value_string, value_width), 417 | )); 418 | 419 | lines.push(line); 420 | } 421 | 422 | lines 423 | } 424 | 425 | pub fn height(&self) -> usize { 426 | if self.expanded { 427 | 1 + EXPANDED_GRAPH_HEIGHT 428 | } else { 429 | 1 430 | } 431 | } 432 | } 433 | 434 | impl MenuItem { 435 | fn render(&self, theme: &Theme) -> String { 436 | format!( 437 | "{}{}\u{2590}{}{}{}{}{}\u{258C}{}{}", 438 | Fg(theme.bottom_bar_key_background_color), 439 | Bg(theme.bottom_bar_color), 440 | Fg(theme.bottom_bar_key_text_color), 441 | Bg(theme.bottom_bar_key_background_color), 442 | self.keys, 443 | Fg(theme.bottom_bar_key_background_color), 444 | Bg(theme.bottom_bar_color), 445 | Fg(theme.bottom_bar_label_color), 446 | self.label, 447 | ) 448 | } 449 | } 450 | 451 | pub fn format_quantity( 452 | quantity: f64, 453 | unit: impl Display, 454 | use_prefix: bool, 455 | precision: usize, 456 | number_style: impl Display, 457 | unit_style: impl Display, 458 | ) -> String { 459 | assert!(quantity.is_finite()); 460 | 461 | let magnitude = if use_prefix && quantity != 0.0 { 462 | let m = (quantity.abs().log10() / 3.0).floor() as i32; 463 | 464 | if format!("{:.*}", precision, quantity / 10.0_f64.powi(3 * m)).starts_with("1000") { 465 | // Rounding will increase the apparent magnitude 466 | m + 1 467 | } else { 468 | m 469 | } 470 | } else { 471 | 0 472 | }; 473 | 474 | let prefix = if magnitude != 0 { 475 | let prefixes = if magnitude > 0 { 476 | vec!["k", "M", "G", "T", "P", "E"] 477 | } else { 478 | vec!["m", "\u{B5}", "n", "p", "f", "a"] 479 | }; 480 | 481 | let index = (magnitude.abs() - 1) as usize; 482 | 483 | if index < prefixes.len() { 484 | prefixes[index] 485 | } else { 486 | "?" 487 | } 488 | } else { 489 | "" 490 | }; 491 | 492 | let mut number = format!("{:.*}", precision, quantity / 10.0_f64.powi(3 * magnitude)); 493 | 494 | if precision > 0 { 495 | // Remove trailing zeros 496 | let regex = Regex::new(r"\.?0+$").unwrap(); 497 | number = regex.replace(&number, "").into_owned(); 498 | } 499 | 500 | format!("{}{}{}{}{}", number_style, number, unit_style, prefix, unit) 501 | } 502 | 503 | fn format_duration(duration: Duration, number_style: impl Display, unit_style: impl Display) -> String { 504 | let mut milliseconds = duration.as_millis(); 505 | 506 | if milliseconds == 0 { 507 | return format!("{}0{}s", number_style, unit_style); 508 | } 509 | 510 | let mut string = String::new(); 511 | 512 | for (unit, factor) in &[("h", 3_600_000), ("m", 60_000)] { 513 | if milliseconds >= *factor { 514 | string.push_str(&format!( 515 | "{}{}{}{}", 516 | number_style, 517 | milliseconds / factor, 518 | unit_style, 519 | unit 520 | )); 521 | milliseconds %= factor; 522 | } 523 | } 524 | if milliseconds > 0 { 525 | string.push_str(&format!( 526 | "{}{:1}{}s", 527 | number_style, 528 | milliseconds as f64 / 1000.0, 529 | unit_style 530 | )); 531 | } 532 | 533 | string 534 | } 535 | 536 | pub fn printed_width(string: impl AsRef) -> usize { 537 | // Matches ANSI SGR control sequences (text attributes), 538 | // which don't affect the printed width 539 | let regex = Regex::new(r"\x1B\[.*?m").unwrap(); 540 | regex.replace_all(string.as_ref(), "").chars().count() 541 | } 542 | 543 | fn ellipsize(string: impl Into, width: usize) -> String { 544 | assert!(width > 0); 545 | 546 | let s = string.into(); 547 | 548 | if s.chars().count() > width { 549 | let truncated_string: String = s.chars().take(width - 1).collect(); 550 | format!("{}\u{2026}", truncated_string) 551 | } else { 552 | s 553 | } 554 | } 555 | 556 | fn pad_left(string: impl AsRef, width: usize) -> String { 557 | format!( 558 | "{}{}", 559 | " ".repeat(width - printed_width(string.as_ref())), 560 | string.as_ref(), 561 | ) 562 | } 563 | 564 | fn pad_right(string: impl AsRef, width: usize) -> String { 565 | format!( 566 | "{}{}", 567 | string.as_ref(), 568 | " ".repeat(width - printed_width(string.as_ref())), 569 | ) 570 | } 571 | 572 | #[cfg(test)] 573 | mod tests { 574 | use termion::{ 575 | color::{Bg, Fg, Green, Red}, 576 | style::Bold, 577 | }; 578 | 579 | use super::*; 580 | 581 | #[test] 582 | fn test_format_quantity() { 583 | assert_eq!(format_quantity(0.0, "C", true, 0, "A", "B"), "A0BC"); 584 | assert_eq!(format_quantity(0.001, "C", true, 0, "A", "B"), "A1BmC"); 585 | assert_eq!(format_quantity(0.999, "C", true, 0, "A", "B"), "A999BmC"); 586 | assert_eq!(format_quantity(1.0, "C", true, 0, "A", "B"), "A1BC"); 587 | assert_eq!(format_quantity(999.0, "C", true, 0, "A", "B"), "A999BC"); 588 | assert_eq!(format_quantity(1000.0, "C", true, 0, "A", "B"), "A1BkC"); 589 | assert_eq!(format_quantity(0.9999, "C", true, 0, "A", "B"), "A1BC"); 590 | assert_eq!(format_quantity(999.9, "C", true, 0, "A", "B"), "A1BkC"); 591 | assert_eq!(format_quantity(999_900.0, "C", true, 0, "A", "B"), "A1BMC"); 592 | assert_eq!(format_quantity(123_456_789.0, "C", true, 3, "A", "B"), "A123.457BMC"); 593 | assert_eq!(format_quantity(123_456_789.0, "C", false, 3, "A", "B"), "A123456789BC"); 594 | assert_eq!( 595 | format_quantity(-0.000_000_001_234_567_89, "C", true, 3, "A", "B"), 596 | "A-1.235BnC", 597 | ); 598 | assert_eq!( 599 | format_quantity(-0.000_000_001_234_567_89, "C", false, 3, "A", "B"), 600 | "A-0BC", 601 | ); 602 | assert_eq!(format_quantity(10.0_f64.powi(100), "C", true, 0, "A", "B"), "A10B?C"); 603 | assert_eq!(format_quantity(10.0_f64.powi(-100), "C", true, 0, "A", "B"), "A100B?C"); 604 | } 605 | 606 | #[test] 607 | fn test_format_duration() { 608 | assert_eq!(format_duration(Duration::from_secs(0), "A", "B"), "A0Bs"); 609 | assert_eq!(format_duration(Duration::from_secs(1), "A", "B"), "A1Bs"); 610 | assert_eq!(format_duration(Duration::from_secs(60), "A", "B"), "A1Bm"); 611 | assert_eq!(format_duration(Duration::from_secs(61), "A", "B"), "A1BmA1Bs"); 612 | assert_eq!(format_duration(Duration::from_secs(3600), "A", "B"), "A1Bh"); 613 | assert_eq!(format_duration(Duration::from_secs(3660), "A", "B"), "A1BhA1Bm"); 614 | assert_eq!(format_duration(Duration::from_secs(3601), "A", "B"), "A1BhA1Bs"); 615 | assert_eq!(format_duration(Duration::from_secs(3661), "A", "B"), "A1BhA1BmA1Bs"); 616 | assert_eq!( 617 | format_duration(Duration::from_secs(100_000), "A", "B"), 618 | "A27BhA46BmA40Bs", 619 | ); 620 | } 621 | 622 | #[test] 623 | fn test_printed_width() { 624 | assert_eq!(printed_width(""), 0); 625 | assert_eq!(printed_width(" "), 1); 626 | assert_eq!(printed_width("\u{21}\u{2190}\u{1F800}"), 3); 627 | assert_eq!(printed_width(format!("{}{}{}", Fg(Red), Bg(Green), Bold)), 0); 628 | assert_eq!(printed_width(format!("ab{}cd{}ef{}gh", Fg(Red), Bg(Green), Bold)), 8); 629 | assert_eq!( 630 | printed_width(format!("ab\u{21}{}cd\u{2190}{}ef\u{1F800}{}", Fg(Red), Bg(Green), Bold)), 631 | 9, 632 | ); 633 | } 634 | } 635 | --------------------------------------------------------------------------------