lib/progressbar.rb in progressbar_zobar-0.9.1.1 vs lib/progressbar.rb in progressbar_zobar-0.9.2.1
- old
+ new
@@ -27,17 +27,19 @@
@format = "%-#{@title_width}s %3d%% %s %s"
@format_arguments = [:title, :percentage, :bar, :stat]
clear
show
end
+
attr_reader :title
attr_reader :current
attr_reader :total
attr_accessor :start_time
attr_writer :bar_mark
- private
+private
+
def fmt_bar
bar_width = do_percentage * @terminal_width / 100
sprintf("|%s%s|",
@bar_mark * bar_width,
" " * (@terminal_width - bar_width))
@@ -118,35 +120,37 @@
else
@current * 100 / @total
end
end
- def get_width
- # FIXME: I don't know how portable it is.
- default_width = 80
- begin
- tiocgwinsz = 0x5413
- data = [0, 0, 0, 0].pack("SSSS")
- if @out.ioctl(tiocgwinsz, data) >= 0 then
- rows, cols, xpixels, ypixels = data.unpack("SSSS")
- if cols >= 0 then cols else default_width end
- else
- default_width
- end
- rescue Exception
- default_width
+ DEFAULT_WIDTH = 80
+ def get_term_width
+ if ENV['COLUMNS'] =~ /^\d+$/
+ ENV['COLUMNS'].to_i
+ elsif (RUBY_PLATFORM =~ /java/ || (!STDIN.tty? && ENV['TERM'])) && shell_command_exists?('tput')
+ `tput cols`.to_i
+ elsif STDIN.tty? && shell_command_exists?('stty')
+ `stty size`.scan(/\d+/).map { |s| s.to_i }[1]
+ else
+ DEFAULT_WIDTH
end
+ rescue
+ DEFAULT_WIDTH
end
+ def shell_command_exists?(command)
+ ENV['PATH'].split(File::PATH_SEPARATOR).any?{|d| File.exists? File.join(d, command) }
+ end
+
def show
arguments = @format_arguments.map {|method|
method = sprintf("fmt_%s", method)
send(method)
}
line = sprintf(@format, *arguments)
- width = get_width
+ width = get_term_width
if line.length == width - 1
@out.print(line + eol)
@out.flush
elsif line.length >= width
@terminal_width = [@terminal_width - (line.length - width + 1), 0].max
@@ -175,14 +179,15 @@
Time.now - @previous_time >= 1 || @finished_p
show
end
end
- public
+public
+
def clear
@out.print "\r"
- @out.print(" " * (get_width - 1))
+ @out.print(" " * (get_term_width - 1))
@out.print "\r"
end
def finish
@current = @total
@@ -226,12 +231,14 @@
show_if_needed
@previous = @current
end
def title= (value)
- @title = value
- show
+ unless @title == value
+ @title = value
+ show
+ end
end
def total= (value)
@prev_total = total
@total = value
@@ -240,9 +247,10 @@
end
def inspect
"#<ProgressBar:#{@current}/#{@total}>"
end
+
end
class ReversedProgressBar < ProgressBar
def do_percentage
100 - super