package progress

  1. Overview
  2. Docs

Source file segment.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
include Segment_intf
open Utils
open Staging

module Width = struct
  external sigwinch : unit -> int = "ocaml_progress_sigwinch"

  let sigwinch = lazy (sigwinch ())

  let default ~fallback =
    let get_winsize () =
      match Terminal_size.get_columns () with Some c -> c | None -> fallback
    in
    let columns = ref (get_winsize ()) in
    Sys.set_signal (Lazy.force sigwinch)
      (Sys.Signal_handle (fun _ -> columns := get_winsize ()));
    columns
end

type 'a t =
  | Pp_unsized of { pp : width:(unit -> int) -> Format.formatter -> 'a -> unit }
  | Pp_fixed of { pp : Format.formatter -> 'a -> unit; width : int }
  | Const of { pp : Format.formatter -> unit; width : int }
  | Staged of (unit -> 'a t)
  | Contramap : 'a t * ('b -> 'a) -> 'b t
  | Cond of 'a t cond
  | Box of { contents : 'a t; width : int ref }
  | Group of 'a t array
  | Pair : { left : 'a t; sep : unit t; right : 'b t } -> ('a * 'b) t

and 'a cond = { if_ : unit -> bool; then_ : 'a }

let of_pp ~width pp = Pp_fixed { pp; width }
let const_fmt ~width pp = Const { pp; width }

let const s =
  const_fmt ~width:(String.length s) (fun ppf -> Format.pp_print_string ppf s)

let utf8_chars =
  (* Characters: space @ [0x258F .. 0x2589] *)
  [| " "; "▏"; "▎"; "▍"; "▌"; "▋"; "▊"; "▉"; "█" |]

let utf_num = Array.length utf8_chars - 1

let bar_unicode width proportion ppf =
  let bar_width =
    let width = width () in
    width - 2
  in
  let squaresf = Float.of_int bar_width *. proportion in
  let squares = Float.to_int squaresf in
  let filled = min squares bar_width in
  let not_filled = bar_width - filled - 1 in
  Format.pp_print_string ppf "│";
  for _ = 1 to filled do
    Format.pp_print_string ppf utf8_chars.(utf_num)
  done;
  ( if filled <> bar_width then
    let () =
      let chunks = Float.to_int (squaresf *. Float.of_int utf_num) in
      let index = chunks - (filled * utf_num) in
      if index < utf_num then Format.pp_print_string ppf utf8_chars.(index)
    in
    for _ = 1 to not_filled do
      Format.pp_print_string ppf utf8_chars.(0)
    done );
  Format.pp_print_string ppf "│"

let bar_ascii width proportion ppf =
  let bar_width = width () - 2 in
  let filled =
    min (Float.to_int (Float.of_int bar_width *. proportion)) bar_width
  in
  let not_filled = bar_width - filled in
  Format.pp_print_char ppf '[';
  for _ = 1 to filled do
    Format.pp_print_char ppf '#'
  done;
  for _ = 1 to not_filled do
    Format.pp_print_char ppf '.'
  done;
  Format.fprintf ppf "]"

let bar ~mode = match mode with `UTF8 -> bar_unicode | `ASCII -> bar_ascii
let ( ++ ) a b = Group [| a; b |]

let bar ~mode ?(width = `Expand) f =
  match width with
  | `Fixed width ->
      if width < 3 then failwith "Not enough space for a progress bar";
      Contramap (of_pp ~width (Fun.flip (bar ~mode (fun _ -> width))), f)
  | `Expand ->
      let pp ~width = Fun.flip (bar ~mode width) in
      Contramap (Pp_unsized { pp } ++ const " " ++ Units.percentage of_pp, f)

(** [ticker n] is a function [f] that returns [true] on every [n]th call. *)
let ticker interval : unit -> bool =
  let ticker = ref 0 in
  fun () ->
    ticker := (!ticker + 1) mod interval;
    !ticker = 0

let stateful f = Staged f

let periodic interval t =
  match interval with
  | n when n <= 0 -> Format.kasprintf invalid_arg "Non-positive interval: %d" n
  | 1 -> t
  | _ ->
      stateful (fun () ->
          let should_update = ticker interval in
          Cond { if_ = should_update; then_ = t })

let accumulator combine zero s =
  stateful (fun () ->
      let state = ref zero in
      Contramap
        ( s,
          fun a ->
            state := combine !state a;
            !state ))

let box_dynamic width contents = Box { contents; width }
let box_fixed width = box_dynamic (ref width)
let box_winsize ~fallback s = box_dynamic (Width.default ~fallback) s
let pair ?(sep = const "") a b = Pair { left = a; sep; right = b }

let list ?(sep = const "  ") =
  List.intersperse ~sep >> Array.of_list >> fun xs -> Group xs

let using f t = Contramap (t, f)

(** The [unstage] step transforms a pure [t] term in to a potentially-impure
    [unstaged] term to be used for a single display lifecycle. It has three
    purposes:

    - eliminate [Staged] nodes by executing any side-effects in preparation for
      display;
    - compute the available widths of any unsized nodes;
    - inline nested groupings to make printing more efficient. *)

type 'a compiled =
  | Pp of { pp : Format.formatter -> 'a -> unit; mutable latest : 'a }
  | Const of { pp : Format.formatter -> unit }
  | Contramap : 'a compiled * ('b -> 'a) -> 'b compiled
  | Cond of 'a compiled cond
  | Group of 'a compiled array
  | Pair : {
      left : 'a compiled;
      sep : unit compiled;
      right : 'b compiled;
    }
      -> ('a * 'b) compiled

type 'a state = {
  consumed : int;
  expand : unit -> int;
  expansion_occurred : bool;
  initial : 'a;
}

let array_fold_left_map f acc input_array =
  let len = Array.length input_array in
  if len = 0 then (acc, [||])
  else
    let acc, elt = f acc (Array.unsafe_get input_array 0) in
    let output_array = Array.make len elt in
    let acc = ref acc in
    for i = 1 to len - 1 do
      let acc', elt = f !acc (Array.unsafe_get input_array i) in
      acc := acc';
      Array.unsafe_set output_array i elt
    done;
    (!acc, output_array)

let compile =
  let rec inner : type a. a state -> a t -> a compiled * a state =
   fun state -> function
    | Const { pp; width } ->
        (* TODO: join adjacent [Const] nodes as an optimisation step*)
        (Const { pp }, { state with consumed = state.consumed + width })
    | Pp_unsized { pp } ->
        if state.expansion_occurred then
          invalid_arg
            "Multiple expansion points encountered. Cannot pack two unsized \
             segments in a single box.";
        ( Pp { pp = pp ~width:state.expand; latest = state.initial },
          { state with expansion_occurred = true } )
    | Pp_fixed { pp; width } ->
        ( Pp { pp; latest = state.initial },
          { state with consumed = state.consumed + width } )
    | Contramap (t, f) ->
        let initial_a = state.initial in
        let inner, state = inner { state with initial = f initial_a } t in
        (Contramap (inner, f), { state with initial = initial_a })
    | Cond { if_; then_ } ->
        let then_, state = inner state then_ in
        (Cond { if_; then_ }, state)
    | Staged s -> inner state (s ())
    | Box { contents; width } ->
        let f = ref (fun () -> assert false) in
        let expand () = !f () in
        let inner, state =
          inner { state with expand; expansion_occurred = false } contents
        in
        (f := fun () -> !width - state.consumed);
        (inner, { state with expansion_occurred = true })
    | Group g ->
        let state, g =
          array_fold_left_map
            (fun state elt ->
              let b, a = inner state elt in
              (a, b))
            state g
        in
        let rec aux :
            type a.
            a state -> a compiled array -> a state * a compiled list list =
         fun state g ->
          Array.fold_left
            (fun (state, acc) -> function
              | Group g ->
                  let state, acc' = aux state g in
                  (state, acc' @ acc) | a -> (state, [ a ] :: acc))
            (state, []) g
        in
        let state, inners = g |> aux state in
        let inners = inners |> List.rev |> List.concat |> Array.of_list in
        (Group inners, state)
    | Pair { left; sep; right } ->
        let initial = state.initial in
        let left, state = inner { state with initial = fst initial } left in
        let sep, state = inner { state with initial = () } sep in
        let right, state = inner { state with initial = snd initial } right in
        (Pair { left; sep; right }, { state with initial })
  in
  fun ~initial x ->
    inner
      {
        consumed = 0;
        expand =
          (fun () ->
            Format.kasprintf invalid_arg
              "Encountered an expanding element that is not contained in a box");
        expansion_occurred = false;
        initial;
      }
      x
    |> fst

let report compiled =
  let rec aux : type a. a compiled -> (Format.formatter -> a -> unit) staged =
    function
    | Const { pp } -> stage (fun ppf (_ : a) -> pp ppf)
    | Pp pp ->
        stage (fun ppf x ->
            pp.latest <- x;
            pp.pp ppf x)
    | Contramap (t, f) ->
        let$ inner = aux t in
        fun ppf a -> inner ppf (f a)
    | Cond { if_; then_ } ->
        let$ then_ = aux then_ in
        fun ppf x -> if if_ () then then_ ppf x else ()
    | Group g ->
        let reporters = Array.map (aux >> unstage) g in
        stage (fun ppf v -> Array.iter (fun f -> f ppf v) reporters)
    | Pair { left; sep; right } ->
        let$ left = aux left and$ sep = aux sep and$ right = aux right in
        fun ppf (v_left, v_right) ->
          left ppf v_left;
          sep ppf ();
          right ppf v_right
  in
  unstage (aux compiled)

let update compiled =
  let rec aux : type a. a compiled -> (Format.formatter -> unit) staged =
    function
    | Const { pp } -> stage pp
    | Pp pp -> stage (fun ppf -> pp.pp ppf pp.latest)
    (* Updating happens unconditionally *)
    | Cond { if_ = _; then_ } -> aux then_
    | Contramap (inner, _) -> aux inner
    | Group g ->
        let updaters = Array.map (aux >> unstage) g in
        stage (fun ppf -> Array.iter (fun f -> f ppf) updaters)
    | Pair { left; sep; right } ->
        let$ left = aux left and$ sep = aux sep and$ right = aux right in
        fun ppf ->
          left ppf;
          sep ppf;
          right ppf
  in
  unstage (aux compiled)