yorha 1.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,192 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Capability detection for the YoRHa gem (Foundation layer).
4
+ #
5
+
6
+
7
+ module Yorha
8
+ module Terminal
9
+ class << self
10
+ # Reports the richest colour depth the stream can display.
11
+
12
+ def color_depth(io = Yorha.config.io)
13
+ configured = configured_color_depth
14
+ return configured unless configured.nil?
15
+
16
+ return :none if ENV.key?("NO_COLOR")
17
+ return force_color_depth if ENV.key?("FORCE_COLOR")
18
+ return :none unless tty?(io)
19
+ return :none if ENV["TERM"] == "dumb"
20
+ return :truecolor if truecolor_terminal?
21
+ return windows_color_depth if windows?
22
+ return :ansi256 if ENV["TERM"].to_s.include?("256color")
23
+
24
+ :ansi16
25
+ rescue StandardError
26
+ # Never raise: a stream that cannot be inspected gets no colour.
27
+ :none
28
+ end
29
+
30
+ # Reports whether Unicode glyphs and Japanese text are safe to use.
31
+
32
+
33
+ def unicode?(io = Yorha.config.io)
34
+ configured = Yorha.config.unicode
35
+ return configured unless configured.nil?
36
+
37
+ return true if ENV.key?("WT_SESSION")
38
+ return false if non_unicode_locale?
39
+ return false unless external_encoding(io) == Encoding::UTF_8
40
+ return false if windows? && !console_utf8?
41
+
42
+ true
43
+ rescue StandardError
44
+ # Never raise: when in doubt, take the ASCII path.
45
+ false
46
+ end
47
+
48
+ # Reports how many columns wide the output area is.
49
+ #
50
+ # The sources are tried in this order:
51
+ #
52
+ # 1. ENV["COLUMNS"], when it is a positive number. This lets a
53
+ # person or a spec choose the width.
54
+ # 2. The console size reported by io.winsize, when io has one.
55
+ # 3. 80, the conventional terminal width.
56
+ #
57
+ # @example
58
+ # Yorha::Terminal.width($stdout)
59
+ # # => 120
60
+ #
61
+ # @param io [#winsize] stream to inspect; defaults to
62
+ # Yorha.config.io
63
+ # @return [Integer] width in columns, always positive
64
+ # @api public
65
+ def width(io = Yorha.config.io)
66
+ environment_width = ENV["COLUMNS"].to_i
67
+ return environment_width if environment_width.positive?
68
+
69
+ # IO#winsize comes from io/console, part of Ruby's standard
70
+ # library. It is loaded here, the first time a width has to be
71
+ # measured, so a program that never measures one never loads
72
+ # it. Once loaded, IO has the method and this line does nothing.
73
+ require "io/console" unless IO.method_defined?(:winsize)
74
+
75
+ if io.respond_to?(:winsize)
76
+ # winsize returns [rows, columns]; index 1 is the columns.
77
+ terminal_width = io.winsize[1].to_i
78
+ return terminal_width if terminal_width.positive?
79
+ end
80
+
81
+ 80
82
+ rescue StandardError, LoadError
83
+ # Never raise: winsize fails on files and pipes, for example,
84
+ # and LoadError covers a Ruby build without io/console.
85
+ 80
86
+ end
87
+
88
+ private
89
+
90
+ # Translates Yorha.config.color into a colour depth (rule 1).
91
+ #
92
+ # true -> :truecolor (colour forced on)
93
+ # false -> :none (colour forced off)
94
+ # a depth -> that depth
95
+ # nil -> nil, meaning "not set, keep detecting"
96
+ #
97
+ # Any other value is also treated as not set.
98
+ #
99
+ # @return [Symbol, nil] configured depth, or nil when not set
100
+ def configured_color_depth
101
+ color = Yorha.config.color
102
+
103
+ case color
104
+ when true
105
+ :truecolor
106
+ when false
107
+ :none
108
+ when :truecolor, :ansi256, :ansi16, :none
109
+ color
110
+ end
111
+ end
112
+
113
+ # Translates ENV["FORCE_COLOR"] into a colour depth (rule 3).
114
+ #
115
+ # "0" -> :none
116
+ # "1" -> :ansi16
117
+ # "2" -> :ansi256
118
+ # anything else -> :truecolor ("3", "true", an empty value)
119
+
120
+ def force_color_depth
121
+ case ENV["FORCE_COLOR"]
122
+ when "0"
123
+ :none
124
+ when "1"
125
+ :ansi16
126
+ when "2"
127
+ :ansi256
128
+ else
129
+ :truecolor
130
+ end
131
+ end
132
+
133
+ # Checks whether the stream is an interactive terminal (rule 4).
134
+ #
135
+
136
+ def tty?(io)
137
+ io.respond_to?(:tty?) && io.tty?
138
+ end
139
+
140
+ # Checks whether the terminal advertises 24-bit colour (rule 6).
141
+
142
+ def truecolor_terminal?
143
+ %w[truecolor 24bit].include?(ENV["COLORTERM"].to_s.downcase)
144
+ end
145
+
146
+ # Checks whether Ruby is running on Windows.
147
+ #
148
+
149
+ def windows?
150
+ RUBY_PLATFORM.match?(/mswin|mingw|cygwin/)
151
+ end
152
+
153
+ # Chooses the colour depth for a Windows terminal (rule 7).
154
+ #
155
+
156
+ def windows_color_depth
157
+ return :truecolor if ENV.key?("WT_SESSION")
158
+ return :truecolor if ENV["ConEmuANSI"] == "ON"
159
+
160
+ :ansi16
161
+ end
162
+
163
+ # Finds the encoding text is converted to when written to io.
164
+ #
165
+
166
+ def external_encoding(io)
167
+ if io.respond_to?(:external_encoding) && io.external_encoding
168
+ io.external_encoding
169
+ else
170
+ Encoding.default_external
171
+ end
172
+ end
173
+
174
+ # Checks whether the locale is the plain C or POSIX locale.
175
+ #
176
+
177
+ def non_unicode_locale?
178
+ locale = %w[LC_ALL LC_CTYPE LANG].map { |key| ENV[key] }.find { |value| value && !value.empty? }
179
+ return false if locale.nil?
180
+ return false if locale.match?(/utf-?8/i)
181
+
182
+ locale.match?(/\A(?:C|POSIX)(?:[.@]|\z)/i)
183
+ end
184
+
185
+ # Checks whether the Windows console code page is UTF-8.
186
+
187
+ def console_utf8?
188
+ Encoding.find("locale") == Encoding::UTF_8
189
+ end
190
+ end
191
+ end
192
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Yorha
4
+ # The current semantic version of the YoRHa gem.
5
+ #
6
+ # The version follows this format:
7
+ #
8
+ # MAJOR.MINOR.PATCH
9
+
10
+ VERSION = "1.9.4"
11
+ end
@@ -0,0 +1,384 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Themed building blocks (Presentation layer).
4
+ #
5
+ # Design document reference: section 5.5, Yorha::Banner and Widgets.
6
+ #
7
+ # Responsibility:
8
+ # Compose Render output into the themed building blocks: bordered
9
+ # system message boxes, memory-slot progress bars, alert lines, and
10
+ # bordered tables.
11
+ #
12
+ # This file does not:
13
+ # - Embed raw glyphs outside the registration block below; every
14
+ # other glyph comes from Render's registry.
15
+ # - Sleep; only Banner animates.
16
+ # - Read configuration beyond default stream and unit lookups.
17
+ # - Depend on a width library; a small private helper counts
18
+ # East Asian wide characters as two columns (decision D7).
19
+ #
20
+ # Invariants:
21
+ # - Every method accepts io: and returns the String it wrote.
22
+ # - Coloured text is padded before painting, so escape bytes never
23
+ # disturb alignment.
24
+ # - Caller text is cleaned of control characters before drawing, so
25
+ # a message can never inject terminal escape sequences.
26
+
27
+ require_relative "terminal"
28
+ require_relative "render"
29
+
30
+ module Yorha
31
+ module Widgets
32
+ # Junction glyphs for bordered tables, registered through the
33
+ # public extension point so this file embeds no other raw glyphs.
34
+ Yorha::Render.register_glyph(:tee_left, "├", "+")
35
+ Yorha::Render.register_glyph(:tee_right, "┤", "+")
36
+ Yorha::Render.register_glyph(:tee_top, "┬", "-")
37
+ Yorha::Render.register_glyph(:tee_bottom, "┴", "-")
38
+ Yorha::Render.register_glyph(:cross, "┼", "+")
39
+
40
+ # Memory-slot count for progress bars. A fixed count keeps bars
41
+ # comparable across terminals of different widths, matching the
42
+ # game's memory-slot look.
43
+ SLOTS = 20
44
+
45
+ # Never render a box narrower than this, even on tiny terminals.
46
+ MINIMUM_WIDTH = 40
47
+
48
+ # Characters that occupy two terminal columns: Hangul Jamo,
49
+ # CJK punctuation, kana, CJK ideographs, Hangul syllables,
50
+ # compatibility ideographs, and fullwidth forms.
51
+ #
52
+ # Built from plain strings rather than a multi-line /x literal.
53
+ # Whitespace inside a bracket class is literal in Ruby even in
54
+ # extended mode, so a formatted literal would count every space
55
+ # as a wide character.
56
+ #
57
+ # @return [Regexp]
58
+ WIDE_CHARACTER = Regexp.new(
59
+ "[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF" \
60
+ "\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE6F\uFF00-\uFF60" \
61
+ "\uFFE0-\uFFE6\u{20000}-\u{3FFFD}]"
62
+ )
63
+
64
+ class << self
65
+ # Renders a bordered system message box.
66
+ #
67
+ # The title sits in the accent colour above a divider; body
68
+ # paragraphs wrap at word boundaries to the box width, which is
69
+ # clamped to [40, Terminal.width].
70
+ #
71
+ # Control characters in the title and body are replaced with "?"
72
+ # and tabs with a space, so the text cannot move the cursor or
73
+ # change colours.
74
+ #
75
+ # Japanese text has no spaces to wrap at, so keep it out of
76
+ # boxes; a long unbroken line overflows the border.
77
+ #
78
+ # sink: is an advanced escape hatch: it receives the written
79
+ # text instead of io. Black Box uses it to render reports as
80
+ # pure strings without writing them.
81
+ #
82
+ # @example
83
+ # Yorha::Widgets.system_message("NOTICE", "Backup complete.")
84
+ #
85
+ # @param title [Object] converted with to_s
86
+ # @param body [Object] converted with to_s; paragraphs split on
87
+ # newlines
88
+ # @param io [#write, nil] detection and default output stream
89
+ # @param width [Integer, nil] requested box width
90
+ # @param sink [#write, nil] write target overriding io
91
+ # @return [String] the full text written
92
+ # @api public
93
+ def system_message(title, body, io: nil, width: nil, sink: nil)
94
+ stream = io || Yorha.config.io
95
+ target = sink || stream
96
+
97
+ outer_width = box_width(width, stream)
98
+ inner = outer_width - 4
99
+
100
+ lines = [frame_row(:top_left, :top_right, outer_width, stream)]
101
+ lines << content_row(clean(title), inner, :accent, stream)
102
+ lines << divider_row(outer_width, stream)
103
+
104
+ body.to_s.split("\n", -1).each do |paragraph|
105
+ wrap(clean(paragraph), inner).each do |line|
106
+ lines << content_row(line, inner, :fg, stream)
107
+ end
108
+ end
109
+
110
+ lines << frame_row(:bottom_left, :bottom_right, outer_width, stream)
111
+
112
+ write(target, lines)
113
+ end
114
+
115
+ # Renders a memory-slot progress bar.
116
+ #
117
+ # The number of filled slots is the fraction value / max of the
118
+ # 20 slots, rounded to the nearest whole slot.
119
+ #
120
+ # @example
121
+ # Yorha::Widgets.progress("MEMORY", 14, 20)
122
+ #
123
+ # @param label [Object] converted with to_s
124
+ # @param value [Integer] filled slots numerator
125
+ # @param max [Integer] total slots denominator
126
+ # @param io [#write, nil] detection and default output stream
127
+ # @return [String] the full text written
128
+ # @api public
129
+ def progress(label, value, max, io: nil)
130
+ stream = io || Yorha.config.io
131
+
132
+ total = max.to_i
133
+ total = 1 if total < 1
134
+
135
+ filled = value.to_i.clamp(0, total)
136
+ slots = (filled * SLOTS).fdiv(total).round.clamp(0, SLOTS)
137
+
138
+ bar =
139
+ "#{Yorha::Render.glyph(:filled, io: stream) * slots}" \
140
+ "#{Yorha::Render.glyph(:empty, io: stream) * (SLOTS - slots)}"
141
+
142
+ text =
143
+ "#{Yorha::Render.paint(clean(label), :fg, io: stream)} " \
144
+ "#{Yorha::Render.paint(bar, :accent, io: stream)} " \
145
+ "#{Yorha::Render.paint("[#{filled}/#{total}]", :muted, io: stream)}"
146
+
147
+ write(stream, [text])
148
+ end
149
+
150
+ # Renders a danger-coloured alert line.
151
+ #
152
+ # @example
153
+ # Yorha::Widgets.alert("Disk almost full")
154
+ #
155
+ # @param text [Object] converted with to_s
156
+ # @param io [#write, nil] detection and default output stream
157
+ # @return [String] the full text written
158
+ # @api public
159
+ def alert(text, io: nil)
160
+ stream = io || Yorha.config.io
161
+
162
+ write(stream, [Yorha::Render.paint("ALERT: #{clean(text)}", :danger, io: stream)])
163
+ end
164
+
165
+ # Renders a bordered table.
166
+ #
167
+ # Column widths come from the widest cell in each column,
168
+ # measured in terminal columns, so Japanese text stays aligned.
169
+ # Ragged rows are padded with empty cells instead of raising.
170
+ # An empty table renders just its borders.
171
+ #
172
+ # @example
173
+ # Yorha::Widgets.table([%w[HUD 6], %w[EVADE 8]], headers: %w[CHIP COST])
174
+ #
175
+ # @param rows [Array<Array<Object>>] table rows; cells use to_s
176
+ # @param headers [Array<Object>, nil] optional header cells
177
+ # @param io [#write, nil] detection and default output stream
178
+ # @return [String] the full text written
179
+ # @api public
180
+ def table(rows, headers: nil, io: nil)
181
+ stream = io || Yorha.config.io
182
+
183
+ body = rows.map { |row| Array(row).map { |cell| clean(cell) } }
184
+ head = headers && Array(headers).map { |cell| clean(cell) }
185
+
186
+ columns = [head&.length, body.map(&:length).max].compact.max || 1
187
+ body.each { |row| row.concat([""] * (columns - row.length)) }
188
+ head&.concat([""] * (columns - head.length))
189
+
190
+ widths = Array.new(columns, 0)
191
+ (body + [head]).compact.each do |row|
192
+ row.each_with_index { |cell, i| widths[i] = [widths[i], display_width(cell)].max }
193
+ end
194
+
195
+ lines = [table_border(widths, :top_left, :tee_top, :top_right, stream)]
196
+ lines << table_row(head, widths, :accent, stream) if head
197
+ lines << table_border(widths, :tee_left, :cross, :tee_right, stream)
198
+ body.each { |row| lines << table_row(row, widths, :fg, stream) }
199
+ lines << table_border(widths, :bottom_left, :tee_bottom, :bottom_right, stream)
200
+
201
+ write(stream, lines)
202
+ end
203
+
204
+ private
205
+
206
+ # Writes joined lines and returns exactly what was written.
207
+ #
208
+ # @param target [#write] destination stream
209
+ # @param lines [Array<String>] rows without line endings
210
+ # @return [String] the text written, with a trailing newline
211
+ def write(target, lines)
212
+ text = "#{lines.join("\n")}\n"
213
+ target.write(text)
214
+ text
215
+ end
216
+
217
+ # Makes caller text safe to draw.
218
+ #
219
+ # Invalid byte sequences become "?", tabs become a space, and
220
+ # every other control character becomes "?".
221
+ #
222
+ # @param text [Object] converted with to_s
223
+ # @return [String]
224
+ def clean(text)
225
+ text.to_s.scrub("?").gsub(/[[:cntrl:]]/) do |character|
226
+ character == "\t" ? " " : "?"
227
+ end
228
+ end
229
+
230
+ # Counts the terminal columns a plain string occupies.
231
+ #
232
+ # Every character counts as one column, and each East Asian
233
+ # wide character counts as one extra.
234
+ #
235
+ # @param text [String] plain text without escape sequences
236
+ # @return [Integer]
237
+ def display_width(text)
238
+ text.length + text.scan(WIDE_CHARACTER).length
239
+ end
240
+
241
+ # Pads plain text with spaces to a display width.
242
+ #
243
+ # @param text [String] plain text
244
+ # @param width [Integer] target display width
245
+ # @return [String]
246
+ def pad(text, width)
247
+ text + (" " * [width - display_width(text), 0].max)
248
+ end
249
+
250
+ # Clamps a requested box width into [40, Terminal.width].
251
+ #
252
+ # @param requested [Integer, nil] caller's width
253
+ # @param stream [#write] stream used to find the terminal width
254
+ # @return [Integer]
255
+ def box_width(requested, stream)
256
+ limit = Yorha::Terminal.width(stream)
257
+
258
+ [[requested || limit, limit].min, MINIMUM_WIDTH].max
259
+ end
260
+
261
+ # Builds a full-width border row for boxes.
262
+ #
263
+ # @param left [Symbol] left corner glyph name
264
+ # @param right [Symbol] right corner glyph name
265
+ # @param width [Integer] outer box width
266
+ # @param stream [#write]
267
+ # @return [String]
268
+ def frame_row(left, right, width, stream)
269
+ Yorha::Render.paint(
270
+ "#{Yorha::Render.glyph(left, io: stream)}" \
271
+ "#{Yorha::Render.glyph(:rule, io: stream) * (width - 2)}" \
272
+ "#{Yorha::Render.glyph(right, io: stream)}",
273
+ :muted,
274
+ io: stream
275
+ )
276
+ end
277
+
278
+ # Builds the divider row under a box title.
279
+ #
280
+ # @param width [Integer] outer box width
281
+ # @param stream [#write]
282
+ # @return [String]
283
+ def divider_row(width, stream)
284
+ Yorha::Render.paint(
285
+ "#{Yorha::Render.glyph(:tee_left, io: stream)}" \
286
+ "#{Yorha::Render.glyph(:rule, io: stream) * (width - 2)}" \
287
+ "#{Yorha::Render.glyph(:tee_right, io: stream)}",
288
+ :muted,
289
+ io: stream
290
+ )
291
+ end
292
+
293
+ # Builds a padded box content row. Padding is applied to the
294
+ # plain text before painting so colour escapes never shift
295
+ # alignment.
296
+ #
297
+ # @param text [String] plain text for the row
298
+ # @param inner [Integer] text area width
299
+ # @param role [Symbol] palette role
300
+ # @param stream [#write]
301
+ # @return [String]
302
+ def content_row(text, inner, role, stream)
303
+ Yorha::Render.paint(
304
+ "#{Yorha::Render.glyph(:vertical, io: stream)} " \
305
+ "#{pad(text, inner)} " \
306
+ "#{Yorha::Render.glyph(:vertical, io: stream)}",
307
+ role,
308
+ io: stream
309
+ )
310
+ end
311
+
312
+ # Wraps one paragraph at word boundaries.
313
+ #
314
+ # A single word longer than the width is kept whole on its own
315
+ # line. An empty paragraph yields one empty line.
316
+ #
317
+ # @param paragraph [String] plain text
318
+ # @param width [Integer] text area width
319
+ # @return [Array<String>]
320
+ def wrap(paragraph, width)
321
+ lines = []
322
+ current = +""
323
+
324
+ paragraph.split(" ").each do |word|
325
+ if current.empty?
326
+ current = +word
327
+ elsif display_width(current) + 1 + display_width(word) <= width
328
+ current << " " << word
329
+ else
330
+ lines << current
331
+ current = +word
332
+ end
333
+ end
334
+
335
+ lines << current unless current.empty?
336
+ lines << "" if lines.empty? && paragraph.empty?
337
+
338
+ lines
339
+ end
340
+
341
+ # Builds a table border row.
342
+ #
343
+ # @param widths [Array<Integer>] column widths
344
+ # @param left [Symbol] left junction glyph name
345
+ # @param join [Symbol] interior junction glyph name
346
+ # @param right [Symbol] right junction glyph name
347
+ # @param stream [#write]
348
+ # @return [String]
349
+ def table_border(widths, left, join, right, stream)
350
+ segments = widths.map do |width|
351
+ Yorha::Render.glyph(:rule, io: stream) * (width + 2)
352
+ end
353
+
354
+ Yorha::Render.paint(
355
+ "#{Yorha::Render.glyph(left, io: stream)}" \
356
+ "#{segments.join(Yorha::Render.glyph(join, io: stream))}" \
357
+ "#{Yorha::Render.glyph(right, io: stream)}",
358
+ :muted,
359
+ io: stream
360
+ )
361
+ end
362
+
363
+ # Builds one padded table row.
364
+ #
365
+ # @param cells [Array<String>]
366
+ # @param widths [Array<Integer>] column display widths
367
+ # @param role [Symbol] palette role
368
+ # @param stream [#write]
369
+ # @return [String]
370
+ def table_row(cells, widths, role, stream)
371
+ content = cells.each_with_index.map do |cell, index|
372
+ pad(cell, widths[index])
373
+ end.join(" #{Yorha::Render.glyph(:vertical, io: stream)} ")
374
+
375
+ Yorha::Render.paint(
376
+ "#{Yorha::Render.glyph(:vertical, io: stream)} #{content} " \
377
+ "#{Yorha::Render.glyph(:vertical, io: stream)}",
378
+ role,
379
+ io: stream
380
+ )
381
+ end
382
+ end
383
+ end
384
+ end