rufio 1.6.0 → 2.0.0

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.
Files changed (88) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +49 -0
  3. data/README.md +17 -10
  4. data/README_ja.md +17 -9
  5. data/SECURITY.md +14 -6
  6. data/docs/csv_cell_preview_design_ja.md +682 -0
  7. data/docs/guide.md +109 -47
  8. data/docs/guide_ja.md +110 -48
  9. data/docs/image_preview_design_ja.md +335 -0
  10. data/docs/native_fuzzy_search_design_ja.md +2 -2
  11. data/examples/config.rb +23 -0
  12. data/info/help.md +32 -27
  13. data/info/keybindings.md +42 -12
  14. data/info/welcome.md +4 -6
  15. data/lib/rufio/background_status.rb +7 -0
  16. data/lib/rufio/bookmark_controller.rb +0 -45
  17. data/lib/rufio/clipboard.rb +162 -0
  18. data/lib/rufio/command_locator.rb +49 -0
  19. data/lib/rufio/config.rb +7 -2
  20. data/lib/rufio/config_loader.rb +56 -21
  21. data/lib/rufio/csv_table_source.rb +125 -0
  22. data/lib/rufio/encoding_detector.rb +152 -0
  23. data/lib/rufio/file_operation_controller.rb +41 -0
  24. data/lib/rufio/file_preview.rb +92 -19
  25. data/lib/rufio/graphics_layer.rb +223 -0
  26. data/lib/rufio/health_checker.rb +27 -10
  27. data/lib/rufio/help_menu.rb +16 -11
  28. data/lib/rufio/image_preview_view.rb +421 -0
  29. data/lib/rufio/image_source.rb +158 -0
  30. data/lib/rufio/keybind_handler.rb +21 -35
  31. data/lib/rufio/kitty_graphics.rb +128 -0
  32. data/lib/rufio/native/aarch64-linux-gnu/librufio_zig.so +0 -0
  33. data/lib/rufio/native/aarch64-linux-musl/librufio_zig.so +0 -0
  34. data/lib/rufio/native/aarch64-macos/librufio_zig.dylib +0 -0
  35. data/lib/rufio/native/aarch64-windows/rufio_zig.dll +0 -0
  36. data/lib/rufio/native/x86_64-linux-gnu/librufio_zig.so +0 -0
  37. data/lib/rufio/native/x86_64-linux-musl/librufio_zig.so +0 -0
  38. data/lib/rufio/native/x86_64-macos/librufio_zig.dylib +0 -0
  39. data/lib/rufio/native/x86_64-windows/rufio_zig.dll +0 -0
  40. data/lib/rufio/native_content_search.rb +1 -1
  41. data/lib/rufio/native_image.rb +177 -0
  42. data/lib/rufio/native_scanner_zig.rb +22 -0
  43. data/lib/rufio/navigation_controller.rb +47 -16
  44. data/lib/rufio/preview_registry.rb +86 -0
  45. data/lib/rufio/preview_view.rb +363 -0
  46. data/lib/rufio/renderer.rb +8 -8
  47. data/lib/rufio/screen.rb +33 -0
  48. data/lib/rufio/search_prompt.rb +50 -0
  49. data/lib/rufio/{global_search.rb → search_screen.rb} +41 -14
  50. data/lib/rufio/sheet_picker.rb +87 -0
  51. data/lib/rufio/sqlite_table_source.rb +205 -0
  52. data/lib/rufio/tab_mode_manager.rb +1 -3
  53. data/lib/rufio/table_cursor.rb +117 -0
  54. data/lib/rufio/table_document.rb +261 -0
  55. data/lib/rufio/table_layout.rb +231 -0
  56. data/lib/rufio/table_preview_view.rb +376 -0
  57. data/lib/rufio/table_query.rb +240 -0
  58. data/lib/rufio/table_source.rb +46 -0
  59. data/lib/rufio/terminal_graphics.rb +168 -0
  60. data/lib/rufio/terminal_ui.rb +63 -111
  61. data/lib/rufio/text_utils.rb +27 -0
  62. data/lib/rufio/ui_renderer.rb +379 -16
  63. data/lib/rufio/version.rb +1 -1
  64. data/lib/rufio/xlsx_table_source.rb +112 -0
  65. data/lib/rufio.rb +19 -5
  66. data/lib_zig/rufio_native/Makefile +6 -4
  67. data/lib_zig/rufio_native/build.zig +10 -0
  68. data/lib_zig/rufio_native/src/image.zig +525 -0
  69. data/lib_zig/rufio_native/src/image_bmp.zig +111 -0
  70. data/lib_zig/rufio_native/src/image_jpeg.zig +878 -0
  71. data/lib_zig/rufio_native/src/image_png.zig +561 -0
  72. data/lib_zig/rufio_native/src/image_resize.zig +170 -0
  73. data/lib_zig/rufio_native/src/image_test.zig +401 -0
  74. data/lib_zig/rufio_native/src/main.zig +1 -0
  75. data/lib_zig/rufio_native/src/search.zig +38 -19
  76. data/lib_zig/rufio_native/src/search_test.zig +35 -0
  77. data/lib_zig/rufio_native/src/testdata/alpha.png +0 -0
  78. data/lib_zig/rufio_native/src/testdata/gradient.bmp +0 -0
  79. data/lib_zig/rufio_native/src/testdata/gradient.jpg +0 -0
  80. data/lib_zig/rufio_native/src/testdata/gradient.png +0 -0
  81. data/retag.sh +4 -4
  82. metadata +37 -9
  83. data/lib/rufio/fuzzy_candidate_cache.rb +0 -258
  84. data/lib/rufio/fuzzy_finder.rb +0 -313
  85. data/lib/rufio/fuzzy_preview_loader.rb +0 -107
  86. data/lib/rufio/rga_result_source.rb +0 -89
  87. data/lib/rufio/search_controller.rb +0 -94
  88. data/lib_zig/rufio_native/src/main.zig.sync +0 -205
@@ -9,9 +9,11 @@ require_relative 'fuzzy_search_session'
9
9
  require_relative 'fuzzy_candidate_block'
10
10
 
11
11
  module Rufio
12
- # ブックマーク配下のファイル名・テキスト内容をバックグラウンドで横断検索する。
13
- # ファイル名は s と同じあいまい検索(FuzzySearchSession)、本文は大文字小文字を無視したリテラル検索。
14
- class GlobalSearch
12
+ # 指定したディレクトリ配下のファイル名・テキスト内容をバックグラウンドで検索する画面(`/`)。
13
+ # ファイル名はあいまい検索(FuzzySearchSession)、本文は大文字小文字を無視したリテラル検索。
14
+ #
15
+ # 対象(roots)は呼び出し側が決める。Files モードの `/` は現在のディレクトリ 1 つを渡す。
16
+ class SearchScreen
15
17
  SPINNER_FRAMES = ['|', '/', '-', '\\'].freeze
16
18
  SPINNER_INTERVAL = 0.12
17
19
  # 検索語に一致した部分の表示(黒の太字・黄色背景)
@@ -51,18 +53,42 @@ module Rufio
51
53
  @scanning
52
54
  end
53
55
 
54
- def open(bookmarks)
56
+ # @param roots [Array<Hash>] 検索対象 [{ name:, path: }, ...]
57
+ def open(roots)
55
58
  close
56
59
  @active = true
57
60
  @query = ''
58
61
  @search_type = :filename
59
- @excluded_extensions = ConfigLoader.global_search_excluded_extensions
60
- @bookmark_count = bookmarks.length
61
- @roots = bookmarks.map { |bookmark| [bookmark[:name].to_s, bookmark[:path].to_s] }
62
+ @excluded_extensions = ConfigLoader.search_excluded_extensions
63
+ @roots = roots.map { |root| [root[:name].to_s, root[:path].to_s] }
62
64
  start_scan
63
65
  true
64
66
  end
65
67
 
68
+ # 対象が 1 つだけなら、結果の行頭に対象名を出さない(同じ名前が並ぶだけになる)
69
+ def single_root?
70
+ @roots.length == 1
71
+ end
72
+
73
+ # 画面上部に出す検索対象の短い名前(1 つならディレクトリ名)
74
+ def root_name
75
+ return '' if @roots.empty?
76
+
77
+ single_root? ? File.basename(@roots.first.last) : "#{@roots.length} directories"
78
+ end
79
+
80
+ # 状態行に出す検索対象のパス(ホームは ~ に畳む)
81
+ def root_label
82
+ return '' if @roots.empty?
83
+ return "#{@roots.length} directories" unless single_root?
84
+
85
+ path = @roots.first.last
86
+ home = Dir.home
87
+ path.start_with?(home) ? path.sub(home, '~') : path
88
+ rescue StandardError
89
+ @roots.first.last
90
+ end
91
+
66
92
  def close
67
93
  @active = false
68
94
  @scanning = false
@@ -109,7 +135,8 @@ module Rufio
109
135
  screen.clear(mark_dirty: true)
110
136
  width = screen.width
111
137
  type = @search_type == :content ? 'Content' : 'File names'
112
- write_line(screen, 0, "G mode - #{type} | Tab: Switch name/content search", width, "\e[1;36m")
138
+ write_line(screen, 0, "Search in #{root_name} - #{type} | Tab: Switch name/content search",
139
+ width, "\e[1;36m")
113
140
  write_line(screen, 1, "Search: #{@query}_", width)
114
141
  state = if scanning?
115
142
  "[#{SPINNER_FRAMES[@spinner_index]}] Searching..."
@@ -120,13 +147,13 @@ module Rufio
120
147
  end
121
148
  color = scanning? ? "\e[1;33m" : "\e[32m"
122
149
  matches = @session ? @total_matches : @results.length
123
- write_line(screen, 2, "#{state} | #{@bookmark_count} bookmarks | #{matches} matches | #{@errors.length} errors | #{@skipped_files} skipped", width, color)
150
+ write_line(screen, 2, "#{state} | #{matches} matches | #{@errors.length} errors | #{@skipped_files} skipped | #{root_label}", width, color)
124
151
  row_height = @search_type == :content ? 2 : 1
125
152
  capacity = [screen.height - 6, 0].max / row_height
126
153
  first = [@selected_index - capacity + 1, 0].max
127
154
  @results.slice(first, capacity).to_a.each_with_index do |entry, index|
128
155
  selected = first + index == @selected_index
129
- prefix = "#{selected ? '>' : ' '} [#{entry[:bookmark]}] "
156
+ prefix = single_root? ? "#{selected ? '>' : ' '} " : "#{selected ? '>' : ' '} [#{entry[:bookmark]}] "
130
157
  text = "#{prefix}#{entry[:relative_path]}"
131
158
  text += if entry[:location]
132
159
  " - #{entry[:location]}"
@@ -142,14 +169,14 @@ module Rufio
142
169
  write_line(screen, y + 1, " #{entry[:match_text]}", width, highlight_from: 4) if entry[:match_text]
143
170
  end
144
171
  if @results.empty?
145
- message = if @bookmark_count.zero?
146
- 'No bookmarks. Add directories with b in Files mode.'
172
+ message = if @roots.empty?
173
+ 'Nothing to search here.'
147
174
  elsif scanning?
148
- 'Searching bookmarked directories...'
175
+ 'Searching...'
149
176
  elsif @search_type == :content && @query.empty?
150
177
  'Type a string to search inside text files.'
151
178
  elsif !@errors.empty? && candidate_count.zero?
152
- 'No readable files in bookmarked directories.'
179
+ 'No readable files in this directory.'
153
180
  else
154
181
  'No matching files. Edit your search to try again.'
155
182
  end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rufio
4
+ # 表プレビューのシート一覧(Excel のシート / SQLite のテーブル)の選択状態。
5
+ #
6
+ # 名前の並びだけを受け取り、選択位置と縦スクロール位置を持つ。TableCursor と同じく
7
+ # 「選択が見えるように最小限ずらす」方式で、表示できる行数は描画側(UIRenderer)が
8
+ # 毎フレーム visible_rows= で教える。
9
+ class SheetPicker
10
+ # 表示行数が分からないうちの既定値
11
+ DEFAULT_VISIBLE_ROWS = 10
12
+
13
+ attr_reader :names, :index, :offset, :visible_rows
14
+
15
+ # @param names [Array<String>] シート名(表示順)
16
+ # @param index [Integer] 最初に選んでおく添字(現在表示中のシート)
17
+ def initialize(names, index: 0)
18
+ @names = Array(names)
19
+ @index = empty? ? 0 : index.to_i.clamp(0, count - 1)
20
+ @offset = 0
21
+ @visible_rows = DEFAULT_VISIBLE_ROWS
22
+ ensure_visible
23
+ end
24
+
25
+ def count
26
+ @names.length
27
+ end
28
+
29
+ def empty?
30
+ @names.empty?
31
+ end
32
+
33
+ def selected_name
34
+ @names[@index]
35
+ end
36
+
37
+ # @return [Boolean] 選択位置かスクロール位置が動いたか
38
+ def move(delta)
39
+ move_to(@index + delta)
40
+ end
41
+
42
+ def first
43
+ move_to(0)
44
+ end
45
+
46
+ def last
47
+ move_to(count - 1)
48
+ end
49
+
50
+ def move_to(index)
51
+ return false if empty?
52
+
53
+ before = [@index, @offset]
54
+ @index = index.to_i.clamp(0, count - 1)
55
+ ensure_visible
56
+ before != [@index, @offset]
57
+ end
58
+
59
+ def page(pages)
60
+ move(pages * @visible_rows)
61
+ end
62
+
63
+ # 描画側が表示できる行数を伝える
64
+ def visible_rows=(rows)
65
+ @visible_rows = [rows.to_i, 1].max
66
+ ensure_visible
67
+ end
68
+
69
+ # @return [Array<Array(Integer, String)>] 表示する [添字, 名前] の並び
70
+ def visible
71
+ return [] if empty?
72
+
73
+ last_index = [@offset + @visible_rows, count].min - 1
74
+ (@offset..last_index).map { |i| [i, @names[i]] }
75
+ end
76
+
77
+ private
78
+
79
+ # 選択行が表示範囲に入るよう、スクロール位置を最小限ずらす
80
+ def ensure_visible
81
+ @offset = @index if @index < @offset
82
+ last_visible = @offset + @visible_rows - 1
83
+ @offset = @index - @visible_rows + 1 if @index > last_visible
84
+ @offset = @offset.clamp(0, [count - @visible_rows, 0].max)
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'csv'
4
+ require_relative 'table_source'
5
+ require_relative 'table_document'
6
+ require_relative 'table_query'
7
+ require_relative 'command_locator'
8
+
9
+ module Rufio
10
+ # SQLite のデータベースをテーブルごとの表として読む TableSource。
11
+ #
12
+ # rga / bat / zoxide と同じ「インストールされていれば使う」方式で、sqlite3 コマンドが
13
+ # 無ければ表として扱わない(プレビューは従来のバイナリ表示になる)。gem を増やさない。
14
+ #
15
+ # 判定は拡張子ではなくファイル先頭のシグネチャで行う。拡張子は .db / .sqlite に限らず
16
+ # 何でもよく、逆に .db という名前の別形式を誤って開くこともない。
17
+ #
18
+ # 実行は argv(シェル非経由)で、必ず読み取り専用で開き、発行するのは SELECT だけ。
19
+ class SqliteTableSource < TableSource
20
+ COMMAND = 'sqlite3'
21
+ SIGNATURE = "SQLite format 3\x00".b
22
+ # 表示するテーブル(sqlite_ で始まる内部テーブルは除く)
23
+ TABLE_LIST_SQL = "SELECT name FROM sqlite_master WHERE type IN ('table','view') " \
24
+ "AND name NOT LIKE 'sqlite_%' ORDER BY name;"
25
+
26
+ class << self
27
+ def supports?(path)
28
+ return false unless command_available?
29
+
30
+ file = path.to_s
31
+ return false unless File.file?(file)
32
+
33
+ sqlite_file?(file)
34
+ end
35
+
36
+ def open(path, limits: TableSource::Limits.default, options: {})
37
+ tables = list_tables(path)
38
+ raise TableSource::ParseError, 'no tables' if tables.empty?
39
+
40
+ sheets = tables.map do |table|
41
+ # `/` の絞り込みは WHERE 付きの SELECT を発行し直す(読み込み上限より後ろも探す)
42
+ filter = ->(query) { load_table(path, table, limits, options, query) }
43
+ LazyTableSheet.new(name: table, filter: filter) { load_table(path, table, limits, options) }
44
+ end
45
+
46
+ TableDocument.new(sheets: sheets, encoding: 'UTF-8', label: File.basename(path.to_s),
47
+ sheet_label: 'Tables')
48
+ end
49
+
50
+ # sqlite3 コマンドが使えるか(テストから差し替えられるよう public)
51
+ def command_available?
52
+ return @command_available unless @command_available.nil?
53
+
54
+ @command_available = CommandLocator.available?(COMMAND)
55
+ end
56
+
57
+ # argv を受け取り [出力, 成功したか] を返す Proc(テストから差し替える)
58
+ def runner
59
+ @runner ||= method(:run_command)
60
+ end
61
+
62
+ # -safe を付けられるか(古い sqlite3 は知らないオプションで失敗する)。
63
+ # プロセス内で 1 度だけ確認する
64
+ def safe_mode_supported?
65
+ return @safe_mode_supported unless @safe_mode_supported.nil?
66
+
67
+ _output, ok = runner.call([COMMAND, '-safe', '-csv', ':memory:', 'SELECT 1;'])
68
+ @safe_mode_supported = ok
69
+ end
70
+
71
+ attr_writer :runner
72
+
73
+ def reset!
74
+ @runner = nil
75
+ @command_available = nil
76
+ @safe_mode_supported = nil
77
+ CommandLocator.reset!
78
+ end
79
+
80
+ private
81
+
82
+ def sqlite_file?(file)
83
+ File.binread(file, SIGNATURE.bytesize) == SIGNATURE
84
+ rescue SystemCallError
85
+ false
86
+ end
87
+
88
+ def list_tables(path)
89
+ output = query(path, TABLE_LIST_SQL, header: false)
90
+ CSV.parse(output).flatten.compact.map(&:strip).reject(&:empty?)
91
+ rescue CSV::MalformedCSVError => e
92
+ raise TableSource::ParseError, e.message
93
+ end
94
+
95
+ def load_table(path, table, limits, options, filter = nil)
96
+ # 上限 + 1 行だけ取り、全体の件数を数える COUNT(*) は発行しない
97
+ sql = +"SELECT * FROM #{quote_identifier(table)}"
98
+ sql << " WHERE #{where_clause(filter)}" if filter
99
+ sql << " LIMIT #{limits.max_rows + 1};"
100
+ parsed = CSV.parse(query(path, sql, header: true))
101
+
102
+ # 列の切り詰めは見出し行にも掛ける(掛け忘れると列数が行とずれる)
103
+ column_truncated = false
104
+ rows = parsed.map do |row|
105
+ cells = Array(row).map { |value| value.nil? ? '' : value.to_s }
106
+ if cells.length > limits.max_columns
107
+ cells = cells[0, limits.max_columns]
108
+ column_truncated = true
109
+ end
110
+ cells
111
+ end
112
+
113
+ header = options.fetch(:header, true) && !rows.empty? ? rows.shift : nil
114
+ row_truncated = rows.length > limits.max_rows
115
+ rows = rows[0, limits.max_rows] if row_truncated
116
+
117
+ { rows: rows, header: header, row_truncated: row_truncated, column_truncated: column_truncated }
118
+ end
119
+
120
+ def query(path, sql, header:)
121
+ argv = [COMMAND, '-readonly', '-csv']
122
+ # -safe は writefile() / load_extension() / ATTACH などを拒否する(sqlite3 3.34+)。
123
+ # 読み取り専用の SELECT しか発行しないため、この機能に失うものはない
124
+ argv << '-safe' if safe_mode_supported?
125
+ argv << '-header' if header
126
+ # SECURITY.md の方針どおり、'-' で始まるパスがオプションと解釈されないようにする
127
+ argv += [File.expand_path(path.to_s), sql]
128
+
129
+ output, ok = runner.call(argv)
130
+ raise TableSource::ParseError, "#{COMMAND} failed" unless ok
131
+
132
+ force_utf8(output)
133
+ end
134
+
135
+ def run_command(argv)
136
+ output = IO.popen(argv, 'r', err: File::NULL, &:read)
137
+ status = Process.last_status
138
+ [force_utf8(output), status.nil? || status.success?]
139
+ rescue SystemCallError, IOError => e
140
+ raise TableSource::ParseError, e.message
141
+ end
142
+
143
+ # コマンドの出力は Encoding.default_external になる(LANG が無い環境では US-ASCII)。
144
+ # sqlite3 は UTF-8 で出力するため、読み替えないと日本語を含むテーブルで
145
+ # CSV が「Invalid byte sequence」になる。
146
+ def force_utf8(output)
147
+ text = output.to_s.dup.force_encoding(Encoding::UTF_8)
148
+ text.valid_encoding? ? text : text.scrub('?')
149
+ end
150
+
151
+ # テーブル名は識別子クォートする(SQL を文字列連結で組まない)
152
+ def quote_identifier(name)
153
+ %("#{name.to_s.gsub('"', '""')}")
154
+ end
155
+
156
+ # TableQuery の条件を WHERE 句にする。
157
+ # 列名は TableQuery が実在する列に解決済みで、ここで識別子クォートする。
158
+ # 演算子は TableQuery が許可したものだけ、値は常にリテラルとして引用する。
159
+ def where_clause(filter)
160
+ parts = filter.conditions.map { |condition| condition_sql(condition, filter.columns) }
161
+ raise TableSource::ParseError, 'no condition' if parts.empty?
162
+
163
+ parts.join(' AND ')
164
+ end
165
+
166
+ def condition_sql(condition, columns)
167
+ if condition.column.nil?
168
+ targets = Array(columns)
169
+ raise TableSource::ParseError, 'no columns to search' if targets.empty?
170
+
171
+ "(#{targets.map { |column| like_sql(column, condition.value) }.join(' OR ')})"
172
+ elsif condition.operator == TableQuery::LIKE
173
+ "(#{like_sql(condition.column, condition.value)})"
174
+ else
175
+ "(#{quote_identifier(condition.column)} #{operator_sql(condition.operator)} " \
176
+ "#{value_sql(condition.value)})"
177
+ end
178
+ end
179
+
180
+ def like_sql(column, pattern)
181
+ "#{quote_identifier(column)} LIKE #{quote_string(pattern)}"
182
+ end
183
+
184
+ # 許可した演算子だけを通す(!= は SQLite の <> に揃える)
185
+ def operator_sql(operator)
186
+ raise TableSource::ParseError, "unsupported operator: #{operator}" unless
187
+ TableQuery::OPERATORS.include?(operator)
188
+
189
+ operator == '!=' ? '<>' : operator
190
+ end
191
+
192
+ # 数値はそのまま、それ以外は文字列リテラルとして引用する
193
+ def value_sql(value)
194
+ text = value.to_s
195
+ return text if text.match?(/\A-?\d+(\.\d+)?\z/)
196
+
197
+ quote_string(text)
198
+ end
199
+
200
+ def quote_string(value)
201
+ "'#{value.to_s.gsub("'", "''")}'"
202
+ end
203
+ end
204
+ end
205
+ end
@@ -4,12 +4,11 @@ module Rufio
4
4
  # タブモード管理クラス
5
5
  # 上部メニューの2段目に表示するモードタブを管理する
6
6
  class TabModeManager
7
- MODES = %i[files config global logs jobs help].freeze
7
+ MODES = %i[files config logs jobs help].freeze
8
8
 
9
9
  MODE_LABELS = {
10
10
  files: 'Files',
11
11
  config: 'Config',
12
- global: 'Search',
13
12
  logs: 'Logs',
14
13
  jobs: 'Jobs',
15
14
  help: 'Help'
@@ -18,7 +17,6 @@ module Rufio
18
17
  MODE_KEYS = {
19
18
  files: nil,
20
19
  config: 'C',
21
- global: 'G',
22
20
  logs: 'L',
23
21
  jobs: 'J',
24
22
  help: '?'
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rufio
4
+ # 表プレビューのセルカーソル。行・列の位置と、縦横のスクロール位置を持つ。
5
+ #
6
+ # 縦スクロールは「カーソルが見えるように最小限ずらす」方式で、表示できる行数は
7
+ # 描画側(UIRenderer)が毎フレーム visible_rows= で教える。
8
+ # 横スクロールは列幅に依存するため、ずらす量の計算は TableLayout#offset_for が担う。
9
+ class TableCursor
10
+ # 表示行数が分からないうちのページ送り量(既存のプレビュースクロールと同じ)
11
+ DEFAULT_VISIBLE_ROWS = 20
12
+
13
+ attr_reader :row, :column, :row_offset, :visible_rows
14
+ attr_accessor :column_offset
15
+
16
+ def initialize(sheet)
17
+ @sheet = sheet
18
+ @row = 0
19
+ @column = 0
20
+ @row_offset = 0
21
+ @column_offset = 0
22
+ @visible_rows = DEFAULT_VISIBLE_ROWS
23
+ end
24
+
25
+ def row_count
26
+ @sheet.row_count
27
+ end
28
+
29
+ def column_count
30
+ @sheet.column_count
31
+ end
32
+
33
+ # カーソルの指すセルの生の値(表示用に畳んでいない値)
34
+ def value
35
+ @sheet.cell(@row, @column)
36
+ end
37
+
38
+ def empty?
39
+ row_count.zero? || column_count.zero?
40
+ end
41
+
42
+ # 先頭のセルに戻す(表示できる行数の記憶は保つ)
43
+ def reset
44
+ @row = 0
45
+ @column = 0
46
+ @row_offset = 0
47
+ @column_offset = 0
48
+ true
49
+ end
50
+
51
+ # @return [Boolean] 位置が動いたか
52
+ def move(rows: 0, columns: 0)
53
+ move_to(@row + rows, @column + columns)
54
+ end
55
+
56
+ def move_to(row, column)
57
+ before = [@row, @column, @row_offset]
58
+ @row = clamp(row, row_count)
59
+ @column = clamp(column, column_count)
60
+ ensure_row_visible
61
+ before != [@row, @column, @row_offset]
62
+ end
63
+
64
+ def move_to_row(row)
65
+ move_to(row, @column)
66
+ end
67
+
68
+ def move_to_column(column)
69
+ move_to(@row, column)
70
+ end
71
+
72
+ def first_row
73
+ move_to_row(0)
74
+ end
75
+
76
+ def last_row
77
+ move_to_row(row_count - 1)
78
+ end
79
+
80
+ def first_column
81
+ move_to_column(0)
82
+ end
83
+
84
+ def last_column
85
+ move_to_column(column_count - 1)
86
+ end
87
+
88
+ # @param pages [Integer] 正で下、負で上
89
+ def page(pages)
90
+ move(rows: pages * [@visible_rows, 1].max)
91
+ end
92
+
93
+ # 描画側が表示できるデータ行数を伝える
94
+ def visible_rows=(count)
95
+ @visible_rows = [count.to_i, 1].max
96
+ ensure_row_visible
97
+ end
98
+
99
+ # カーソル行が表示範囲に入るよう、スクロール位置を最小限ずらす
100
+ def ensure_row_visible
101
+ @row_offset = @row if @row < @row_offset
102
+ last_visible = @row_offset + @visible_rows - 1
103
+ @row_offset = @row - @visible_rows + 1 if @row > last_visible
104
+ @row_offset = 0 if @row_offset.negative?
105
+ @row_offset = [@row_offset, [row_count - 1, 0].max].min
106
+ @row_offset
107
+ end
108
+
109
+ private
110
+
111
+ def clamp(value, count)
112
+ return 0 if count <= 0
113
+
114
+ value.clamp(0, count - 1)
115
+ end
116
+ end
117
+ end