Source file line_intf.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
(*————————————————————————————————————————————————————————————————————————————
   Copyright (c) 2020–2021 Craig Ferguson <me@craigfe.io>
   Distributed under the MIT license. See terms at the end of this file.
  ————————————————————————————————————————————————————————————————————————————*)

open! Import

(** These values are documented as part of {!DSL}.*)
module type Integer_dependent = sig
  type integer
  type color
  type duration
  type 'a printer
  type bar_style

  (**)
  type 'a t

  val sum : ?pp:integer printer -> width:int -> unit -> integer t
  val count_to : ?pp:integer printer -> ?sep:unit t -> integer -> integer t
  val bytes : integer t
  val bytes_per_sec : integer t
  val percentage_of : integer -> integer t
  val rate : float printer -> integer t
  val eta : ?pp:duration printer -> integer -> integer t

  type bar_style := [ `ASCII | `UTF8 | `Custom of bar_style ]

  val bar :
       ?style:bar_style
    -> ?color:color
    -> ?width:[ `Fixed of int | `Expand ]
    -> ?data:[ `Sum | `Latest ]
    -> integer
    -> integer t
end

(** The 'main' set of combinators, specialised to a particular integer type. *)
module type DSL = sig
  type integer
  type color
  type duration
  type 'a printer

  type 'a t
  (** The type of progress lines for reported values of type ['a]. This module
      provides a selection of {{!basic} individual line segments} that can be
      {{!combinators} combined} to produce more interesting layouts. You may
      wish to look over the {{!examples} examples} for inspiration. *)

  (** {1:basic Basic line segments} *)

  val const : string -> _ t
  (** [const s] is the segment that always displays [s]. *)

  val constf : ('a, Format.formatter, unit, _ t) format4 -> 'a
  (** Like {!const}, but takes a format string and corresponding arguments.
      [constf "..." a b c ...] is equivalent to
      [const (Format.asprintf "..." a b c ...)], except that colours added with
      [Fmt.styled] are not discarded. *)

  val string : string t
  (** A line segment that displays a dynamically-sized string message. Use
      {!lpad} and {!rpad} to pad the message up to a given length. *)

  val lpad : int -> 'a t -> 'a t
  (** [lpad n t] left-pads the segment [t] to size [n] by adding blank space at
      the start. *)

  val rpad : int -> 'a t -> 'a t
  (** [rpad n t] right-pads the segment [t] to size [n] by adding blank space at
      the end. *)

  val of_printer : ?init:'a -> 'a printer -> 'a t
  (** [of_printer p] is a segment that renders the {i latest} reported value
      using printer [p]. See {!sum} for a variant that reports accumulated
      values instead. *)

  (** {2:counting Counting segments}

      These segments all consume integer values and display the accumulated
      total of reported values in some way. The top-level [Line] segments are
      specialised to [int] values; see "{!integers}" for variants supporting
      [int32], [int64] etc. *)

  val count_to : ?pp:integer printer -> ?sep:unit t -> integer -> integer t
  (** [count_to target] renders both the current running total of reported
      values and the fixed value [target], separated by the the given separator,
      i.e. [42/100]. [sep] defaults to [const "/"]. *)

  val bytes : integer t
  (** Prints the running total as a number of bytes, using ISO/IEC binary
      prefixes (e.g. [10.4 MiB]). See also {!bytes_per_sec}. *)

  val percentage_of : integer -> integer t
  (** [percentage_of target] renders the running total as a percentage of
      [target], i.e. [42%]. Values outside the range [\[0, 100\]] will be
      clamped to either [0] or [100]. *)

  val sum : ?pp:integer printer -> width:int -> unit -> integer t
  (** [sum ~width ()] displays a running total of reported values using
      [width]-many terminal columns. If passed, [pp] overrides the printer used
      for rendering the count. *)

  (** {2:graphical Graphical segments} *)

  module Bar_style : sig
    type t
    (** The type of progress bar style specifications. *)

    val ascii : t
    (** The style used by [bar ~style:`ASCII] (which is the default). Generates
        bars of the form [\[######---\]]. *)

    val utf8 : t
    (** {!utf8} is the style used by [bar ~style:`UTF8]. Uses the UTF-8 block
        element characters ([U+2588]–[U+258F]) for progress stages, and a
        box-drawing character ([U+2502]) for delimiters. *)

    (** {1 Custom styles} *)

    val v :
         ?delims:string * string
      -> ?color:color
      -> ?color_empty:color
      -> string list
      -> t

    (** [v stages] is a bar that uses the given string {i stages} to render
        progress. The first stage is interpreted as a "full" segment, with
        subsequent stages denoting progressively {i less}-full segments until a
        final "empty" stage (which is implicitly a space if only one stage is
        provided).

        The optional parameters are as follows:

        - [?delims]: a pair of left and right delimiters used to wrap the body
          of the progress bar;
        - [?color]: the color of non-empty segments (including the in-progress
          one);
        - [?color_empty]: the color of empty segments.

        {2 Examples}

        - [v \[ "#" \]] renders like "[#######   ]";
        - [v \[ "="; ">"; " " \]] renders like "[======>    ]";
        - [v \[ "4"; "3"; "2"; "1"; "0" \]] renders like "[444444410000]";
        - ... see [examples/bar_styles.ml] in the source repository for more.

        {2 Specifics}

        Each segment of a rendering progress bar is in one of three states:
        full, empty or in-progress. At any given time, either the bar is
        entirely full or or there is exactly one in-progress segment. Given the
        style [v \[s1; s2; ... sN\]], these states are rendered as follows:

        - {b full}: rendered as [s1];
        - {b empty}: rendered as [sN] if [N >= 1], otherwise [' '];
        - {b in-progress}: if [N <= 1], then equivalent to the empty state.
          Otherwise, the intermediate stages [s2], [s3], ... [s{N-1}] denote
          decreasing progress. For example, if there are four intermediate
          stages ([N = 6]) then [s2] is used for progress in the range
          [\[0, 25%)], [s3] for [\[25%, 50%)] etc.

        For the progress bar to render within a fixed size, the user must ensure
        that each of the [stages] must have the same rendered width. *)

    (** {1 Setters} *)

    val with_color : color -> t -> t
    val with_empty_color : color -> t -> t
    val with_delims : (string * string) option -> t -> t
    val with_stages : string list -> t -> t
  end

  val bar :
       ?style:[ `ASCII | `UTF8 | `Custom of Bar_style.t ]
    -> ?color:color
    -> ?width:[ `Fixed of int | `Expand ]
    -> ?data:[ `Sum | `Latest ]
    -> integer
    -> integer t
  (** [bar total] is a progress bar of the form:
      [\[#################...............\]]

      The proportion of the bar that is filled is given by
      [<reported_so_far> / total]. Optional parameters are as follows:

      - [?style] specifies whether to use a UTF-8 or an ASCII encoding for the
        progress bar. The UTF-8 encoding shows a higher resolution of progress,
        but may not be supported in all terminals. The default is [`ASCII].

      - [?color] causes the filled portion of the bar to be rendered with the
        given colour. (Equivalent to setting the colour with
        {!Bar_style.with_color}.)

      - [?width] is the width of the bar in columns. Defaults to [`Expand],
        which causes the bar to occupy the remaining rendering space after
        accounting for other line segments on the same line.

      - [?data] changes the metric that is indicated by the progress bar. [`Sum]
        (the default) causes the progress bar to correspond to the
        {i running total} of values reported so far. [`Latest] causes each
        reported value to overwrite the previous one instead. *)

  val spinner :
       ?frames:string list
    -> ?color:color
    -> ?min_interval:duration option
    -> unit
    -> _ t
  (** [spinner ()] is a small segment that cycles over a fixed number of frames
      each time a value is reported. e.g.

      {[
        ⠋ → ⠙ → ⠹ → ⠸ → ⠼ → ⠴ → ⠦ → ⠧ → ⠇ → ⠏ → ...
      ]}

      Optional prameters are as follows:

      - [?frames] alters the sequence of frames rendered by the spinner;
      - [?color] causes each frame to be rendered with the given colour;
      - [?min_interval] is the minimum time interval between frame transitions
        of the spinner (i.e. a debounce threshold). The default is [Some 80ms]. *)

  (** {2:time Time-sensitive segments} *)

  val bytes_per_sec : integer t
  (** [bytes_per_sec] renders the rate of change of the running total as a
      number of bytes per second, using ISO/IEC binary prefixes (e.g.
      [10.4 MiB/s]). *)

  val elapsed : ?pp:duration printer -> unit -> _ t
  (** Displays the time for which the bar has been rendering in [MM:SS] form. *)

  val eta : ?pp:duration printer -> integer -> integer t
  (** Displays an estimate of the remaining time until [total] is accumulated by
      the reporters, in [MM:SS] form. *)

  val rate : float printer -> integer t
  (** [rate pp] is an integer segment that uses [pp] to print the {i rate} of
      reported values per second. (For instance, [bytes_per_sec] is
      [rate Units.Bytes.of_float].)*)

  (** {1:combinators Combining segments} *)

  val ( ++ ) : 'a t -> 'a t -> 'a t
  (** Horizontally join two segments of the same reported value type. *)

  val list : ?sep:'a t -> 'a t list -> 'a t
  (** Horizontally join a list of segments, with a given separator. [sep]
      defaults to [const " "]. *)

  val pair : ?sep:unit t -> 'a t -> 'b t -> ('a * 'b) t
  (** Horizontally join a pair of segments consuming different reported values
      into a single segment that consumes a pair. *)

  val using : ('a -> 'b) -> 'b t -> 'a t
  (** [using f s] is a segment that first applies [f] to the reported value and
      then behaves as segment [s]. *)

  (** {1 Utilities}

      The following line segments are definable in terms of the others, but
      provided for convenience: *)

  val parens : 'a t -> 'a t
  (** [parens t] is [const "(" ++ t ++ const ")"]. *)

  val brackets : 'a t -> 'a t
  (** [brackets t] is [const "\[" ++ t ++ const "\]"]. *)

  val braces : 'a t -> 'a t
  (** [braces t] is [const "{" ++ t ++ const "}"]. *)

  val noop : unit -> _ t
  (** A zero-width line segment that does nothing. This segment will not be
      surrounded with separators when used in a {!list}, making it a useful
      "off" state for conditionally-enabled segments. *)

  val spacer : int -> _ t
  (** [spacer n] is [const (String.make n ' ')]. *)

  val ticker_to : ?sep:unit t -> integer -> _ t
  (** [ticker_to total] is [using ~f:(fun _ -> 1) (counter_to total)]. i.e. it
      renders the total {i number} of reported values of some arbitrary type. *)
end

module Assert_subtype (X : DSL) :
  Integer_dependent with type bar_style := X.Bar_style.t =
  X

module type S = sig
  include DSL with type integer := int
  (** @inline *)

  (** {1:integers Alternative integer types}

      Many of the line segments above are specialised to [int] values for
      simplicity (and performance), but certain use-cases may require different
      types (e.g. for file transfers greater than [2 GiB] on 32-bit platforms).
      The following modules re-export the [Line] DSL with different integer
      specialisations, and are intended to be opened locally, e.g.

      {[
        let my_line =
          let open Progress.Line.Using_int64 in
          list [ const "Downloading large file"; bar total; bytes ]
      ]} *)

  module Integer_dependent : sig
    (** {!S} contains just the line segments that can be specialised to an
        underlying integer implementation. *)
    module type S =
      Integer_dependent
        with type 'a t := 'a t
         and type color := color
         and type duration := duration
         and type 'a printer := 'a printer
         and type bar_style := Bar_style.t

    module Make (Integer : Integer.S) : S with type integer := Integer.t

    (** {!Ext} is {!S} extended with non-integer-dependent segments as well. *)
    module type Ext =
      DSL
        with type 'a t := 'a t
         and type color := color
         and type duration := duration
         and type 'a printer := 'a printer
         and type Bar_style.t := Bar_style.t
  end

  module Using_int32 : Integer_dependent.Ext with type integer := int32
  module Using_int63 : Integer_dependent.Ext with type integer := int63
  module Using_int64 : Integer_dependent.Ext with type integer := int64
  module Using_float : Integer_dependent.Ext with type integer := float

  (** {1:examples Examples}

      {[
        (* Renders: "[######---------------------------------------]  14/100" *)
        bar 100 ++ const " " ++ count_to 100
      ]}
      {[
        (* Renders: "⠏ [01:04] [####-----------------]  293.9 MiB (eta: 07:12)" *)
        list
          [ spinner ()
          ; brackets (elapsed ())
          ; bar total
          ; bytes
          ; parens (const "eta: " ++ eta total)
          ]
      ]}
      {[
        (* Renders: "  a.txt │██████████████████████████▋   │   91.4 MiB/s  92%" *)
        list
          [ lpad 7 (const file_name)
          ; bar ~style:`UTF8 total
          ; bytes_per_sec
          ; percentage_of total
          ]
      ]}

      See the [examples/] directory of the source repository for more. *)

  (** {1 Library internals} *)

  module Internals : sig
    (** Exposes the underlying implementation of line segments for testing. This
        API is unstable, unsafe and mostly undocumented; here be dragons etc. *)

    type 'a line

    module Line_buffer = Line_buffer

    include Line_primitives.S with type 'a t = 'a Line_primitives.t
    (** @inline *)

    val box_winsize : ?max:int -> ?fallback:int -> 'a t -> 'a t
    (** A box that takes on the current size of the terminal (or [fallback] if
        stdout is not attached to a terminal).

        @param fallback defaults to [80].
        @param max defaults to no limit. *)

    val to_line : 'a t -> 'a line
  end
  with type 'a line := 'a t
end

module type Line = sig
  module type S = S

  type 'a t

  module Make (_ : Platform.S) : sig
    include
      S
        with type 'a t := 'a t
         and type color := Terminal.Color.t
         and type duration := Duration.t
         and type 'a printer := 'a Printer.t

    val to_primitive : Config.t -> 'a t -> 'a Internals.t
  end
end

(*————————————————————————————————————————————————————————————————————————————
   Copyright (c) 2020–2021 Craig Ferguson <me@craigfe.io>

   Permission to use, copy, modify, and/or distribute this software for any
   purpose with or without fee is hereby granted, provided that the above
   copyright notice and this permission notice appear in all copies.

   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.
  ————————————————————————————————————————————————————————————————————————————*)