Compare commits

...

6 Commits

Author SHA1 Message Date
Joe Bellus 6b1098c863 initial UI framework 2022-01-06 00:46:27 -05:00
Joe Bellus 93195bab1b Merge branch 'v0.1.1' into 'main'
Added App::long_desc(self) which sets the root level description

See merge request arkham/arkham!4
2021-11-14 02:47:55 +00:00
Joe Bellus 445ae2ddfc General imrovements
Added app! macro that can extract package name and version.

Opts can be parsed for the application root prior to launching handling
functions.

Added further integration with the console create

Improved display of description_lists, these now wrap the description
text.

Long and short opts are now optional and one or both can be used.
2021-11-14 02:47:55 +00:00
Joe Bellus 2573ef293a Updated license for Cargo.toml 2021-06-20 21:51:16 -04:00
Joe Bellus 902414f31b Merge branch 'publish' into 'master'
Publish Preperation

See merge request arkham/arkham!5
2021-06-21 01:43:01 +00:00
Joe Bellus bb78209345 Preparing for publishing crate on crates.io.
* Added license file
* Added fields to Cargo.toml
2021-06-21 01:43:00 +00:00
23 changed files with 1136 additions and 232 deletions

246
Cargo.lock generated
View File

@ -3,13 +3,23 @@
version = 3
[[package]]
name = "arkham"
version = "0.1.0"
name = "aho-corasick"
version = "0.7.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f"
dependencies = [
"memchr",
]
[[package]]
name = "arkham"
version = "0.1.1"
dependencies = [
"console",
"criterion",
"crossterm",
"serde",
"serde_json",
"textwrap 0.14.2",
"toml",
]
@ -32,9 +42,9 @@ checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bitflags"
version = "1.2.1"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bstr"
@ -76,25 +86,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002"
dependencies = [
"bitflags",
"textwrap",
"textwrap 0.11.0",
"unicode-width",
]
[[package]]
name = "console"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cc80946b3480f421c2f17ed1cb841753a371c7c5104f51d507e13f532c856aa"
dependencies = [
"encode_unicode",
"lazy_static",
"libc",
"regex",
"terminal_size",
"unicode-width",
"winapi",
]
[[package]]
name = "criterion"
version = "0.3.4"
@ -175,6 +170,32 @@ dependencies = [
"lazy_static",
]
[[package]]
name = "crossterm"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c85525306c4291d1b73ce93c8acf9c339f9b213aef6c1d85c3830cbf1c16325c"
dependencies = [
"bitflags",
"crossterm_winapi",
"futures-core",
"libc",
"mio",
"parking_lot",
"signal-hook",
"signal-hook-mio",
"winapi",
]
[[package]]
name = "crossterm_winapi"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c"
dependencies = [
"winapi",
]
[[package]]
name = "csv"
version = "1.1.6"
@ -204,10 +225,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457"
[[package]]
name = "encode_unicode"
version = "0.3.6"
name = "futures-core"
version = "0.3.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
checksum = "d0c8ff0461b82559810cdccfde3215c3f373807f5e5232b71479bff7bb2583d7"
[[package]]
name = "half"
@ -224,6 +245,15 @@ dependencies = [
"libc",
]
[[package]]
name = "instant"
version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if",
]
[[package]]
name = "itertools"
version = "0.9.0"
@ -265,9 +295,18 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.88"
version = "0.2.112"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "03b07a082330a35e43f63177cc01689da34fbffa0105e1246cf0311472cac73a"
checksum = "1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125"
[[package]]
name = "lock_api"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712a4d093c9976e24e7dbca41db895dabcbac38eb5f4045393d17a95bdfb1109"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
@ -293,6 +332,37 @@ dependencies = [
"autocfg",
]
[[package]]
name = "mio"
version = "0.7.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8067b404fe97c70829f082dec8bcf4f71225d7eaea1d8645349cb76fa06205cc"
dependencies = [
"libc",
"log",
"miow",
"ntapi",
"winapi",
]
[[package]]
name = "miow"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9f1c5b025cda876f66ef43a113f91ebc9f4ccef34843000e0adf6ebbab84e21"
dependencies = [
"winapi",
]
[[package]]
name = "ntapi"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f6bb902e437b6d86e03cce10a7e2af662292c5dfef23b65899ea3ac9354ad44"
dependencies = [
"winapi",
]
[[package]]
name = "num-traits"
version = "0.2.14"
@ -312,12 +382,43 @@ dependencies = [
"libc",
]
[[package]]
name = "once_cell"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56"
[[package]]
name = "oorandom"
version = "11.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
[[package]]
name = "parking_lot"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
dependencies = [
"instant",
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216"
dependencies = [
"cfg-if",
"instant",
"libc",
"redox_syscall",
"smallvec",
"winapi",
]
[[package]]
name = "pest"
version = "2.1.3"
@ -398,13 +499,25 @@ dependencies = [
"num_cpus",
]
[[package]]
name = "redox_syscall"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8383f39639269cde97d255a32bdb68c047337295414940c68bdd30c2e13203ff"
dependencies = [
"bitflags",
]
[[package]]
name = "regex"
version = "1.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9251239e129e16308e70d853559389de218ac275b515068abc96829d05b948a"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
"thread_local",
]
[[package]]
@ -508,6 +621,48 @@ dependencies = [
"serde",
]
[[package]]
name = "signal-hook"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "647c97df271007dcea485bb74ffdb57f2e683f1306c854f468a0c244badabf2d"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-mio"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fd5867f1c4f2c5be079aee7a2adf1152ebb04a4bc4d341f504b7dece607ed4"
dependencies = [
"libc",
"mio",
"signal-hook",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"
dependencies = [
"libc",
]
[[package]]
name = "smallvec"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ecab6c735a6bb4139c0caafd0cc3635748bbb3acf4550e8138122099251f309"
[[package]]
name = "smawk"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f67ad224767faa3c7d8b6d91985b78e70a1324408abcb1cfcc2be4c06bc06043"
[[package]]
name = "syn"
version = "1.0.73"
@ -519,16 +674,6 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "terminal_size"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86ca8ced750734db02076f44132d802af0b33b09942331f4459dde8636fd2406"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "textwrap"
version = "0.11.0"
@ -538,6 +683,26 @@ dependencies = [
"unicode-width",
]
[[package]]
name = "textwrap"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0066c8d12af8b5acd21e00547c3797fde4e8677254a7ee429176ccebbe93dd80"
dependencies = [
"smawk",
"unicode-linebreak",
"unicode-width",
]
[[package]]
name = "thread_local"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8018d24e04c95ac8790716a5987d0fec4f8b27249ffa0f7d33f1369bdfb88cbd"
dependencies = [
"once_cell",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
@ -563,6 +728,15 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56dee185309b50d1f11bfedef0fe6d036842e3fb77413abef29f8f8d1c5d4c1c"
[[package]]
name = "unicode-linebreak"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a52dcaab0c48d931f7cc8ef826fa51690a08e1ea55117ef26f89864f532383f"
dependencies = [
"regex",
]
[[package]]
name = "unicode-width"
version = "0.1.8"

View File

@ -1,22 +1,32 @@
[package]
name = "arkham"
version = "0.1.0"
version = "0.1.1"
authors = ["Joe Bellus <joe@5sigma.io>"]
edition = "2018"
description = "A framework for CLI applications"
repository = "https://git.5sigma.io/arkham/arkham"
readme = "README.md"
license = "Apache-2.0"
keywords = ["CLI", "arguments", "config"]
categories = ["command-line-interface", "config"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
# indicatif = "0.15.0"
console = "0.14.0"
serde = { version = "1.0", features = ["derive"], optional = true }
serde_json = { version = "1.0", optional = true}
toml = { version="0.5.8", optional = true}
textwrap = "0.14.2"
crossterm = { version = "0.22.1", features=["event-stream"]}
[features]
config = ["serde"]
config = ["serialize"]
config_toml = ["toml", "config"]
config_json = ["serde_json", "config"]
serialize = ["serde"]
[dev-dependencies]
criterion = "0.3"
@ -25,3 +35,7 @@ criterion = "0.3"
name = "arg_parsing"
harness = false
[[bench]]
name = "space_fill"
harness = false

202
LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2021 Arkham CLI Tools
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -12,6 +12,13 @@ building blocks for building attractive and smooth CLIs
* Automatic usage details for subcommands and bare execution
* Flags and options can be set via environment variables
## Configuration Handling
Configurations can be loaded from either TOML or JSON files. Configuration files
can be used to automatically provide values for command line opts or arbitrary
configuration values
## Styling
* Canned helper methods for generating colored and formatted outputs for common
@ -20,4 +27,5 @@ structures: Detail lists, headers, etc.
# Basic Usage
* [fib](https://git.5sigma.io/arkham/arkham/-/blob/master/examples/fib.rs) - An example using subcommands and command line options
* [config](https://git.5sigma.io/arkham/arkham/-/blob/master/examples/config.rs) - An example loading a configuration file. This must be ran with `cargo run --example config --features toml_config`

54
benches/space_fill.rs Normal file
View File

@ -0,0 +1,54 @@
use arkham::ui;
use criterion::{criterion_group, criterion_main, Criterion};
fn space_fill(c: &mut Criterion) {
c.bench_function("large_space_fill", |b| {
let mut space = ui::View::new(200, 200);
space.fill(
ui::Rect::new(50, 50, 100, 100),
*ui::Cell::default()
.fg(ui::Color::White)
.bg(ui::Color::Green),
);
b.iter(|| {
let mut output: Vec<u8> = vec![];
space
.render(ui::Pos::new(0, 0), &mut output)
.expect("couldnt render");
})
});
c.bench_function("small_space_fill", |b| {
let mut space = ui::View::new(20, 20);
space.fill(
ui::Rect::new(0, 0, 20, 20),
*ui::Cell::default()
.fg(ui::Color::White)
.bg(ui::Color::Green),
);
b.iter(|| {
let mut output: Vec<u8> = vec![];
space
.render(ui::Pos::new(0, 0), &mut output)
.expect("couldnt render");
})
});
c.bench_function("fill_all", |b| {
let mut space = ui::View::new(200, 200);
space.fill_all(
*ui::Cell::default()
.fg(ui::Color::White)
.bg(ui::Color::Green),
);
b.iter(|| {
let mut output: Vec<u8> = vec![];
space
.render(ui::Pos::new(0, 0), &mut output)
.expect("couldnt render");
})
});
}
criterion_group!(benches, space_fill);
criterion_main!(benches);

29
examples/component.rs Normal file
View File

@ -0,0 +1,29 @@
use arkham::{
ui::{Cell, Color, Component, Rect, UI},
Result,
};
pub struct OuterComponent;
impl Component for OuterComponent {
fn view(&mut self, ctx: &mut arkham::ui::Context) -> Result<()> {
ctx.view
.fill_all(*Cell::default().content(' ').bg(Color::Red));
ctx.add_component(Rect::new(20, 20, 40, 40), &mut InnerComponent)?;
Ok(())
}
}
pub struct InnerComponent;
impl Component for InnerComponent {
fn view(&mut self, ctx: &mut arkham::ui::Context) -> Result<()> {
ctx.view
.fill_all(*Cell::default().content(' ').bg(Color::Green));
Ok(())
}
}
fn main() {
UI::new(OuterComponent).run().expect("Couldnt run UI loop");
}

View File

@ -4,6 +4,7 @@ fn main() {
let _ = App::new()
.name("Fibonacci App")
.version("1.0")
.long_desc("This app can be used to calculate fibonacci numbers")
.command(
Command::new("fib")
.opt(
@ -22,7 +23,7 @@ fn main() {
fn fibonacci_handler(_app: &App, ctx: &Context, _args: &[String]) {
let v = fibonacci(
ctx.get_string("count")
.unwrap_or("1".to_string())
.unwrap_or_else(|| "1".to_string())
.parse()
.unwrap_or(1),
);

View File

@ -1,8 +0,0 @@
// use arkham::TaskGroup;
fn main() {
// let tasks = TaskGroup::new();
// let task = tasks.start_task("task 1");
// task.tick();
// tasks.join();
}

View File

@ -1,9 +1,12 @@
use crate::{
context::Context,
use std::fmt::Debug;
use super::{
opt::{self, Opt},
vox, App,
App, Context,
};
use super::helpers;
pub type Handler = fn(&App, &Context, &[String]);
#[derive(Clone)]
@ -16,6 +19,12 @@ pub struct Command {
pub short_desc: Option<String>,
}
impl Debug for Command {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Command").field("name", &self.name).finish()
}
}
impl Command {
pub fn new<T: Into<String>>(name: T) -> Self {
Command {
@ -50,7 +59,7 @@ impl Command {
}
pub(crate) fn help(app: &App, _ctx: &Context, args: &[String]) {
vox::print(app.application_header());
helpers::print(app.application_header());
print_command_help(&app.root, args);
}
@ -60,17 +69,17 @@ pub(crate) fn print_command_help(cmd: &Command, args: &[String]) {
return print_command_help(cmd, &args[1..]);
}
}
vox::print("");
if let Some(desc) = cmd.long_desc.as_ref().or(cmd.short_desc.as_ref()) {
helpers::print("");
if let Some(desc) = cmd.long_desc.as_ref().or_else(|| cmd.short_desc.as_ref()) {
if cmd.name != "root" {
vox::header(&cmd.name.to_uppercase());
helpers::header(&cmd.name.to_uppercase());
}
vox::print(desc);
vox::print("");
helpers::print(desc);
helpers::print("");
}
if !cmd.opts.is_empty() {
vox::header("OPTIONS");
vox::description_list(
helpers::header("OPTIONS");
helpers::description_list(
cmd.opts
.iter()
.map(|o| (o.usage(), o.desc.clone().unwrap_or_default()))
@ -79,12 +88,13 @@ pub(crate) fn print_command_help(cmd: &Command, args: &[String]) {
}
if !cmd.commands.is_empty() {
vox::header("Subcommands");
vox::description_list(
helpers::header("Commands");
helpers::description_list(
cmd.commands
.iter()
.map(|c| (c.name.clone(), c.short_desc.clone().unwrap_or_default()))
.collect(),
)
}
std::process::exit(1);
}

View File

@ -1,7 +1,9 @@
use crate::{Command, Opt};
use std::{collections::BTreeMap, env};
#[derive(Clone, Debug)]
use super::command::print_command_help;
#[derive(Clone, Debug, Default)]
pub struct Map(BTreeMap<String, ContextValue>);
impl Map {
@ -102,9 +104,9 @@ impl ContextValue {
pub fn parse_string(value: String, kind: ValueKind) -> Option<Self> {
match kind {
ValueKind::String => Some(Self::String(value)),
ValueKind::Integer => value.parse::<i64>().ok().map(|v| Self::Integer(v)),
ValueKind::Float => value.parse::<f64>().ok().map(|v| Self::Float(v)),
ValueKind::Bool => value.parse::<bool>().ok().map(|v| Self::Bool(v)),
ValueKind::Integer => value.parse::<i64>().ok().map(Self::Integer),
ValueKind::Float => value.parse::<f64>().ok().map(Self::Float),
ValueKind::Bool => value.parse::<bool>().ok().map(Self::Bool),
ValueKind::Array => None,
ValueKind::Map => None,
}
@ -136,7 +138,7 @@ impl From<bool> for ContextValue {
}
pub struct Context {
pub(crate) cmd: Command,
pub cmd: Command,
pub(crate) config_data: Map,
pub(crate) env_prefix: Option<String>,
pub(crate) env_enabled: bool,
@ -166,14 +168,14 @@ impl Context {
}
fn get_env_value(&self, name: &str) -> Option<String> {
if self.env_enabled == false {
if !self.env_enabled {
return None;
}
let name = self
.env_prefix
.as_ref()
.map(|pre| format!("{}_{}", pre, name))
.unwrap_or(name.to_string());
.unwrap_or_else(|| name.to_string());
env::var(name).ok()
}
@ -182,7 +184,7 @@ impl Context {
self.config_data
.get(name)
.cloned()
.or(self.get_env_value(name).map(|v| ContextValue::String(v)))
.or_else(|| self.get_env_value(name).map(ContextValue::String))
}
/// Returns a string for the field if it is a string
@ -240,7 +242,7 @@ impl Context {
/// Can be used to display the automatic help message for the current command.
pub fn display_help(&self) {
crate::command::print_command_help(&self.cmd, &vec![])
print_command_help(&self.cmd, &[])
}
pub(crate) fn load_config_file(&mut self, filename: &str) {
@ -340,7 +342,7 @@ mod tests {
App::new()
.opt(Opt::flag("thing").short("-t").long("--t"))
.handler(|_, ctx, _| {
assert_eq!(ctx.flag("thing"), true);
assert!(ctx.flag("thing"));
})
.run_with(vec![])
.unwrap();

77
src/app/helpers.rs Normal file
View File

@ -0,0 +1,77 @@
use crossterm::style::{self, style, Stylize};
use std::collections::HashMap;
use std::fmt::Display;
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy)]
pub enum Color {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
}
impl From<Color> for style::Color {
fn from(fr: Color) -> Self {
match fr {
Color::Black => Self::Black,
Color::Red => Self::Red,
Color::Green => Self::Green,
Color::Yellow => Self::Yellow,
Color::Blue => Self::Blue,
Color::Magenta => Self::Magenta,
Color::Cyan => Self::Cyan,
Color::White => Self::White,
}
}
}
pub fn print<T: Display>(s: T) {
println!("{}", s);
}
pub fn header<T: Display>(str: T) {
println!(
"{} {} {}",
"-=[".red().dim(),
style::style(str).white().bold(),
"]=-".red().dim()
);
}
pub fn description_list(list: HashMap<String, String>) {
let mut lines = list.into_iter().collect::<Vec<(String, String)>>();
let key_max_length = lines.iter().map(|(v, _)| v.len()).max().unwrap_or(10) + 3;
let desc_max_length = 80 - key_max_length;
let indent_string = " ".repeat(key_max_length);
lines.sort_by(|(a, _), (b, _)| a.cmp(b));
let output = lines.iter().fold(String::new(), |output, (name, desc)| {
let spaced_key = format!("{:width$}", name, width = key_max_length);
let mut desc_lines: Vec<String> = textwrap::fill(desc, desc_max_length)
.split('\n')
.map(|s| s.to_string())
.collect();
desc_lines.reverse();
let first_line = desc_lines.pop().unwrap_or_else(String::new);
desc_lines.reverse();
output
+ &format!("{}{}", style(spaced_key).bold(), style(first_line).dim())
+ "\n"
+ &desc_lines
.iter()
.map(|s| indent_string.clone() + s + "\n")
.collect::<String>()
});
println!("{}", output);
}
pub fn error<T: Display>(s: T) {
println!("{}", style(s).red().bold());
}
#[cfg(test)]
mod tests {}

View File

@ -1,11 +1,17 @@
use crate::print_command_help;
mod command;
mod context;
mod helpers;
mod opt;
use super::command::{help, Command, Handler};
use super::context::Context;
use super::opt::{Opt, OptError, OptKind};
use command::help;
pub use command::{Command, Handler};
pub use context::Context;
pub use opt::{Opt, OptError, OptKind};
use std::env;
use command::print_command_help;
type Result<T> = std::result::Result<T, OptError>;
pub struct App {
@ -110,6 +116,29 @@ impl App {
self
}
/// Similar to `App::Command` but allows multiple commands to be added at once.
/// Adds a root level commands to the application. This command can then be executed with:
///
/// myapp command_name
///
/// Help flags will also be generated for the command which will display command
/// information for:
///
/// myapp --help command_name or myapp help command_name
///
/// Example:
/// ```rust
/// use arkham::{App, Command, Context};
/// let names = vec!["one", "two", "three"];
/// let commands = names.into_iter().map(|name| Command::new(name).handler(my_handler)).collect();
/// App::new().commands(commands);
///
/// fn my_handler(app: &App, ctx: &Context, args: &[String]) {}
/// ```
pub fn commands(self, commands: Vec<Command>) -> Self {
commands.into_iter().fold(self, |app, cmd| app.command(cmd))
}
/// Adds a root level opt/flag that is available to all commands. Opts are given a name which
/// is used to reference them, as well as a short and long identifier.
///
@ -140,9 +169,19 @@ impl App {
self
}
/// Execute the app and any specified handlers based on the passed arguemnts. This function is
/// mostly used for testing or any situation where you need to pass arbitrary arguments instead
/// of using the ones passed to the application.
/// Sets the longe description for the bare app. This will be displayed in the help content
/// when no additional subcommands are given.
/// Example:
/// ```rust
/// use arkham::{App, Command, Context};
/// App::new().long_desc("This app does all the things");
/// ```
pub fn long_desc(mut self, desc: &str) -> Self {
self.root.long_desc = Some(desc.to_string());
self
}
/// Execute the app and any specified handlers based on the passed arguemnts. This function is mostly used for testing or any situation where you need to pass arbitrary arguments instead of using the ones passed to the application.
/// Example:
/// ```rust
/// use arkham::{App, Command, Context, Opt};
@ -160,11 +199,19 @@ impl App {
if let Some(filename) = self.config_filename {
ctx.load_config_file(filename);
}
run_command(self, &self.root, &args, &mut ctx)
if let Err(e) = run_command(self, &self.root, &args, &mut ctx) {
match e {
OptError::InvalidOpt(opt) => {
helpers::error(format!("Invalid options {}", &opt));
Err(OptError::InvalidOpt(opt))
}
}
} else {
Ok(())
}
}
/// Execute the app and any specified handlers based on the arguments passsed to the
/// application.
/// Execute the app and any specified handlers based on the arguments passsed to the application.
///
/// Example:
/// running with myapp --name alice
@ -182,11 +229,17 @@ impl App {
pub fn run(&mut self) -> Result<()> {
self.run_with(env::args().skip(1).collect())
}
/// Generates a context for the root command allowing flags to be parsed. This can be useful to predetect certian root level arguments before processing sub commands and other app configurations.
pub fn root_context(&self) -> Result<Context> {
let mut ctx = Context::new(self.root.clone());
let args = env::args().skip(1).collect::<Vec<_>>();
populate_args(&mut ctx, &self.root, &args)?;
Ok(ctx)
}
}
/// This is the core logic for parsing arguments and executing handlers. It is ran but the App::run
/// and App::run_with functions.
fn run_command(app: &App, cmd: &Command, args: &[String], ctx: &mut Context) -> Result<()> {
fn populate_args(ctx: &mut Context, cmd: &Command, args: &[String]) -> Result<Vec<String>> {
// Get an iterator for the incomming arguments
let mut args = args.iter();
// We will keep track of any arguments that arent consumed by the current command.
@ -197,7 +250,11 @@ fn run_command(app: &App, cmd: &Command, args: &[String], ctx: &mut Context) ->
while let Some(arg) = args.next() {
// Check for long args
if arg.starts_with("--") {
if let Some(opt) = cmd.opts.iter().find(|o| &o.long == &arg[2..]) {
if let Some(opt) = cmd
.opts
.iter()
.find(|o| o.long == Some(arg[2..].to_string()))
{
match opt.kind {
OptKind::Flag => {
ctx.set_flag(opt);
@ -216,8 +273,13 @@ fn run_command(app: &App, cmd: &Command, args: &[String], ctx: &mut Context) ->
continue;
}
// Check for short args
if arg.starts_with("-") {
if let Some(opt) = cmd.opts.iter().find(|o| &o.short == &arg[1..]) {
if arg.starts_with('-') {
for switch in arg.chars().skip(1) {
if let Some(opt) = cmd
.opts
.iter()
.find(|o| o.short == Some(switch.to_string()))
{
match opt.kind {
OptKind::Flag => {
ctx.set_flag(opt);
@ -233,11 +295,20 @@ fn run_command(app: &App, cmd: &Command, args: &[String], ctx: &mut Context) ->
} else {
ignored.push(arg.clone());
}
}
continue;
}
ignored.push(arg.clone());
}
Ok(ignored)
}
/// This is the core logic for parsing arguments and executing handlers. It is ran but the App::run
/// and App::run_with functions.
fn run_command(app: &App, cmd: &Command, args: &[String], ctx: &mut Context) -> Result<()> {
let mut ignored = populate_args(ctx, cmd, args)?;
// Find an recurse into sub commands if the remaining argumetns match any subcommand name
if let Some(cmd) = cmd
.commands
@ -250,12 +321,12 @@ fn run_command(app: &App, cmd: &Command, args: &[String], ctx: &mut Context) ->
// Automatic command help display
if ignored.iter().any(|a| a == "-h" || a == "--help") {
super::command::print_command_help(cmd, &vec![]);
print_command_help(cmd, &[]);
return Ok(());
}
// If any ignored parameters start with "-" we will throw an unknwon flag error.
if let Some(arg) = ignored.iter().find(|a| a.starts_with("-")) {
if let Some(arg) = ignored.iter().find(|a| a.starts_with('-')) {
return Err(OptError::InvalidOpt(arg.clone()));
}
@ -265,10 +336,10 @@ fn run_command(app: &App, cmd: &Command, args: &[String], ctx: &mut Context) ->
if let Some(prefix) = app.env_prefix {
ctx.env_prefix = Some(prefix.to_string());
}
handler(app, &ctx, &ignored);
handler(app, ctx, &ignored);
} else {
crate::vox::print(app.application_header());
print_command_help(cmd, &vec![])
helpers::print(app.application_header());
print_command_help(cmd, &[])
}
Ok(())
@ -328,15 +399,6 @@ mod tests {
.unwrap();
}
fn function_handler(_app: &App, _ctx: &Context, _args: &[String]) {
assert!(true);
}
#[test]
fn test_function_handler() {
App::new().handler(function_handler);
}
#[test]
fn test_extra_args() {
let args = vec!["somefile".to_string()];
@ -354,12 +416,27 @@ mod tests {
App::new()
.opt(Opt::flag("verbose").short("v").long("verbose"))
.handler(|_, ctx, _| {
assert_eq!(ctx.flag("verbose"), true);
assert!(ctx.flag("verbose"));
})
.run_with(vec!["-v".into()])
.unwrap();
}
#[test]
fn test_combined_short_flags() {
App::new()
.opt(Opt::flag("thingA").short("a").long("a"))
.opt(Opt::flag("thingB").short("b").long("b"))
.opt(Opt::flag("thingC").short("c").long("c"))
.handler(|_, ctx, _| {
assert!(ctx.flag("thingA"));
assert!(ctx.flag("thingB"));
assert!(ctx.flag("thingC"));
})
.run_with(vec!["-abc".into()])
.unwrap();
}
#[test]
fn test_invalid_long_flag() {
let r = App::new()
@ -383,7 +460,7 @@ mod tests {
.env_prefix("ARKHAM")
.opt(Opt::flag("thing").short("-t").long("--t"))
.handler(|_, ctx, _| {
assert_eq!(ctx.flag("thing"), true);
assert!(ctx.flag("thing"));
})
.run_with(vec![])
.unwrap();

View File

@ -6,8 +6,8 @@ pub enum OptError {
#[derive(Clone, Debug)]
pub struct Opt {
pub name: String,
pub short: String,
pub long: String,
pub short: Option<String>,
pub long: Option<String>,
pub desc: Option<String>,
pub(crate) kind: OptKind,
}
@ -23,8 +23,8 @@ impl Opt {
pub fn flag(name: &str) -> Self {
Self {
name: name.into(),
short: "".into(),
long: "".into(),
short: None,
long: None,
kind: OptKind::Flag,
desc: None,
}
@ -40,8 +40,8 @@ impl Opt {
pub fn scalar(name: &str) -> Self {
Self {
name: name.into(),
short: "".into(),
long: "".into(),
short: None,
long: None,
kind: OptKind::String,
desc: None,
}
@ -55,7 +55,7 @@ impl Opt {
/// App::new().opt(Opt::scalar("user").short("u").long("user"));
///```
pub fn short(mut self, short: &str) -> Self {
self.short = short.into();
self.short = Some(short.into());
self
}
@ -67,7 +67,7 @@ impl Opt {
/// App::new().opt(Opt::scalar("user").short("u").long("user"));
///```
pub fn long(mut self, long: &str) -> Self {
self.long = long.into();
self.long = Some(long.into());
self
}
@ -92,17 +92,39 @@ impl Opt {
pub(crate) fn usage(&self) -> String {
match self.kind {
OptKind::Flag => {
format!("-{}, --{}", self.short, self.long)
let short = self
.short
.as_ref()
.map(|s| format!("-{}", s))
.unwrap_or_else(String::new);
let long = self
.long
.as_ref()
.map(|s| format!("--{}", s))
.unwrap_or_else(String::new);
vec![short, long].join(",").trim_matches(',').to_string()
}
OptKind::String => {
format!("-{} [value], --{} [value]", self.short, self.long)
let short = self
.short
.as_ref()
.map(|s| format!("-{} [value]", s))
.unwrap_or_else(String::new);
let long = self
.long
.as_ref()
.map(|s| format!("--{} [value]", s))
.unwrap_or_else(String::new);
vec![short, long].join(",").trim_matches(',').to_string()
}
}
}
}
#[derive(Clone, Debug)]
pub(crate) enum OptKind {
pub enum OptKind {
Flag,
String,
}

View File

@ -1,9 +1,36 @@
#[macro_use]
mod macros;
mod app;
mod command;
mod context;
mod opt;
pub mod vox;
pub mod ui;
use std::error::Error;
use std::fmt::{Debug, Display};
pub use app::*;
pub use command::*;
pub use context::*;
pub use opt::*;
pub use app::{App, Command, Opt};
pub type Result<T> = std::result::Result<T, ArkhamError>;
#[derive(Debug)]
pub enum ArkhamError {
IO(String),
Other(String),
}
impl Error for ArkhamError {}
impl Display for ArkhamError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Other(v) => f.write_str(v),
Self::IO(v) => f.write_str(v),
}
}
}
impl From<std::io::Error> for ArkhamError {
fn from(fr: std::io::Error) -> Self {
Self::IO(fr.to_string())
}
}

8
src/macros.rs Normal file
View File

@ -0,0 +1,8 @@
#[macro_export]
macro_rules! app {
() => {
App::default()
.version(env!("CARGO_PKG_VERSION"))
.name(env!("CARGO_PKG_NAME"))
};
}

View File

@ -1,64 +0,0 @@
use indicatif::{HumanDuration, MultiProgress, ProgressBar, ProgressStyle};
use std::{
sync::{Arc, Mutex},
time::Instant,
};
#[derive(Clone)]
pub struct TaskGroup {
mp: Arc<MultiProgress>,
}
impl TaskGroup {
pub fn new() -> Self {
Self {
mp: Arc::new(MultiProgress::new()),
}
}
pub fn start_task(&self, desc: &str) -> Task {
let pb = self.mp.add(ProgressBar::new(1));
let spinner_style = ProgressStyle::default_spinner()
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ")
.template("{prefix:.bold.dim} {spinner} {wide_msg}");
pb.set_style(spinner_style);
Task::new(TaskState {
pb,
desc: desc.into(),
started_at: Instant::now(),
})
}
pub fn join(&self) {
self.mp.join().unwrap();
}
}
#[derive(Clone)]
pub struct Task(Arc<Mutex<TaskState>>);
impl Task {
pub fn new(state: TaskState) -> Self {
Self(Arc::new(Mutex::new(state)))
}
pub fn tick(&self) {
let state = self.0.lock().unwrap();
state.pb.set_message(&format!(
"{} [{}]",
state.desc,
style(HumanDuration(state.started_at.elapsed())).yellow()
));
state.pb.tick();
}
pub fn complete(&self) {
self.0.lock().unwrap().pb.finish_with_message("OK");
}
}
pub struct TaskState {
pb: ProgressBar,
desc: String,
started_at: Instant,
}

93
src/ui/cell.rs Normal file
View File

@ -0,0 +1,93 @@
use crossterm::queue;
use crossterm::style::{
Attribute, Attributes, SetAttributes, SetBackgroundColor, SetForegroundColor,
};
use crossterm::style::{Color, Print};
use std::io::Write;
use crate::Result;
#[derive(Clone, Debug, Copy, PartialEq)]
pub struct Cell {
empty: bool,
fg: Color,
bg: Color,
content: char,
attributes: Attributes,
}
impl Default for Cell {
fn default() -> Self {
Self {
empty: true,
fg: Color::Reset,
bg: Color::Reset,
content: ' ',
attributes: Attributes::default(),
}
}
}
impl Cell {
pub fn new() -> Self {
Self::default()
}
pub fn content(&mut self, v: char) -> &mut Cell {
self.empty = false;
self.content = v;
self
}
pub fn fg(&mut self, color: Color) -> &mut Cell {
self.fg = color;
self
}
pub fn bg(&mut self, color: Color) -> &mut Cell {
self.bg = color;
self
}
pub fn bold(&mut self, v: bool) -> &mut Cell {
if v {
self.attributes.set(Attribute::Bold);
} else {
self.attributes.unset(Attribute::Bold);
}
self
}
pub fn render(&self, output: &mut impl Write) -> Result<()> {
if !self.empty {
queue!(output, SetForegroundColor(self.fg))?;
queue!(output, SetBackgroundColor(self.bg))?;
queue!(output, SetAttributes(self.attributes))?;
queue!(output, Print(&self.content))?;
}
Ok(())
}
pub fn raw(&self) -> Vec<u8> {
let mut output: Vec<u8> = vec![];
self.render(&mut output).expect("Render error");
output
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cell_render() {
let mut cell = Cell::default();
cell.fg(Color::Red);
cell.bg(Color::White);
cell.content = 'T';
cell.bold(true);
let mut output: Vec<u8> = vec![];
cell.render(&mut output).expect("Render error");
let out_str = String::from_utf8(output).expect("Couldnt unwrap to utf8");
assert_eq!(out_str, "\u{1b}[38;5;9m\u{1b}[48;5;15m\u{1b}[1mT");
}
}

7
src/ui/component.rs Normal file
View File

@ -0,0 +1,7 @@
use crate::Result;
use super::Context;
pub trait Component {
fn view(&mut self, _ctx: &mut Context) -> Result<()>;
}

34
src/ui/context.rs Normal file
View File

@ -0,0 +1,34 @@
use crossterm::event::Event;
use super::{Component, Rect, View};
use crate::Result;
pub struct Context {
pub view: View,
pub event: Option<Event>,
}
impl Default for Context {
fn default() -> Self {
Context {
view: View::fullscreen(),
event: None,
}
}
}
impl Context {
pub fn new(width: u16, height: u16, event: Option<Event>) -> Self {
Context {
view: View::new(width, height),
event,
}
}
pub fn add_component(&mut self, rect: Rect, cmp: &mut impl Component) -> Result<()> {
let mut ctx = Context::new(rect.width, rect.height, self.event);
cmp.view(&mut ctx)?;
self.view.merge(rect.pos, ctx.view);
Ok(())
}
}

51
src/ui/geometry.rs Normal file
View File

@ -0,0 +1,51 @@
use std::ops::{Add, Sub};
pub struct Rect {
pub pos: Pos,
pub width: u16,
pub height: u16,
}
impl Rect {
pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
Rect {
pos: Pos::new(x, y),
width,
height,
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct Pos(u16, u16);
impl Pos {
pub fn new(x: u16, y: u16) -> Self {
Pos(x, y)
}
pub fn x(&self) -> u16 {
self.0
}
pub fn y(&self) -> u16 {
self.1
}
}
impl Add for Pos {
type Output = Pos;
fn add(self, rhs: Self) -> Self::Output {
Pos(self.x() + rhs.x(), self.y() + rhs.y())
}
}
impl Sub for Pos {
type Output = Pos;
fn sub(self, rhs: Self) -> Self::Output {
Pos(
(self.x() as i32 - rhs.x() as i32).max(0) as u16,
(self.y() as i32 - rhs.y() as i32).max(0) as u16,
)
}
}

44
src/ui/mod.rs Normal file
View File

@ -0,0 +1,44 @@
mod cell;
mod component;
mod context;
mod geometry;
mod view;
pub use cell::Cell;
pub use component::Component;
pub use context::Context;
pub use crossterm::style::{Color, Stylize};
use crossterm::terminal::enable_raw_mode;
pub use geometry::{Pos, Rect};
pub use std::io::Write;
pub use view::View;
use crate::Result;
pub struct UI {
root: Box<dyn Component>,
}
impl UI {
pub fn new<C: Component + 'static>(root: C) -> Self {
Self {
root: Box::new(root),
}
}
pub fn run(&mut self) -> Result<()> {
let mut output = std::io::stdout();
let mut context = Context::default();
loop {
// enable_raw_mode();
self.root.view(&mut context)?;
context.view.render(Pos::new(0, 0), &mut output)?;
output.flush().expect("Couldnt flush output");
let event = crossterm::event::read()?;
context.event = Some(event);
self.root.view(&mut context)?;
context.view.render(Pos::new(0, 0), &mut output)?;
output.flush().expect("Couldnt flush output");
}
}
}

77
src/ui/view.rs Normal file
View File

@ -0,0 +1,77 @@
use super::Rect;
use std::io::Write;
use crossterm::{
cursor::{MoveDown, MoveTo, MoveToColumn},
queue, terminal,
};
use crate::Result;
use super::{Cell, Pos};
pub struct View {
cells: Vec<Cell>,
width: u16,
#[allow(dead_code)]
height: u16,
}
impl View {
pub fn new(width: u16, height: u16) -> Self {
Self {
width,
height,
cells: vec![Cell::default(); (width * height) as usize],
}
}
pub fn fullscreen() -> Self {
let (width, height) = terminal::size().expect("Couldnt detect terminal size");
Self {
width,
height,
cells: vec![Cell::default(); (width * height) as usize],
}
}
pub fn get(&self, pos: Pos) -> Option<&Cell> {
self.cells.get((pos.y() * self.width + pos.x()) as usize)
}
pub fn set(&mut self, pos: Pos, cell: Cell) {
self.cells[(pos.y() * self.width + pos.x()) as usize] = cell;
}
pub fn fill(&mut self, rect: Rect, cell: Cell) {
for y in rect.pos.y()..rect.pos.y() + rect.height {
for x in rect.pos.x()..rect.pos.x() + rect.width {
self.set(Pos::new(x, y), cell);
}
}
}
pub fn fill_all(&mut self, cell: Cell) {
self.cells.fill(cell);
}
pub fn merge(&mut self, pos: Pos, view: View) {
for (idx, line) in view.cells.chunks(view.width as usize).enumerate() {
let start = ((pos.y() + idx as u16) * self.width + pos.x()) as usize;
let end = start + line.len();
self.cells.splice(start..end, line.iter().cloned());
}
}
pub fn render(&mut self, pos: Pos, output: &mut impl Write) -> Result<()> {
queue!(output, MoveTo(pos.x(), pos.y()))?;
for line in self.cells.chunks(self.width as usize) {
for cell in line {
cell.render(output)?;
}
queue!(output, MoveDown(1))?;
queue!(output, MoveToColumn(pos.x()))?;
}
Ok(())
}
}

View File

@ -1,35 +0,0 @@
use console::style;
use std::collections::HashMap;
use std::fmt::Display;
pub fn message<T: Display>(str: T) {
println!("{}", style(str).white().bold());
}
pub fn header<T: Display>(str: T) {
println!(
"{} {} {}",
style("-=[").red().dim(),
style(str).white().bold(),
style("]=-").red().dim()
);
}
pub fn note<T: Display>(str: T) {
println!("{}", style(str).white().dim());
}
pub fn description_list(list: HashMap<String, String>) {
let max_length = list.keys().map(|v| v.len()).max().unwrap_or(10) + 3;
for (name, desc) in list {
let spaced_name = format!("{:width$}", name, width = max_length);
println!("{}{}", style(spaced_name).bold(), style(desc).dim())
}
}
pub fn print<T: Display>(s: T) {
println!("{}", s);
}
#[cfg(test)]
mod tests {}