From ddd9bf0b2907082eeab68851af4f6344c9456724 Mon Sep 17 00:00:00 2001 From: Dimitri Lozeve Date: Sat, 10 Sep 2022 21:06:37 +0200 Subject: [PATCH] Add progress bars --- build.ss | 1 + demo.ss | 6 ++++++ fancy/progress.ss | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 fancy/progress.ss diff --git a/build.ss b/build.ss index 0b6399f..c814c94 100755 --- a/build.ss +++ b/build.ss @@ -6,5 +6,6 @@ '("fancy/format" "fancy/table" "fancy/rule" + "fancy/progress" "fancy/spinner") optimize: #t debug: 'src) diff --git a/demo.ss b/demo.ss index 7a228d2..8f8a507 100755 --- a/demo.ss +++ b/demo.ss @@ -8,6 +8,7 @@ :dlozeve/fancy/format :dlozeve/fancy/table :dlozeve/fancy/rule + :dlozeve/fancy/progress :dlozeve/fancy/spinner) (def (main) @@ -30,6 +31,11 @@ culpa qui officia deserunt mollit anim id est laborum.")) (display (table-footer tab)) (displayln) (displayln) + (def pbar (progress-bar 100 "[green]Progress: " percent: #f style: 'line)) + (for ((i (in-range 100))) + (display (progress pbar (1+ i))) + (thread-sleep! 0.05)) + (displayln) (for ((i (in-range 20))) (display (spinner i "[yellow]Waiting:" (format "(computing ~d/20)" (1+ i)) style: 'dots)) diff --git a/fancy/progress.ss b/fancy/progress.ss new file mode 100644 index 0000000..576db8f --- /dev/null +++ b/fancy/progress.ss @@ -0,0 +1,39 @@ +(export (struct-out progress-bar) + progress) + +(import :std/misc/string + :std/format + :dlozeve/fancy/format) + +(def +progress-styles+ + '((ascii . (#\[ #\= #\> #\ #\])) + (line . (#\┝ #\━ #\━ #\ #\┥)) + (double . (#\╞ #\═ #\═ #\ #\╡)) + (block . (#\│ #\█ #\█ #\ #\│)) + (halfblock . (#\╻ #\▄ #\▄ #\ #\╻)) + (dots . (#\⣿ #\⠶ #\⠶ #\⠀ #\⣿)))) + +(defstruct progress-bar (total description length style percent) + constructor: :init!) + +(defmethod {:init! progress-bar} + (lambda (self total (description #f) length: (length 80) style: (style 'line) percent: (percent #f)) + (struct-instance-init! self total description length style percent))) + +(def (progress pbar n) + (with ((progress-bar total description length style percent) pbar) + (let* ((n (min total (max 0 n))) + (n-done (inexact->exact (floor (* (- length 3) (/ n total))))) + (n-remaining (inexact->exact (ceiling (* (- length 3) (/ (- total n) total))))) + (progress-chars (assgetq style +progress-styles+)) + (bar (format "~c~a~c~a~c" + (list-ref progress-chars 0) + (make-string n-done (list-ref progress-chars 1)) + (list-ref progress-chars 2) + (make-string n-remaining (list-ref progress-chars 3)) + (list-ref progress-chars 4))) + (progress (if percent + (format "~3,0F%" (* 100 (/ n total))) + (format "(~d/~d)" n total)))) + (str (cursor-up 1) + (parse-markup description) bar " " progress "\n"))))