File: spinner.rb

package info (click to toggle)
ruby-tty-spinner 0.9.3-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, trixie
  • size: 124 kB
  • sloc: ruby: 728; makefile: 4
file content (571 lines) | stat: -rw-r--r-- 12,237 bytes parent folder | download
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
# frozen_string_literal: true

require 'monitor'
require 'tty-cursor'

require_relative 'spinner/version'
require_relative 'spinner/formats'

module TTY
  # Used for creating terminal spinner
  #
  # @api public
  class Spinner
    include Formats
    include MonitorMixin

    # @raised when attempting to join dead thread
    NotSpinningError = Class.new(StandardError)

    ECMA_CSI = "\x1b["

    MATCHER = /:spinner/
    TICK = '✔'
    CROSS = '✖'

    CURSOR_LOCK = Monitor.new

    # The object that responds to print call defaulting to stderr
    #
    # @api public
    attr_reader :output

    # The current format type
    #
    # @return [String]
    #
    # @api public
    attr_reader :format

    # Whether to show or hide cursor
    #
    # @return [Boolean]
    #
    # @api public
    attr_reader :hide_cursor

    # The message to print before the spinner
    #
    # @return [String]
    #   the current message
    #
    # @api public
    attr_reader :message

    # Tokens for the message
    #
    # @return [Hash[Symbol, Object]]
    #   the current tokens
    #
    # @api public
    attr_reader :tokens

    # The amount of time between frames in auto spinning
    #
    # @api public
    attr_reader :interval

    # The current row inside the multi spinner
    #
    # @api public
    attr_reader :row

    # Initialize a spinner
    #
    # @example
    #   spinner = TTY::Spinner.new
    #
    # @param [String] message
    #   the message to print in front of the spinner
    #
    # @param [Hash] options
    # @option options [String] :format
    #   the spinner format type defaulting to :spin_1
    # @option options [Object] :output
    #   the object that responds to print call defaulting to stderr
    # @option options [Boolean] :hide_cursor
    #   display or hide cursor
    # @option options [Boolean] :clear
    #   clear ouptut when finished
    # @option options [Float] :interval
    #   the interval for auto spinning
    #
    # @api public
    def initialize(*args)
      super()
      options  = args.last.is_a?(::Hash) ? args.pop : {}
      @message = args.empty? ? ':spinner' : args.pop
      @tokens  = {}

      @format      = options.fetch(:format) { :classic }
      @output      = options.fetch(:output) { $stderr }
      @hide_cursor = options.fetch(:hide_cursor) { false }
      @frames      = options.fetch(:frames) do
                       fetch_format(@format.to_sym, :frames)
                     end
      @clear       = options.fetch(:clear) { false }
      @success_mark= options.fetch(:success_mark) { TICK }
      @error_mark  = options.fetch(:error_mark) { CROSS }
      @interval    = options.fetch(:interval) do
                       fetch_format(@format.to_sym, :interval)
                     end
      @row         = options[:row]

      @callbacks   = Hash.new { |h, k| h[k] = [] }
      @length      = @frames.length
      @thread      = nil
      @job         = nil
      @multispinner= nil
      reset
    end

    # Reset the spinner to initial frame
    #
    # @api public
    def reset
      synchronize do
        @current   = 0
        @done      = false
        @state     = :stopped
        @succeeded = false
        @first_run = true
      end
    end

    # Notifies the TTY::Spinner that it is running under a multispinner
    #
    # @param [TTY::Spinner::Multi] the multispinner that it is running under
    #
    # @api private
    def attach_to(multispinner)
      @multispinner = multispinner
    end

    # Whether the spinner has completed spinning
    #
    # @return [Boolean] whether or not the spinner has finished
    #
    # @api public
    def done?
      @done
    end

    # Whether the spinner is spinning
    #
    # @return [Boolean] whether or not the spinner is spinning
    #
    # @api public
    def spinning?
      @state == :spinning
    end

    # Whether the spinner is in the success state.
    # When true the spinner is marked with a success mark.
    #
    # @return [Boolean] whether or not the spinner succeeded
    #
    # @api public
    def success?
      @succeeded == :success
    end

    # Whether the spinner is in the error state. This is only true
    # temporarily while it is being marked with a failure mark.
    #
    # @return [Boolean] whether or not the spinner is erroring
    #
    # @api public
    def error?
      @succeeded == :error
    end

    # Register callback
    #
    # @param [Symbol] name
    #   the name for the event to listen for, e.i. :complete
    #
    # @return [self]
    #
    # @api public
    def on(name, &block)
      synchronize do
        @callbacks[name] << block
      end
      self
    end

    # Start timer and unlock spinner
    #
    # @api public
    def start
      @started_at = Time.now
      @done = false
      reset
    end

    # Add job to this spinner
    #
    # @api public
    def job(&work)
      synchronize do
        if block_given?
          @job = work
        else
          @job
        end
      end
    end

    # Execute this spinner job
    #
    # @yield [TTY::Spinner]
    #
    # @api public
    def execute_job
      job.(self) if job?
    end

    # Check if this spinner has a scheduled job
    #
    # @return [Boolean]
    #
    # @api public
    def job?
      !@job.nil?
    end

    # Start automatic spinning animation
    #
    # @api public
    def auto_spin
      CURSOR_LOCK.synchronize do
        start
        sleep_time = 1.0 / @interval

        spin
        @thread = Thread.new do
          sleep(sleep_time)
          while @started_at
            if Thread.current['pause']
              Thread.stop
              Thread.current['pause'] = false
            end
            spin
            sleep(sleep_time)
          end
        end
      end
    ensure
      if @hide_cursor
        write(TTY::Cursor.show, false)
      end
    end

    # Checked if current spinner is paused
    #
    # @return [Boolean]
    #
    # @api public
    def paused?
      !!(@thread && @thread['pause'])
    end

    # Pause spinner automatic animation
    #
    # @api public
    def pause
      return if paused?

      synchronize do
        @thread['pause'] = true if @thread
      end
    end

    # Resume spinner automatic animation
    #
    # @api public
    def resume
      return unless paused?

      @thread.wakeup if @thread
    end

    # Run spinner while executing job
    #
    # @param [String] stop_message
    #   the message displayed when block is finished
    #
    # @yield automatically animate and finish spinner
    #
    # @example
    #   spinner.run('Migrated DB') { ... }
    #
    # @api public
    def run(stop_message = '', &block)
      job(&block)
      auto_spin

      @work = Thread.new { execute_job }
      @work.join
    ensure
      stop(stop_message)
    end

    # Duration of the spinning animation
    #
    # @return [Numeric]
    #
    # @api public
    def duration
      @started_at ? Time.now - @started_at : nil
    end

    # Join running spinner
    #
    # @param [Float] timeout
    #   the timeout for join
    #
    # @api public
    def join(timeout = nil)
      unless @thread
        raise(NotSpinningError, 'Cannot join spinner that is not running')
      end

      timeout ? @thread.join(timeout) : @thread.join
    end

    # Kill running spinner
    #
    # @api public
    def kill
      synchronize do
        @thread.kill if @thread
      end
    end

    # Perform a spin
    #
    # @return [String]
    #   the printed data
    #
    # @api public
    def spin
      synchronize do
        return if @done
        emit(:spin)

        if @hide_cursor && !spinning?
          write(TTY::Cursor.hide)
        end

        data = message.gsub(MATCHER, @frames[@current])
        data = replace_tokens(data)
        write(data, true)
        @current = (@current + 1) % @length
        @state = :spinning
        data
      end
    end

    # Redraw the indent for this spinner, if it exists
    #
    # @api private
    def redraw_indent
      if @hide_cursor && !spinning?
        write(TTY::Cursor.hide)
      end

      write("", false)
    end

    # Finish spining
    #
    # @param [String] stop_message
    #   the stop message to print
    #
    # @api public
    def stop(stop_message = '')
      mon_enter
      return if done?

      clear_line
      return if @clear

      data = message.gsub(MATCHER, next_char)
      data = replace_tokens(data)
      if !stop_message.empty?
        data << ' ' + stop_message
      end

      write(data, false)
      write("\n", false) unless @clear || @multispinner
    ensure
      @state      = :stopped
      @done       = true
      @started_at = nil

      if @hide_cursor
        write(TTY::Cursor.show, false)
      end

      emit(:done)
      kill
      mon_exit
    end

    # Retrieve next character
    #
    # @return [String]
    #
    # @api private
    def next_char
      if success?
        @success_mark
      elsif error?
        @error_mark
      else
        @frames[@current - 1]
      end
    end

    # Finish spinning and set state to :success
    #
    # @api public
    def success(stop_message = '')
      return if done?

      synchronize do
        @succeeded = :success
        stop(stop_message)
        emit(:success)
      end
    end

    # Finish spinning and set state to :error
    #
    # @api public
    def error(stop_message = '')
      return if done?

      synchronize do
        @succeeded = :error
        stop(stop_message)
        emit(:error)
      end
    end

    # Clear current line
    #
    # @api public
    def clear_line
      write(ECMA_CSI + '0m' + TTY::Cursor.clear_line)
    end

    # Update string formatting tokens
    #
    # @param [Hash[Symbol]] tokens
    #   the tokens used in formatting string
    #
    # @api public
    def update(tokens)
      synchronize do
        clear_line if spinning?
        @tokens.merge!(tokens)
      end
    end

    private

    # Execute a block on the proper terminal line if the spinner is running
    # under a multispinner. Otherwise, execute the block on the current line.
    #
    # @api private
    def execute_on_line
      if @multispinner
        @multispinner.synchronize do
          if @first_run
            @row ||= @multispinner.next_row
            yield if block_given?
            output.print "\n"
            @first_run = false
          else
            lines_up = (@multispinner.rows + 1) - @row
            output.print TTY::Cursor.save
            output.print TTY::Cursor.up(lines_up)
            yield if block_given?
            output.print TTY::Cursor.restore
          end
        end
      else
        yield if block_given?
      end
    end

    # Write data out to output
    #
    # @return [nil]
    #
    # @api private
    def write(data, clear_first = false)
      return unless tty? # write only to terminal

      execute_on_line do
        output.print(TTY::Cursor.column(1)) if clear_first
        # If there's a top level spinner, print with inset
        characters_in = @multispinner.line_inset(@row) if @multispinner
        output.print("#{characters_in}#{data}")
        output.flush
      end
    end

    # Check if IO is attached to a terminal
    #
    # return [Boolean]
    #
    # @api public
    def tty?
      output.respond_to?(:tty?) && output.tty?
    end

    # Emit callback
    #
    # @api private
    def emit(name, *args)
      @callbacks[name].each do |callback|
        callback.call(*args)
      end
    end

    # Find frames by token name
    #
    # @param [Symbol] token
    #   the name for the frames
    #
    # @return [Array, String]
    #
    # @api private
    def fetch_format(token, property)
      if FORMATS.key?(token)
        FORMATS[token][property]
      else
        raise ArgumentError, "Unknown format token `:#{token}`"
      end
    end

    # Replace any token inside string
    #
    # @param [String] string
    #   the string containing tokens
    #
    # @return [String]
    #
    # @api private
    def replace_tokens(string)
      data = string.dup
      @tokens.each do |name, val|
        data.gsub!(/\:#{name}/, val.to_s)
      end
      data
    end
  end # Spinner
end # TTY