diff options
| author | 魏曹先生 <1992414357@qq.com> | 2026-02-28 18:01:33 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2026-02-28 18:49:31 +0800 |
| commit | 05b7b483056902a07f83bc14f443ab59ce1471d8 (patch) | |
| tree | e46c9e5e672a6d0e9baf4bca09ea159ad669f881 | |
First version0.1.1
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | Cargo.lock | 292 | ||||
| -rw-r--r-- | Cargo.toml | 16 | ||||
| -rw-r--r-- | LICENSE-APACHE | 202 | ||||
| -rw-r--r-- | LICENSE-MIT | 9 | ||||
| -rw-r--r-- | README.md | 97 | ||||
| -rw-r--r-- | src/lib.rs | 223 | ||||
| -rw-r--r-- | src/progress.rs | 200 | ||||
| -rw-r--r-- | src/renderer.rs | 854 |
9 files changed, 1894 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..b4be7da --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,292 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "just_progress" +version = "0.1.1" +dependencies = [ + "tokio", +] + +[[package]] +name = "libc" +version = "0.2.182" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tokio" +version = "1.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..38d9fa4 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "just_progress" +authors = ["Weicao-CatilGrass"] +description = "Just a progress display tool" +version = "0.1.1" +edition = "2024" + +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/catilgrass/just_progress" + +[dependencies] +tokio = { version = "1", features = ["sync"] } + +[dev-dependencies] +tokio = { version = "1", features = ["full"] } diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..51eefef --- /dev/null +++ b/LICENSE-APACHE @@ -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 2026 Weicao-CatilGrass + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..4ff38a3 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,9 @@ +# The MIT License (MIT) + +Copyright © 2026 Weicao-CatilGrass + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..517ae53 --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +# just_progress + +> Just a progress display tool + +## Usage + +```rust +use just_progress::progress; +use just_progress::renderer::ProgressSimpleRenderer; +use tokio::time::{sleep, Duration}; +use tokio::join; + +#[tokio::main] +async fn main() { + // Initialize the progress center + let center = progress::init(); + + // Create a renderer and enable subprogress display + let renderer = ProgressSimpleRenderer::new().with_subprogress(true); + + // Bind the renderer callback function + let bind = progress::bind(center, move |name, state| renderer.update(name, state)); + + // Concurrently execute progress binding and business logic + join!(bind, proc()); +} + +async fn proc() { + println!("Starting package download!"); + sleep(Duration::from_millis(500)).await; + + // Define multiple concurrent download tasks + let download_task = async { + for i in 1..21 { + sleep(Duration::from_millis(50)).await; + progress::update_progress("Download/Data", i as f32 * 0.05); + } + }; + + let extract_task = async { + for i in 1..11 { + sleep(Duration::from_millis(100)).await; + progress::update_progress("Download/Extract", i as f32 * 0.1); + } + }; + + let verify_sha256_task = async { + for i in 1..6 { + sleep(Duration::from_millis(300)).await; + progress::update_progress("Download/Verify/SHA256", i as f32 * 0.2); + } + }; + + let verify_md5_task = async { + for i in 1..6 { + sleep(Duration::from_millis(100)).await; + progress::update_progress("Download/Verify/MD5", i as f32 * 0.2); + } + }; + + let verify_blake3_task = async { + for i in 1..6 { + sleep(Duration::from_millis(500)).await; + progress::update_progress("Download/Verify/Blake3", i as f32 * 0.2); + } + }; + + // Concurrently execute all download tasks + join!( + download_task, + extract_task, + verify_sha256_task, + verify_blake3_task, + verify_md5_task + ); + + sleep(Duration::from_millis(500)).await; + progress::clear_all(); // Clear all progress after download completes + println!("Package download complete!"); + + progress::close(); // Close the progress channel, ending the program +} +``` + +## Installation + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +just_progress = "0.1" +``` + +## License + +This project is dual-licensed under MIT and Apache 2.0. +See the LICENSE file for details. diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..2875c41 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,223 @@ +//! Progress Management Library +//! +//! This library provides flexible progress management functionality, supporting multi-level progress display and custom renderers. +//! +//! # Quick Start +//! +//! The following is a simple usage example demonstrating how to create a progress center, bind a renderer, and update progress for multiple concurrent tasks: +//! +//! ```rust +//! use just_progress::progress; +//! use just_progress::renderer::ProgressSimpleRenderer; +//! use tokio::time::{sleep, Duration}; +//! use tokio::join; +//! +//! #[tokio::main] +//! async fn main() { +//! // Initialize the progress center +//! let center = progress::init(); +//! // Create a renderer and enable subprogress display +//! let renderer = ProgressSimpleRenderer::new().with_subprogress(true); +//! // Bind the renderer callback function +//! let bind = progress::bind(center, move |name, state| renderer.update(name, state)); +//! +//! // Concurrently execute progress binding and business logic +//! join!(bind, proc()); +//! } +//! +//! async fn proc() { +//! println!("Starting package download!"); +//! sleep(Duration::from_millis(500)).await; +//! +//! // Define multiple concurrent download tasks +//! let download_task = async { +//! for i in 1..21 { +//! sleep(Duration::from_millis(50)).await; +//! progress::update_progress("Download/Data", i as f32 * 0.05); +//! } +//! }; +//! +//! let extract_task = async { +//! for i in 1..11 { +//! sleep(Duration::from_millis(100)).await; +//! progress::update_progress("Download/Extract", i as f32 * 0.1); +//! } +//! }; +//! +//! let verify_sha256_task = async { +//! for i in 1..6 { +//! sleep(Duration::from_millis(300)).await; +//! progress::update_progress("Download/Verify/SHA256", i as f32 * 0.2); +//! } +//! }; +//! +//! let verify_md5_task = async { +//! for i in 1..6 { +//! sleep(Duration::from_millis(100)).await; +//! progress::update_progress("Download/Verify/MD5", i as f32 * 0.2); +//! } +//! }; +//! +//! let verify_blake3_task = async { +//! for i in 1..6 { +//! sleep(Duration::from_millis(500)).await; +//! progress::update_progress("Download/Verify/Blake3", i as f32 * 0.2); +//! } +//! }; +//! +//! // Concurrently execute all download tasks +//! join!( +//! download_task, +//! extract_task, +//! verify_sha256_task, +//! verify_blake3_task, +//! verify_md5_task +//! ); +//! +//! sleep(Duration::from_millis(500)).await; +//! progress::clear_all(); // Clear all progress after download completes +//! println!("Package download complete!"); +//! +//! progress::close(); // Close the progress channel, ending the program +//! } +//! ``` +//! + +/// Progress Module +/// +/// Provides core functionality for progress management, including progress center initialization, +/// status updates, and callback binding. +/// +/// # Usage +/// +/// 1. Initialize the progress center: +/// ```rust +/// # use just_progress::progress; +/// let progress_center = progress::init(); +/// ``` +/// +/// 2. Bind a renderer callback: +/// ```rust +/// # use just_progress::progress; +/// # use just_progress::renderer::ProgressSimpleRenderer; +/// let center = progress::init(); +/// let renderer = ProgressSimpleRenderer::new().with_subprogress(true); +/// let bind = progress::bind(center, move |name, state| renderer.update(name, state)); +/// // Run `bind` and business logic in an async context +/// ``` +/// +/// 3. Update progress status: +/// ```rust +/// # use just_progress::progress::{self, ProgressInfo}; +/// // Update progress value +/// progress::update_progress("download/file1", 0.5); +/// +/// // Update status information +/// progress::update_info("download/file1", ProgressInfo::Info("Downloading...")); +/// +/// // Update both progress and status simultaneously +/// progress::update("download/file1", 0.75, ProgressInfo::Warning("Slow network")); +/// +/// // Mark as complete +/// // Equivalent to progress::update_progress("download/file1", 1.0); +/// progress::complete("download/file1"); +/// +/// // Clear all progress items +/// progress::clear_all(); +/// +/// // Close the progress channel +/// progress::close(); +/// ``` +/// +/// # Special Flags +/// +/// The module uses two special flags internally to control the flow: +/// - `_clear`: Clears all progress items +/// - `_close`: Closes the binding channel, stopping callbacks +/// +/// # Asynchronous Binding +/// +/// The `bind` function creates an asynchronous Future that listens for progress changes and invokes the callback. +/// The callback receives the progress name and state, making it suitable for use with renderers. +/// +/// # Hierarchical Progress +/// +/// Progress names can use slashes (`/`) to represent hierarchical relationships, e.g., `"parent/child"`. +/// Renderers can leverage this structure to display indentation or calculate the average progress of parent tasks. +/// +/// # Notes +/// +/// - `init()` must be called before using any other functions. +/// - The Future returned by `bind()` needs to be polled or awaited for callbacks to execute. +/// - `clear_all()` sends a clear signal but does not immediately clear messages in the channel. +/// - `close()` stops all `bind()` calls; progress updates are no longer possible afterward. +/// +pub mod progress; + +/// Renderer Module +/// +/// Provides the `ProgressSimpleRenderer` for displaying progress bars and status information. +/// +/// # Usage +/// +/// 1. Create a renderer instance: +/// ```rust +/// # use just_progress::renderer::ProgressSimpleRenderer; +/// let renderer = ProgressSimpleRenderer::new(); +/// ``` +/// +/// 2. Configure the renderer (optional): +/// ```rust +/// # use just_progress::renderer::ProgressSimpleRenderer; +/// # use just_progress::renderer::RendererSortingRule; +/// let renderer = ProgressSimpleRenderer::new() +/// .with_subprogress(true) // Enable subprogress +/// .with_auto_remove_completed(true) // Automatically remove completed items +/// .with_sorting(RendererSortingRule::AlphabeticalAsc); // Sort alphabetically ascending +/// ``` +/// +/// 3. Trigger rendering: +/// ```rust +/// # use just_progress::renderer::ProgressSimpleRenderer; +/// # use just_progress::renderer::RendererSortingRule; +/// # use just_progress::progress::{ProgressState, ProgressInfo}; +/// # let renderer = ProgressSimpleRenderer::new(); +/// renderer.render_all(); +/// ``` +/// +/// # Subprogress +/// +/// When `subprogress` is enabled, progress names can be separated by slashes (`/`) to represent hierarchical relationships: +/// - `"parent"` - Top-level progress +/// - `"parent/child"` - Subprogress, automatically indented when displayed +/// - `"parent/child/grandchild"` - Deeper level progress +/// +/// If a parent node does not have a directly corresponding progress state, the renderer will automatically calculate the average progress of its child nodes as the display value. +/// +/// # Theme +/// +/// Customize the rendering style via the `RendererTheme` struct: +/// ```rust +/// use just_progress::renderer::{RendererTheme, ProgressSimpleRenderer}; +/// let theme = RendererTheme { +/// layout: "{name},{progress},{percent}", +/// show_state: false, +/// progress_content_len: 30, +/// progress_filled_char: "█", +/// progress_empty_char: "░", +/// ..RendererTheme::default() +/// }; +/// let renderer = ProgressSimpleRenderer::new().with_theme(theme); +/// ``` +/// +/// # Layout +/// +/// The `layout` field uses a comma-separated template string, supporting the following placeholders: +/// - `{name}`: Progress name (supports indentation) +/// - `{state}`: Status information (INFO/WARN/ERROR) +/// - `{progress}`: Progress bar +/// - `{percent}`: Percentage +/// +/// Example: `"{name},{state},{progress},{percent}"` +/// +pub mod renderer; diff --git a/src/progress.rs b/src/progress.rs new file mode 100644 index 0000000..a5509ef --- /dev/null +++ b/src/progress.rs @@ -0,0 +1,200 @@ +use std::{collections::HashMap, fmt::Display, sync::OnceLock}; +use tokio::sync::watch; + +pub static PROGRESS_CENTER: OnceLock<ProgressCenter> = OnceLock::new(); + +const SPECIAL_FLAG_CLEAR: &str = "_clear"; +const SPECIAL_FLAG_CLOSE: &str = "_close"; + +#[derive(Debug)] +pub struct ProgressCenter { + tx: watch::Sender<HashMap<String, ProgressState>>, + rx: watch::Receiver<HashMap<String, ProgressState>>, +} + +/// Initialize `ProgressCenter` early in the program +/// +/// ``` rust +/// use just_progress::progress; +/// +/// fn main() { +/// // Initialize +/// let progress_center = progress::init(); +/// } +/// ``` +pub fn init() -> &'static ProgressCenter { + let (tx, rx) = watch::channel::<HashMap<String, ProgressState>>(HashMap::new()); + PROGRESS_CENTER.get_or_init(|| ProgressCenter { tx, rx }) +} + +/// Bind a callback to ProgressCenter and create a Future for receiving and rendering messages +/// +/// +/// ```rust +/// use just_progress::progress; +/// +/// #[tokio::main] +/// async fn main() { +/// // Initialize +/// let progress_center = progress::init(); +/// let bind_future = progress::bind(progress_center, |name, state| { +/// println!("Update progress `{}` state to `{}`", name, state); +/// }); +/// } +/// ``` +pub fn bind<F>( + center: &'static ProgressCenter, + mut callback: F, +) -> impl std::future::Future<Output = ()> + Send +where + F: FnMut(String, ProgressState) + Send + 'static, +{ + let mut rx = center.rx.clone(); + async move { + while rx.changed().await.is_ok() { + let state = rx.borrow().clone(); + + // If it's a close flag, break + if let Some(_) = state.get(SPECIAL_FLAG_CLOSE) { + break; + } + // Clear flag + if let Some(_) = state.get(SPECIAL_FLAG_CLEAR) { + // Send all known names + progress 0 + EmptyState + for (name, _) in state.iter().filter(|(k, _)| *k != SPECIAL_FLAG_CLEAR) { + callback( + name.clone(), + ProgressState { + progress: 0.0, + info: ProgressInfo::Empty, + }, + ); + } + // Clear the entire HashMap + let _ = center.tx.send(HashMap::new()); + } else { + for (name, progress_state) in state { + callback(name, progress_state); + } + } + } + } +} + +#[derive(Debug, Default, Clone, Copy)] +pub struct ProgressState { + pub(crate) progress: f32, + pub(crate) info: ProgressInfo, +} + +impl ProgressState { + /// Get the progress value (0.0 to 1.0) + pub fn progress(&self) -> f32 { + self.progress + } + + /// Get the progress info + pub fn info(&self) -> ProgressInfo { + self.info + } +} + +impl Display for ProgressState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let space = if !matches!(self.info, ProgressInfo::Empty) { + " " + } else { + "" + }; + write!(f, "{}{}({:.1}%)", self.info, space, self.progress * 100.0) + } +} + +#[derive(Debug, Default, Clone, Copy)] +pub enum ProgressInfo { + #[default] + Empty, + Info(&'static str), + Warning(&'static str), + Error(&'static str), +} + +impl Display for ProgressInfo { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ProgressInfo::Empty => write!(f, ""), + ProgressInfo::Info(msg) => write!(f, "Info: `{}`", msg), + ProgressInfo::Warning(msg) => write!(f, "Warning: `{}`", msg), + ProgressInfo::Error(msg) => write!(f, "Error: `{}`", msg), + } + } +} + +/// Complete an item +/// +/// Set an item's progress to 100% so it disappears from progress rendering +pub fn complete(name: &str) { + update_progress(name, 1.); +} + +/// Clear all +/// +/// Send a message to clear all items, ensuring no progress remains +pub fn clear_all() { + update(SPECIAL_FLAG_CLEAR, 0., ProgressInfo::Empty); +} + +/// Close the channel +/// +/// Send a close message to stop bind() from running +pub fn close() { + update(SPECIAL_FLAG_CLOSE, 0., ProgressInfo::Empty); +} + +/// Update +/// +/// Update a progress item's information +pub fn update(name: &str, progress: f32, info: ProgressInfo) { + let Some(center) = PROGRESS_CENTER.get() else { + return; + }; + let mut state = center.tx.borrow().clone(); + state.insert(name.to_string(), ProgressState { progress, info }); + let _ = center.tx.send(state); +} + +/// Update progress +/// +/// Modify a progress item's value +pub fn update_progress(name: &str, progress: f32) { + let Some(center) = PROGRESS_CENTER.get() else { + return; + }; + let mut state = center.tx.borrow().clone(); + let entry = state + .entry(name.to_string()) + .or_insert_with(|| ProgressState { + progress: 0.0, + info: ProgressInfo::default(), + }); + entry.progress = progress; + let _ = center.tx.send(state); +} + +/// Update info +/// +/// Modify a progress item's status information +pub fn update_info(name: &str, info: ProgressInfo) { + let Some(center) = PROGRESS_CENTER.get() else { + return; + }; + let mut state = center.tx.borrow().clone(); + let entry = state + .entry(name.to_string()) + .or_insert_with(|| ProgressState { + progress: 0.0, + info: ProgressInfo::default(), + }); + entry.info = info; + let _ = center.tx.send(state); +} diff --git a/src/renderer.rs b/src/renderer.rs new file mode 100644 index 0000000..ccd083b --- /dev/null +++ b/src/renderer.rs @@ -0,0 +1,854 @@ +use crate::progress::ProgressInfo; +use crate::progress::ProgressState; +use std::collections::HashMap; +use std::io::{self, Write}; +use std::sync::{Arc, Mutex}; + +pub struct ProgressSimpleRenderer<'a> { + /// Use sub-progress (split by "/", indent by level) + /// If no relevant parent node exists, show parent progress as overall percentage of child progress + pub subprogress: bool, + + /// Sorting rule + pub sorting: RendererSortingRule, + + /// Theme + pub theme: RendererTheme<'a>, + + /// Whether to automatically remove completed (100%) progress items + pub auto_remove_completed: bool, + + /// Internal state storage + states: Arc<Mutex<HashMap<String, ProgressState>>>, + + /// Number of lines rendered last time + last_line_count: Arc<Mutex<usize>>, +} + +impl<'a> ProgressSimpleRenderer<'a> { + /// Create a new renderer + pub fn new() -> Self { + Self { + subprogress: false, + sorting: RendererSortingRule::Append, + theme: RendererTheme::default(), + auto_remove_completed: true, + states: Arc::new(Mutex::new(HashMap::new())), + last_line_count: Arc::new(Mutex::new(0)), + } + } + + /// Set whether to use sub-progress + pub fn with_subprogress(mut self, subprogress: bool) -> Self { + self.subprogress = subprogress; + self + } + + /// Set sorting rule + pub fn with_sorting(mut self, sorting: RendererSortingRule) -> Self { + self.sorting = sorting; + self + } + + /// Set theme + pub fn with_theme(mut self, theme: RendererTheme<'a>) -> Self { + self.theme = theme; + self + } + + /// Set whether to automatically remove completed (100%) progress items + pub fn with_auto_remove_completed(mut self, auto_remove: bool) -> Self { + self.auto_remove_completed = auto_remove; + self + } + + /// Update progress state and render + pub fn update(&self, name: String, state: ProgressState) { + { + let mut states = self.states.lock().unwrap(); + + if self.auto_remove_completed && state.progress() >= 1.0 { + states.remove(&name); + } else { + states.insert(name.clone(), state); + } + } + + // Render all states + self.render_all(); + } + + /// Clear the previously rendered content in the terminal + fn clear_previous_output(&self) { + let line_count = *self.last_line_count.lock().unwrap(); + if line_count > 0 { + print!("\x1B[{}A\x1B[0J", line_count); + } + } + + /// Save the number of lines rendered this time + fn save_line_count(&self, count: usize) { + let mut last_line_count = self.last_line_count.lock().unwrap(); + *last_line_count = count; + } + + /// Render all progress states + pub fn render_all(&self) { + let states = self.states.lock().unwrap(); + + if states.is_empty() { + self.clear_previous_output(); + self.save_line_count(0); + return; + } + + // Collect all progress items + let mut items: Vec<ProgressItem> = Vec::new(); + + for (name, state) in states.iter() { + // If `auto_remove_completed` is enabled, skip 100% progress items + if self.auto_remove_completed && state.progress() >= 1.0 { + continue; + } + + items.push(ProgressItem { + name: name.clone(), + progress: state.progress(), + info: state.info(), + depth: 0, + is_parent: false, + }); + } + + // If `subprogress` is enabled, compute hierarchy + if self.subprogress { + self.process_subprogress(&mut items); + } + + // Sort + self.sort_items(&mut items); + + // Render and save line count + let line_count = self.render_items(&items); + self.save_line_count(line_count); + } + + /// Clear all progress states + pub fn clear(&self) { + // Clear previous output + self.clear_previous_output(); + + let mut states = self.states.lock().unwrap(); + states.clear(); + + // Reset line count + self.save_line_count(0); + } + + /// Process sub-progress, compute levels and indentation + fn process_subprogress(&self, items: &mut Vec<ProgressItem>) { + // Find parent nodes + let mut parent_items: Vec<String> = Vec::new(); + + for item in items.iter() { + let parts: Vec<&str> = item.name.split('/').collect(); + if parts.len() > 1 { + // Build parent node path + for i in 1..parts.len() { + let parent_path = parts[0..i].join("/"); + if !parent_items.contains(&parent_path) { + parent_items.push(parent_path); + } + } + } + } + + // Compute depth for each item + for item in items.iter_mut() { + item.depth = item.name.matches('/').count(); + } + + // Add missing parent nodes + for parent_path in parent_items { + if !items.iter().any(|item| item.name == parent_path) { + // Compute parent node progress + let child_progress: Vec<f32> = items + .iter() + .filter(|item| item.name.starts_with(&format!("{}/", parent_path))) + .map(|item| item.progress) + .collect(); + + let avg_progress = if !child_progress.is_empty() { + child_progress.iter().sum::<f32>() / child_progress.len() as f32 + } else { + 0.0 + }; + + items.push(ProgressItem { + name: parent_path.clone(), + progress: avg_progress, + info: ProgressInfo::Empty, + depth: parent_path.matches('/').count(), + is_parent: true, + }); + } + } + + // Mark parent nodes + let item_names: Vec<String> = items.iter().map(|item| item.name.clone()).collect(); + for item in items.iter_mut() { + if item_names.iter().any(|other_name| { + other_name != &item.name && other_name.starts_with(&format!("{}/", item.name)) + }) { + item.is_parent = true; + } + } + } + + /// Sort items according to sorting rule + fn sort_items(&self, items: &mut Vec<ProgressItem>) { + if self.subprogress { + items.sort_by(|a, b| match self.sorting { + RendererSortingRule::Append => a.name.cmp(&b.name), + RendererSortingRule::AlphabeticalAsc => a.name.cmp(&b.name), + RendererSortingRule::AlphabeticalDesc => b.name.cmp(&a.name), + }); + } else { + match self.sorting { + RendererSortingRule::AlphabeticalAsc => { + items.sort_by(|a, b| a.name.cmp(&b.name)); + } + RendererSortingRule::AlphabeticalDesc => { + items.sort_by(|a, b| b.name.cmp(&a.name)); + } + RendererSortingRule::Append => {} + } + } + } + + /// Render all items, return the number of lines rendered + fn render_items(&self, items: &[ProgressItem]) -> usize { + // Compute maximum width for alignment + let max_name_width = items + .iter() + .map(|item| { + let indent = if self.subprogress { + item.depth * self.theme.indent_spaces + } else { + 0 + }; + let display_name_len = if self.subprogress { + // For sub-progress, only show the last part + item.name.split('/').last().unwrap_or(&item.name).len() + } else { + item.name.len() + }; + display_name_len + indent + }) + .max() + .unwrap_or(0); + + let max_state_width = if self.theme.show_state { + items + .iter() + .map(|item| self.format_state(item.info).len()) + .max() + .unwrap_or(0) + } else { + 0 + }; + + // Build complete output string + let mut output = String::new(); + + // Add clear command + let line_count = *self.last_line_count.lock().unwrap(); + if line_count > 0 { + output.push_str(&format!("\x1B[{}A\x1B[0J", line_count)); + } + + // Add all lines + for item in items { + let line = self.format_item(item, max_name_width, max_state_width); + output.push_str(&line); + output.push('\n'); + } + + // Disable buffering, output immediately + let _ = io::stdout().write_all(output.as_bytes()); + let _ = io::stdout().flush(); + + items.len() + } + + /// Format a single item + fn format_item( + &self, + item: &ProgressItem, + max_name_width: usize, + max_state_width: usize, + ) -> String { + let mut result = String::new(); + let layout = self.theme.layout; + + // Parse layout template + for part in layout.split(',') { + match part.trim() { + "{name}" => { + let name = self.format_name(item, max_name_width); + result.push_str(&name); + } + "{state}" => { + if self.theme.show_state { + let state = self.format_state(item.info); + if !state.is_empty() { + let state = if self.theme.align { + self.align_component(&state, max_state_width, false) + } else { + state + }; + result.push_str(&state); + } + } + } + "{progress}" => { + if self.theme.show_progress { + let progress = self.format_progress(item.progress); + if !progress.is_empty() { + let progress = if self.theme.align { + self.align_component(&progress, 0, false) + } else { + progress + }; + result.push_str(&progress); + } + } + } + "{percent}" => { + if self.theme.show_percent { + let percent = self.format_percent(item.progress); + if !percent.is_empty() { + let percent = if self.theme.align { + self.align_component(&percent, 0, false) + } else { + percent + }; + result.push_str(&percent); + } + } + } + _ => { + // Output as-is + result.push_str(part); + } + } + } + + result + } + + /// Format name (including indentation) + fn format_name(&self, item: &ProgressItem, max_width: usize) -> String { + let indent = if self.subprogress { + " ".repeat(item.depth * self.theme.indent_spaces) + } else { + String::new() + }; + + // Only show the last part of the path + let display_name = if self.subprogress { + item.name + .split('/') + .last() + .unwrap_or(&item.name) + .to_string() + } else { + item.name.clone() + }; + + let name = format!("{}{}", indent, display_name); + + if self.theme.align { + self.align_component(&name, max_width, true) + } else { + name + } + } + + /// Format state + fn format_state(&self, info: ProgressInfo) -> String { + match info { + ProgressInfo::Empty => self.theme.state_empty.to_string(), + ProgressInfo::Info(msg) => self.theme.state_info.replace("{}", msg), + ProgressInfo::Warning(msg) => self.theme.state_warning.replace("{}", msg), + ProgressInfo::Error(msg) => self.theme.state_error.replace("{}", msg), + } + } + + /// Format progress bar + fn format_progress(&self, progress: f32) -> String { + let filled_len = (progress * self.theme.progress_content_len as f32).round() as usize; + let empty_len = self.theme.progress_content_len - filled_len; + + let filled = self.theme.progress_filled_char.repeat(filled_len); + let empty = self.theme.progress_empty_char.repeat(empty_len); + + self.theme + .progress + .replace("{}", &format!("{}{}", filled, empty)) + } + + /// Format percentage + fn format_percent(&self, progress: f32) -> String { + let percent = progress * 100.0; + let formatted = format!("{:.1$}", percent, self.theme.percent_decimal_places); + self.theme.percent.replace("{}", &formatted) + } + + /// Align component + fn align_component( + &self, + component: &str, + max_width: usize, + is_first_component: bool, + ) -> String { + let trimmed = if is_first_component { + // For the first component, only trim the end, not the beginning + component.trim_end() + } else { + component.trim() + }; + + if trimmed.is_empty() { + // Empty component is not aligned, return empty string + String::new() + } else { + let padding = max_width.saturating_sub(trimmed.len()); + let before_padding = " ".repeat(self.theme.align_padding_before); + let after_padding = " ".repeat(self.theme.align_padding_after); + format!( + "{}{}{}{}", + before_padding, + trimmed, + " ".repeat(padding), + after_padding + ) + } + } +} + +struct ProgressItem { + name: String, + progress: f32, + info: ProgressInfo, + depth: usize, + is_parent: bool, +} + +pub enum RendererSortingRule { + /// Append, newly added progress items are always at the end + Append, + + /// Sort by name in ascending alphabetical order + AlphabeticalAsc, + + /// Sort by name in descending alphabetical order + AlphabeticalDesc, +} + +pub struct RendererTheme<'a> { + /// Alignment + /// When enabled, ensures the first character of each component of each item is aligned + /// At the same time, each component will be trimmed before and after + pub align: bool, + + /// Number of spaces before a component when aligning + pub align_padding_before: usize, + + /// Number of spaces after a component when aligning + pub align_padding_after: usize, + + /// Overall layout + pub layout: &'a str, + + /// Show state (different from setting in `layout`, it affects whether this component is rendered) + pub show_state: bool, + + /// Warning state style + pub state_warning: &'a str, + + /// Error state style + pub state_error: &'a str, + + /// Info state style + pub state_info: &'a str, + + /// Empty state style + pub state_empty: &'a str, + + /// Show progress bar (different from setting in `layout`, it affects whether this component is rendered) + pub show_progress: bool, + + /// Progress bar style + pub progress: &'a str, + + /// Number of content characters in the progress bar + pub progress_content_len: usize, + + /// Character for filled part + pub progress_filled_char: &'a str, + + /// Character for unfilled part + pub progress_empty_char: &'a str, + + /// Show percentage (different from setting in `layout`, it affects whether this component is rendered) + pub show_percent: bool, + + /// Percentage style + pub percent: &'a str, + + /// Number of decimal places for percentage + pub percent_decimal_places: usize, + + /// Number of spaces per indentation level + pub indent_spaces: usize, +} + +impl<'a> Default for RendererTheme<'a> { + fn default() -> Self { + Self { + align: true, + layout: "{name},{state},{progress},{percent}", + show_state: true, + state_warning: " WARN: {}", + state_error: " ERR: {}", + state_info: " INFO: {}", + state_empty: "", + show_progress: true, + progress: " [{}]", + progress_content_len: 20, + progress_filled_char: "#", + progress_empty_char: " ", + show_percent: true, + percent: " ({}%)", + percent_decimal_places: 1, + indent_spaces: 2, + align_padding_before: 0, + align_padding_after: 1, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::progress::{ProgressInfo, ProgressState}; + + #[test] + fn test_renderer_update() { + let renderer = ProgressSimpleRenderer::new(); + + // Test update and rendering + renderer.update( + "task1".to_string(), + ProgressState { + progress: 0.5, + info: ProgressInfo::Info("Processing"), + }, + ); + + renderer.update( + "task2".to_string(), + ProgressState { + progress: 0.75, + info: ProgressInfo::Warning("Almost done"), + }, + ); + + // Call render_all to render + renderer.render_all(); + } + + #[test] + fn test_renderer_with_subprogress() { + let renderer = ProgressSimpleRenderer::new().with_subprogress(true); + + renderer.update( + "download/file1".to_string(), + ProgressState { + progress: 0.5, + info: ProgressInfo::Info("Downloading file1"), + }, + ); + + renderer.update( + "download/file2".to_string(), + ProgressState { + progress: 0.75, + info: ProgressInfo::Info("Downloading file2"), + }, + ); + + renderer.render_all(); + } + + #[test] + fn test_auto_remove_completed() { + let renderer = ProgressSimpleRenderer::new().with_auto_remove_completed(true); + + // Add an unfinished task + renderer.update( + "task1".to_string(), + ProgressState { + progress: 0.5, + info: ProgressInfo::Info("Processing"), + }, + ); + + // Add a completed task + renderer.update( + "task2".to_string(), + ProgressState { + progress: 1.0, + info: ProgressInfo::Info("Completed"), + }, + ); + + // Render, should only show task1 + renderer.render_all(); + + // Check internal state, task2 should be removed + { + let states = renderer.states.lock().unwrap(); + assert!(states.contains_key("task1")); + assert!(!states.contains_key("task2")); + } + } + + #[test] + fn test_auto_remove_completed_disabled() { + let renderer = ProgressSimpleRenderer::new().with_auto_remove_completed(false); + + // Add a completed task + renderer.update( + "task1".to_string(), + ProgressState { + progress: 1.0, + info: ProgressInfo::Info("Completed"), + }, + ); + + // Check internal state, task1 should still exist + { + let states = renderer.states.lock().unwrap(); + assert!(states.contains_key("task1")); + } + } + #[test] + fn test_indent_spaces_config() { + // Create custom theme, set indent spaces to 4 + let mut theme = RendererTheme::default(); + theme.indent_spaces = 4; + + let renderer = ProgressSimpleRenderer::new() + .with_subprogress(true) + .with_theme(theme); + + // Add multi-level progress + renderer.update( + "parent".to_string(), + ProgressState { + progress: 0.5, + info: ProgressInfo::Info("Parent task"), + }, + ); + + renderer.update( + "parent/child".to_string(), + ProgressState { + progress: 0.75, + info: ProgressInfo::Info("Child task"), + }, + ); + + renderer.update( + "parent/child/grandchild".to_string(), + ProgressState { + progress: 0.9, + info: ProgressInfo::Info("Grandchild task"), + }, + ); + + // Render and check + renderer.render_all(); + + // Check internal state + { + let states = renderer.states.lock().unwrap(); + assert!(states.contains_key("parent")); + assert!(states.contains_key("parent/child")); + assert!(states.contains_key("parent/child/grandchild")); + } + } + + #[test] + fn test_align_padding_config() { + // Create custom theme, set alignment padding before and after + let mut theme = RendererTheme::default(); + theme.align = true; + theme.align_padding_before = 2; + theme.align_padding_after = 3; + + let renderer = ProgressSimpleRenderer::new().with_theme(theme); + + // Add test data + renderer.update( + "task1".to_string(), + ProgressState { + progress: 0.5, + info: ProgressInfo::Info("Processing"), + }, + ); + + renderer.update( + "task2".to_string(), + ProgressState { + progress: 0.75, + info: ProgressInfo::Warning("Almost done"), + }, + ); + + // Render and check + renderer.render_all(); + + // Check internal state + { + let states = renderer.states.lock().unwrap(); + assert!(states.contains_key("task1")); + assert!(states.contains_key("task2")); + } + } + + #[test] + fn test_align_padding_with_empty_state() { + // Create custom theme, set alignment padding before and after + let mut theme = RendererTheme::default(); + theme.align = true; + theme.align_padding_before = 1; + theme.align_padding_after = 2; + theme.show_state = true; + + let renderer = ProgressSimpleRenderer::new().with_theme(theme); + + // Add test data - empty state + renderer.update( + "task1".to_string(), + ProgressState { + progress: 0.5, + info: ProgressInfo::Empty, + }, + ); + + // Add test data - with state + renderer.update( + "task2".to_string(), + ProgressState { + progress: 0.75, + info: ProgressInfo::Info("Processing"), + }, + ); + + // Render and check + renderer.render_all(); + + // Check internal state + { + let states = renderer.states.lock().unwrap(); + assert!(states.contains_key("task1")); + assert!(states.contains_key("task2")); + } + } + + #[test] + fn test_align_first_component_no_trim_start() { + let renderer = ProgressSimpleRenderer::new(); + + // Test that the first component does not trim the start when aligning + let component = " test "; + let aligned = renderer.align_component(component, 10, true); + + // The first component should only trim the end, not the start + assert!(aligned.starts_with(" test")); + assert!(!aligned.starts_with("test")); + } + + #[test] + fn test_align_non_first_component_trim_both() { + let renderer = ProgressSimpleRenderer::new(); + + // Test that non-first components trim both sides when aligning + let component = " test "; + let aligned = renderer.align_component(component, 10, false); + + // Non-first components should trim both sides + assert!(aligned.starts_with("test")); + assert!(!aligned.starts_with(" test")); + } + + #[test] + fn test_format_progress() { + let renderer = ProgressSimpleRenderer::new(); + let progress = renderer.format_progress(0.5); + assert!(progress.contains("[")); + assert!(progress.contains("]")); + } + + #[test] + fn test_format_percent() { + let renderer = ProgressSimpleRenderer::new(); + let percent = renderer.format_percent(0.5); + assert!(percent.contains("50")); + assert!(percent.contains("%")); + } + + #[test] + fn test_subprogress_indentation() { + let renderer = ProgressSimpleRenderer::new().with_subprogress(true); + + // Add parent and child nodes + renderer.update( + "progress".to_string(), + ProgressState { + progress: 0.95, + info: ProgressInfo::Info("Processing"), + }, + ); + + renderer.update( + "progress/2".to_string(), + ProgressState { + progress: 0.95, + info: ProgressInfo::Info("Step 2"), + }, + ); + + renderer.update( + "progress/3".to_string(), + ProgressState { + progress: 0.8, + info: ProgressInfo::Info("Step 3"), + }, + ); + + // Render and check output format + renderer.render_all(); + + // Check internal state + { + let states = renderer.states.lock().unwrap(); + assert!(states.contains_key("progress")); + assert!(states.contains_key("progress/2")); + assert!(states.contains_key("progress/3")); + } + } +} |
