rufio 1.5.1 → 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 (92) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +86 -0
  3. data/README.md +18 -6
  4. data/README_ja.md +18 -6
  5. data/Rakefile +5 -0
  6. data/SECURITY.md +16 -8
  7. data/docs/csv_cell_preview_design_ja.md +682 -0
  8. data/docs/guide.md +115 -20
  9. data/docs/guide_ja.md +116 -21
  10. data/docs/image_preview_design_ja.md +335 -0
  11. data/docs/native_fuzzy_search_design_ja.md +684 -0
  12. data/examples/config.rb +23 -0
  13. data/info/help.md +32 -18
  14. data/info/keybindings.md +43 -11
  15. data/info/welcome.md +4 -6
  16. data/lib/rufio/background_status.rb +7 -0
  17. data/lib/rufio/bookmark_controller.rb +0 -45
  18. data/lib/rufio/clipboard.rb +162 -0
  19. data/lib/rufio/command_locator.rb +49 -0
  20. data/lib/rufio/config.rb +7 -4
  21. data/lib/rufio/config_loader.rb +66 -11
  22. data/lib/rufio/csv_table_source.rb +125 -0
  23. data/lib/rufio/encoding_detector.rb +152 -0
  24. data/lib/rufio/file_operation_controller.rb +41 -0
  25. data/lib/rufio/file_preview.rb +92 -19
  26. data/lib/rufio/fuzzy_candidate_block.rb +131 -0
  27. data/lib/rufio/fuzzy_file_source.rb +180 -0
  28. data/lib/rufio/fuzzy_search.rb +327 -0
  29. data/lib/rufio/fuzzy_search_session.rb +426 -0
  30. data/lib/rufio/graphics_layer.rb +223 -0
  31. data/lib/rufio/health_checker.rb +27 -32
  32. data/lib/rufio/help_menu.rb +16 -10
  33. data/lib/rufio/image_preview_view.rb +421 -0
  34. data/lib/rufio/image_source.rb +158 -0
  35. data/lib/rufio/keybind_handler.rb +21 -34
  36. data/lib/rufio/kitty_graphics.rb +128 -0
  37. data/lib/rufio/native/aarch64-linux-gnu/librufio_zig.so +0 -0
  38. data/lib/rufio/native/aarch64-linux-musl/librufio_zig.so +0 -0
  39. data/lib/rufio/native/aarch64-macos/librufio_zig.dylib +0 -0
  40. data/lib/rufio/native/aarch64-windows/rufio_zig.dll +0 -0
  41. data/lib/rufio/native/x86_64-linux-gnu/librufio_zig.so +0 -0
  42. data/lib/rufio/native/x86_64-linux-musl/librufio_zig.so +0 -0
  43. data/lib/rufio/native/x86_64-macos/librufio_zig.dylib +0 -0
  44. data/lib/rufio/native/x86_64-windows/rufio_zig.dll +0 -0
  45. data/lib/rufio/native_content_search.rb +44 -8
  46. data/lib/rufio/native_image.rb +177 -0
  47. data/lib/rufio/native_scanner_zig.rb +39 -0
  48. data/lib/rufio/navigation_controller.rb +47 -16
  49. data/lib/rufio/preview_registry.rb +86 -0
  50. data/lib/rufio/preview_view.rb +363 -0
  51. data/lib/rufio/renderer.rb +8 -8
  52. data/lib/rufio/screen.rb +38 -1
  53. data/lib/rufio/search_prompt.rb +50 -0
  54. data/lib/rufio/search_screen.rb +680 -0
  55. data/lib/rufio/sheet_picker.rb +87 -0
  56. data/lib/rufio/sqlite_table_source.rb +205 -0
  57. data/lib/rufio/tab_mode_manager.rb +1 -3
  58. data/lib/rufio/table_cursor.rb +117 -0
  59. data/lib/rufio/table_document.rb +261 -0
  60. data/lib/rufio/table_layout.rb +231 -0
  61. data/lib/rufio/table_preview_view.rb +376 -0
  62. data/lib/rufio/table_query.rb +240 -0
  63. data/lib/rufio/table_source.rb +46 -0
  64. data/lib/rufio/terminal_graphics.rb +168 -0
  65. data/lib/rufio/terminal_ui.rb +74 -60
  66. data/lib/rufio/text_utils.rb +27 -0
  67. data/lib/rufio/ui_renderer.rb +380 -17
  68. data/lib/rufio/version.rb +1 -1
  69. data/lib/rufio/xlsx_table_source.rb +112 -0
  70. data/lib/rufio.rb +21 -1
  71. data/lib_zig/rufio_native/Makefile +21 -5
  72. data/lib_zig/rufio_native/build.zig +18 -0
  73. data/lib_zig/rufio_native/src/fuzzy.zig +520 -0
  74. data/lib_zig/rufio_native/src/fuzzy_test.zig +212 -0
  75. data/lib_zig/rufio_native/src/image.zig +525 -0
  76. data/lib_zig/rufio_native/src/image_bmp.zig +111 -0
  77. data/lib_zig/rufio_native/src/image_jpeg.zig +878 -0
  78. data/lib_zig/rufio_native/src/image_png.zig +561 -0
  79. data/lib_zig/rufio_native/src/image_resize.zig +170 -0
  80. data/lib_zig/rufio_native/src/image_test.zig +401 -0
  81. data/lib_zig/rufio_native/src/main.zig +28 -0
  82. data/lib_zig/rufio_native/src/search.zig +260 -64
  83. data/lib_zig/rufio_native/src/search_test.zig +35 -0
  84. data/lib_zig/rufio_native/src/testdata/alpha.png +0 -0
  85. data/lib_zig/rufio_native/src/testdata/gradient.bmp +0 -0
  86. data/lib_zig/rufio_native/src/testdata/gradient.jpg +0 -0
  87. data/lib_zig/rufio_native/src/testdata/gradient.png +0 -0
  88. data/retag.sh +4 -4
  89. metadata +44 -5
  90. data/lib/rufio/global_search.rb +0 -412
  91. data/lib/rufio/search_controller.rb +0 -92
  92. data/lib_zig/rufio_native/src/main.zig.sync +0 -205
@@ -0,0 +1,680 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thread'
4
+ require_relative 'text_utils'
5
+ require_relative 'config_loader'
6
+ require_relative 'document_text_extractor'
7
+ require_relative 'native_content_search'
8
+ require_relative 'fuzzy_search_session'
9
+ require_relative 'fuzzy_candidate_block'
10
+
11
+ module Rufio
12
+ # 指定したディレクトリ配下のファイル名・テキスト内容をバックグラウンドで検索する画面(`/`)。
13
+ # ファイル名はあいまい検索(FuzzySearchSession)、本文は大文字小文字を無視したリテラル検索。
14
+ #
15
+ # 対象(roots)は呼び出し側が決める。Files モードの `/` は現在のディレクトリ 1 つを渡す。
16
+ class SearchScreen
17
+ SPINNER_FRAMES = ['|', '/', '-', '\\'].freeze
18
+ SPINNER_INTERVAL = 0.12
19
+ # 検索語に一致した部分の表示(黒の太字・黄色背景)
20
+ MATCH_FG = "\e[30m\e[1m"
21
+ MATCH_BG = "\e[43m"
22
+ # ファイル名検索で一覧に保持する上位件数
23
+ FILE_RESULT_LIMIT = 1_000
24
+ # 一致位置は上位のこの件数だけ照合時に求め、それより下の行は表示するときに求める
25
+ FILE_POSITION_LIMIT = 100
26
+
27
+ attr_reader :query, :results, :errors, :selected_index, :search_type, :skipped_files
28
+
29
+ class << self
30
+ # nil: 利用可能なら Zig 実装を使う(RUFIO_NATIVE_SEARCH=0 で無効化)
31
+ attr_writer :native_search
32
+
33
+ def native_search?
34
+ enabled = @native_search.nil? ? ENV['RUFIO_NATIVE_SEARCH'] != '0' : @native_search
35
+ enabled && NativeContentSearch.available?
36
+ end
37
+ end
38
+
39
+ def initialize
40
+ @active = false
41
+ @scanning = false
42
+ @worker = nil
43
+ @session = nil
44
+ @document_extractor = DocumentTextExtractor.new
45
+ @document_cache = DocumentTextCache.new(extractor: @document_extractor)
46
+ end
47
+
48
+ def active?
49
+ @active
50
+ end
51
+
52
+ def scanning?
53
+ @scanning
54
+ end
55
+
56
+ # @param roots [Array<Hash>] 検索対象 [{ name:, path: }, ...]
57
+ def open(roots)
58
+ close
59
+ @active = true
60
+ @query = ''
61
+ @search_type = :filename
62
+ @excluded_extensions = ConfigLoader.search_excluded_extensions
63
+ @roots = roots.map { |root| [root[:name].to_s, root[:path].to_s] }
64
+ start_scan
65
+ true
66
+ end
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
+
92
+ def close
93
+ @active = false
94
+ @scanning = false
95
+ stop_search
96
+ end
97
+
98
+ # 1フレーム当たりの処理量を制限し、検索中も入力を受け付ける。
99
+ def poll
100
+ return false unless active?
101
+
102
+ changed = @session ? poll_session : poll_events
103
+ if scanning?
104
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
105
+ if now - @last_spinner_update >= SPINNER_INTERVAL
106
+ @spinner_index = (@spinner_index + 1) % SPINNER_FRAMES.length
107
+ @last_spinner_update = now
108
+ changed = true
109
+ end
110
+ end
111
+ changed
112
+ end
113
+
114
+ def handle_key(key)
115
+ case key
116
+ when "\e" then close
117
+ when "\t"
118
+ @search_type = @search_type == :filename ? :content : :filename
119
+ start_scan
120
+ when "\r" then return @results[@selected_index]
121
+ when :down then select_index(@selected_index + 1)
122
+ when :up then select_index(@selected_index - 1)
123
+ when "\x0a", "\x0e" then handle_key(:down) # Ctrl+J / Ctrl+N
124
+ when "\x0b", "\x10" then handle_key(:up) # Ctrl+K / Ctrl+P
125
+ when "\x15" then update_query('') # Ctrl+U
126
+ when "\u007f", "\b" then update_query(@query[0...-1])
127
+ else
128
+ update_query(@query + key) if key.is_a?(String) && !key.empty? && key.valid_encoding? &&
129
+ key.each_codepoint.all? { |c| c >= 32 && c != 127 }
130
+ end
131
+ nil
132
+ end
133
+
134
+ def draw(screen)
135
+ screen.clear(mark_dirty: true)
136
+ width = screen.width
137
+ type = @search_type == :content ? 'Content' : 'File names'
138
+ write_line(screen, 0, "Search in #{root_name} - #{type} | Tab: Switch name/content search",
139
+ width, "\e[1;36m")
140
+ write_line(screen, 1, "Search: #{@query}_", width)
141
+ state = if scanning?
142
+ "[#{SPINNER_FRAMES[@spinner_index]}] Searching..."
143
+ elsif @search_type == :content && @query.empty?
144
+ 'Ready'
145
+ else
146
+ 'Search complete'
147
+ end
148
+ color = scanning? ? "\e[1;33m" : "\e[32m"
149
+ matches = @session ? @total_matches : @results.length
150
+ write_line(screen, 2, "#{state} | #{matches} matches | #{@errors.length} errors | #{@skipped_files} skipped | #{root_label}", width, color)
151
+ row_height = @search_type == :content ? 2 : 1
152
+ capacity = [screen.height - 6, 0].max / row_height
153
+ first = [@selected_index - capacity + 1, 0].max
154
+ @results.slice(first, capacity).to_a.each_with_index do |entry, index|
155
+ selected = first + index == @selected_index
156
+ prefix = single_root? ? "#{selected ? '>' : ' '} " : "#{selected ? '>' : ' '} [#{entry[:bookmark]}] "
157
+ text = "#{prefix}#{entry[:relative_path]}"
158
+ text += if entry[:location]
159
+ " - #{entry[:location]}"
160
+ elsif entry[:line_number]
161
+ ":#{entry[:line_number]}"
162
+ else
163
+ ''
164
+ end
165
+ y = index * row_height + 3
166
+ # ファイル名検索はあいまい検索の一致位置、本文検索はスニペットの一致箇所をハイライトする
167
+ write_line(screen, y, text, width, selected ? "\e[1;36m" : nil)
168
+ highlight_positions(screen, y, prefix, entry, width) if @search_type == :filename
169
+ write_line(screen, y + 1, " #{entry[:match_text]}", width, highlight_from: 4) if entry[:match_text]
170
+ end
171
+ if @results.empty?
172
+ message = if @roots.empty?
173
+ 'Nothing to search here.'
174
+ elsif scanning?
175
+ 'Searching...'
176
+ elsif @search_type == :content && @query.empty?
177
+ 'Type a string to search inside text files.'
178
+ elsif !@errors.empty? && candidate_count.zero?
179
+ 'No readable files in this directory.'
180
+ else
181
+ 'No matching files. Edit your search to try again.'
182
+ end
183
+ write_line(screen, 3, message, width)
184
+ end
185
+ write_line(screen, screen.height - 3, @results[@selected_index]&.[](:path) || @errors.first.to_s, width, "\e[90m")
186
+ write_line(screen, screen.height - 2, 'ESC: Back | Enter: Go to file | Up/Down or Ctrl+J/K: Select | Type: Search', width)
187
+ end
188
+
189
+ private
190
+
191
+ # 本文検索の走査スレッドとファイル名検索のセッションを止める。セッションは待たずに閉じる
192
+ def stop_search
193
+ @worker&.kill
194
+ @worker&.join
195
+ @worker = nil
196
+ @session&.close
197
+ @session = nil
198
+ @file_source = nil
199
+ end
200
+
201
+ def candidate_count
202
+ @session ? @candidate_count : @entries.length
203
+ end
204
+
205
+ def start_scan
206
+ stop_search
207
+ @entries = []
208
+ @results = []
209
+ @result_ids = []
210
+ @errors = []
211
+ @skipped_files = 0
212
+ @selected_index = 0
213
+ @selected_id = nil
214
+ @total_matches = 0
215
+ @candidate_count = 0
216
+ @shown = nil
217
+ @events = SizedQueue.new(256)
218
+ @spinner_index = 0
219
+ @last_spinner_update = Process.clock_gettime(Process::CLOCK_MONOTONIC)
220
+ @scanning = !(@search_type == :content && @query.empty?)
221
+ return unless @scanning
222
+ return start_file_name_session if @search_type == :filename
223
+
224
+ roots, events, query = @roots, @events, @query.downcase
225
+ native = self.class.native_search?
226
+ native_cache = native ? (@native_cache ||= NativeContentSearch::Cache.new) : nil
227
+ @worker = Thread.new do
228
+ begin
229
+ if native && NativeContentSearch.supports_query?(query)
230
+ scan_roots_natively(roots, events, query, native_cache)
231
+ else
232
+ scan_roots(roots, events, :content, query)
233
+ end
234
+ rescue StandardError => e
235
+ events << [:error, e.message]
236
+ end
237
+ events << [:done, nil]
238
+ end
239
+ end
240
+
241
+ # ファイル名は走査と照合を FuzzySearchSession のワーカーに任せ、UI スレッドでは絞り込まない
242
+ def start_file_name_session
243
+ @file_source = FileNameSource.new(self, @roots, self.class.native_search?)
244
+ @session = FuzzySearchSession.new(source: @file_source, limit: FILE_RESULT_LIMIT,
245
+ position_limit: FILE_POSITION_LIMIT).start
246
+ @session.update_query(@query) unless @query.empty?
247
+ # 開いた直後の状態は描画済みなので、変化があったときだけ poll で再描画させる
248
+ @shown = @session.snapshot
249
+ end
250
+
251
+ def update_query(query)
252
+ @query = query
253
+ @selected_index = 0
254
+ @selected_id = nil
255
+ return start_scan if @search_type == :content || @session.nil?
256
+
257
+ # 前の検索語の結果を選べないよう、新しい結果が届くまで一覧を空にする
258
+ @session.update_query(query)
259
+ @results = []
260
+ @result_ids = []
261
+ @scanning = true
262
+ rescue IOError
263
+ nil
264
+ end
265
+
266
+ def select_index(index)
267
+ @selected_index = index.clamp(0, [@results.length - 1, 0].max)
268
+ @selected_id = @result_ids&.[](@selected_index)
269
+ end
270
+
271
+ def poll_session
272
+ @session.poll
273
+ state = @session.snapshot
274
+ @skipped_files = @file_source.skipped
275
+ @scanning = state.scanning || state.searching
276
+ return false if state.equal?(@shown)
277
+
278
+ @shown = state
279
+ @results = state.results.map { |result| result[:entry].merge(positions: result[:positions]) }
280
+ @result_ids = state.results.map { |result| result[:id] }
281
+ @errors = state.errors
282
+ @total_matches = state.total_matches
283
+ @candidate_count = state.candidate_count
284
+ # 候補の追加で順位が変わっても、選択中のファイルを追い続ける
285
+ index = @selected_id && @result_ids.index(@selected_id)
286
+ @selected_index = (index || @selected_index).clamp(0, [@results.length - 1, 0].max)
287
+ true
288
+ end
289
+
290
+ # 本文検索の走査スレッドからのイベントを 1 フレーム当たり最大 256 件取り込む
291
+ def poll_events
292
+ changed = false
293
+ 256.times do
294
+ event = begin
295
+ @events.pop(true)
296
+ rescue ThreadError
297
+ break
298
+ end
299
+ changed = true
300
+ type, value = event
301
+ case type
302
+ when :entry
303
+ @entries << value
304
+ @results << value
305
+ when :entries
306
+ # Zig 実装の結果はまとめて届くので、1 フレーム 256 件の上限に縛られない
307
+ @entries.concat(value)
308
+ @results.concat(value)
309
+ when :error then @errors << value
310
+ when :skipped then @skipped_files += value || 1
311
+ when :done then @scanning = false
312
+ end
313
+ end
314
+ changed
315
+ end
316
+
317
+ # あいまい検索の一致位置(UTF-8 の先頭バイトオフセット)を表示桁に変換してハイライトする
318
+ def highlight_positions(screen, y, prefix, entry, width)
319
+ offsets = entry[:positions]
320
+ # 照合時に位置を求めなかった下位の行は、表示する行だけここで求める(照合と同じ位置になる)
321
+ offsets = FuzzySearch.positions(entry[:text], @shown.query) if offsets.nil? && @shown
322
+ return if offsets.nil? || offsets.empty?
323
+
324
+ targets = offsets.each_with_object({}) { |offset, set| set[offset] = true }
325
+ line = "#{prefix}#{entry[:text]}"
326
+ limit = TextUtils.display_width(line) > width ? width - TextUtils::ELLIPSIS_MIN_WIDTH : width
327
+ x = TextUtils.display_width(prefix)
328
+ byte = 0
329
+ entry[:text].each_char do |char|
330
+ shown = char.match?(/[[:cntrl:]]/) ? ' ' : char
331
+ char_width = TextUtils.display_width(shown)
332
+ break if x + char_width > limit
333
+
334
+ screen.put(x, y, shown, fg: MATCH_FG, bg: MATCH_BG, width: char_width) if targets[byte]
335
+ x += char_width
336
+ byte += char.bytesize
337
+ end
338
+ end
339
+
340
+ def scan_roots(roots, events, type, query)
341
+ visited_dirs = {}
342
+ excluded_names = @excluded_extensions.select { |e| e.start_with?('/') }.map { |e| e.delete_prefix('/') }
343
+ excluded_suffixes = @excluded_extensions.reject { |e| e.start_with?('/') }
344
+ roots.each do |name, root|
345
+ begin
346
+ root = File.expand_path(root)
347
+ raise Errno::ENOTDIR, root unless File.directory?(root)
348
+
349
+ pending = [root]
350
+ until pending.empty?
351
+ directory = pending.pop
352
+ canonical = File.realpath(directory)
353
+ next if visited_dirs[canonical]
354
+
355
+ visited_dirs[canonical] = true
356
+ begin
357
+ Dir.each_child(directory) do |child|
358
+ path = File.join(directory, child)
359
+ folded_child = child.scrub.downcase
360
+ # ディレクトリシンボリックリンクは追わず、循環・範囲外の走査を防ぐ。
361
+ if File.directory?(path)
362
+ pending << path unless File.symlink?(path) || excluded_names.include?(folded_child)
363
+ elsif File.file?(path)
364
+ if excluded_names.include?(folded_child) || (!excluded_suffixes.empty? && folded_child.end_with?(*excluded_suffixes))
365
+ events << [:skipped, nil]
366
+ next
367
+ end
368
+
369
+ entry = { path: path, bookmark: name, relative_path: path.delete_prefix(root + File::SEPARATOR) }
370
+ if type == :content
371
+ scan_content(entry, query, events)
372
+ else
373
+ events << [:entry, entry]
374
+ end
375
+ end
376
+ end
377
+ rescue SystemCallError, IOError => e
378
+ events << [:error, "#{directory}: #{e.message}"]
379
+ end
380
+ end
381
+ rescue SystemCallError, IOError => e
382
+ events << [:error, "#{name}: #{e.message}"]
383
+ end
384
+ end
385
+ end
386
+
387
+ # Zig 実装でブックマーク配下のファイル一覧を並列走査する
388
+ def scan_files_natively(roots, events, cancelled: nil)
389
+ valid_roots = []
390
+ roots.each do |name, root|
391
+ root = File.expand_path(root)
392
+ raise Errno::ENOTDIR, root unless File.directory?(root)
393
+
394
+ valid_roots << [name, root]
395
+ rescue SystemCallError, IOError => e
396
+ events << [:error, "#{name}: #{e.message}"]
397
+ end
398
+ return if valid_roots.empty?
399
+
400
+ # ラベル列を受け取れる相手(FileNameSource::Sink)には、ファイルごとのイベントを作らずに渡す
401
+ labels = events.respond_to?(:add_labels) && NativeContentSearch.labels_available?
402
+ engine = NativeContentSearch.new(roots: valid_roots.map(&:last), query: nil,
403
+ excluded_extensions: @excluded_extensions, labels: labels)
404
+ # 大きな取り出しは分けて受け取り、解析の合間に検索ワーカーと UI が動けるようにする
405
+ engine.each_batch(cancelled: cancelled, max_events: FileNameSource::BLOCK_SIZE) do |batch|
406
+ entries = []
407
+ batch.each do |kind, *args|
408
+ case kind
409
+ when :labels
410
+ unless entries.empty?
411
+ events << [:entries, entries]
412
+ entries = []
413
+ end
414
+ name, root = valid_roots[args[0]]
415
+ events.add_labels(name, root, args[1], args[2])
416
+ when :file, :match
417
+ name, root = valid_roots[args[0]]
418
+ path = args[1]
419
+ entries << { path: path, bookmark: name, relative_path: path.delete_prefix(root + File::SEPARATOR) }
420
+ when :error then events << [:error, args[1]]
421
+ when :skipped then events << [:skipped, args[0]]
422
+ end
423
+ end
424
+ events << [:entries, entries] unless entries.empty?
425
+ end
426
+ ensure
427
+ engine&.close
428
+ end
429
+
430
+ # Zig 実装で走査・検索し、PDF などのドキュメントだけ Ruby 側で抽出する
431
+ def scan_roots_natively(roots, events, query, cache)
432
+ valid_roots = []
433
+ roots.each do |name, root|
434
+ root = File.expand_path(root)
435
+ raise Errno::ENOTDIR, root unless File.directory?(root)
436
+
437
+ valid_roots << [name, root]
438
+ rescue SystemCallError, IOError => e
439
+ events << [:error, "#{name}: #{e.message}"]
440
+ end
441
+ return if valid_roots.empty?
442
+
443
+ engine = NativeContentSearch.new(roots: valid_roots.map(&:last), query: query,
444
+ excluded_extensions: @excluded_extensions,
445
+ document_extensions: DocumentTextExtractor::EXTENSIONS, cache: cache)
446
+ engine.each_batch do |batch|
447
+ entries = []
448
+ batch.each do |kind, *args|
449
+ case kind
450
+ when :match, :document
451
+ name, root = valid_roots[args[0]]
452
+ path = args[1]
453
+ entry = { path: path, bookmark: name, relative_path: path.delete_prefix(root + File::SEPARATOR) }
454
+ if kind == :document
455
+ scan_content(entry, query, events)
456
+ else
457
+ entries << entry.merge(line_number: args[2], match_text: args[3])
458
+ end
459
+ when :error then events << [:error, args[1]]
460
+ when :skipped then events << [:skipped, args[0]]
461
+ end
462
+ end
463
+ events << [:entries, entries] unless entries.empty?
464
+ end
465
+ ensure
466
+ engine&.close
467
+ end
468
+
469
+ def scan_content(entry, query, events)
470
+ if @document_extractor.supported?(entry[:path])
471
+ @document_cache.each_record(entry[:path]) do |record|
472
+ match_index = record[:search_text].index(query)
473
+ next unless match_index
474
+
475
+ snippet = record[:text][[match_index - 30, 0].max, 200].to_s.strip
476
+ metadata = record.reject { |key, _| key == :text || key == :search_text }
477
+ events << [:entry, entry.merge(metadata).merge(match_text: snippet)]
478
+ end
479
+ return
480
+ end
481
+
482
+ File.open(entry[:path], 'rb') do |file|
483
+ sample = file.read(8192).to_s
484
+ if sample.include?("\0")
485
+ events << [:skipped, nil]
486
+ return
487
+ end
488
+
489
+ file.rewind
490
+ file.each_line.with_index(1) do |raw_line, number|
491
+ line = raw_line.force_encoding(Encoding::UTF_8).scrub
492
+ match_index = line.downcase.index(query)
493
+ next unless match_index
494
+
495
+ snippet_start = [match_index - 30, 0].max
496
+ snippet = line[snippet_start, 200].strip
497
+ events << [:entry, entry.merge(line_number: number, match_text: snippet)]
498
+ end
499
+ end
500
+ rescue SystemCallError, IOError, DocumentTextExtractor::ExtractionError => e
501
+ events << [:error, "#{entry[:path]}: #{e.message}"]
502
+ end
503
+
504
+ def write_line(screen, y, text, width, color = nil, highlight_from: nil)
505
+ safe_text = text.scrub.gsub(/[[:cntrl:]]/, ' ')
506
+ visible = TextUtils.truncate_to_width(safe_text, width)
507
+ screen.put_string(0, y, visible, fg: color)
508
+ return unless highlight_from
509
+
510
+ match_ranges(visible, highlight_from).each do |start, length|
511
+ x = TextUtils.display_width(visible[0, start])
512
+ screen.put_string(x, y, visible[start, length], fg: MATCH_FG, bg: MATCH_BG)
513
+ end
514
+ end
515
+
516
+ # 検索と同じく大文字小文字を区別せず、from 文字目以降の一致位置を [開始, 長さ] で返す
517
+ def match_ranges(text, from)
518
+ needle = @query.to_s.downcase.chars
519
+ return [] if needle.empty?
520
+
521
+ folded = text.chars.map(&:downcase)
522
+ ranges = []
523
+ index = from
524
+ while index + needle.length <= folded.length
525
+ if folded[index, needle.length] == needle
526
+ ranges << [index, needle.length]
527
+ index += needle.length
528
+ else
529
+ index += 1
530
+ end
531
+ end
532
+ ranges
533
+ end
534
+
535
+ # ファイル名検索の候補を FuzzySearchSession に流す。既存の走査(Zig / Ruby)のイベントを
536
+ # バッチに変換し、停止要求があれば次のイベントで走査を打ち切る。
537
+ class FileNameSource
538
+ BLOCK_SIZE = 4096
539
+ Cancelled = Class.new(StandardError)
540
+
541
+ attr_reader :skipped
542
+
543
+ def initialize(search, roots, native)
544
+ @search = search
545
+ @roots = roots
546
+ @native = native
547
+ @skipped = 0
548
+ end
549
+
550
+ def each_batch(cancelled:, on_error:, &emit)
551
+ sink = Sink.new(self, cancelled, on_error, emit)
552
+ if @native && NativeContentSearch.files_available?
553
+ @search.send(:scan_files_natively, @roots, sink, cancelled: cancelled)
554
+ else
555
+ @search.send(:scan_roots, @roots, sink, :filename, '')
556
+ end
557
+ sink.flush
558
+ rescue Cancelled
559
+ nil
560
+ end
561
+
562
+ def add_skipped(count)
563
+ @skipped += count
564
+ end
565
+
566
+ # 「ブックマークのルート + 相対パス」から行を作る。scrub した候補だけ元のパスと相対パスを別に持つ
567
+ class Rows
568
+ def initialize(prefix, bookmark, encoding, exceptions)
569
+ @prefix = prefix
570
+ @bookmark = bookmark
571
+ @encoding = encoding
572
+ @exceptions = exceptions
573
+ freeze
574
+ end
575
+
576
+ def call(index, text)
577
+ path, relative = @exceptions && @exceptions[index]
578
+ relative ||= @encoding == Encoding::UTF_8 ? text : text.b.force_encoding(@encoding).freeze
579
+ { text: text, path: path || (@prefix + text.b).force_encoding(@encoding).freeze,
580
+ bookmark: @bookmark, relative_path: relative }
581
+ end
582
+ end
583
+
584
+ # scan_roots / scan_files_natively が使う events << [種類, 値] を受け取る。
585
+ # 候補は行(Hash)にせず、同じブックマークが続く間は 1 つの FuzzyCandidateBlock に詰める。
586
+ class Sink
587
+ def initialize(source, cancelled, on_error, emit)
588
+ @source = source
589
+ @cancelled = cancelled
590
+ @on_error = on_error
591
+ @emit = emit
592
+ @builder = FuzzyCandidateBlock::Builder.new
593
+ @exceptions = nil
594
+ @prefix_text = nil
595
+ end
596
+
597
+ def <<(event)
598
+ raise Cancelled if @cancelled.call
599
+
600
+ type, value = event
601
+ case type
602
+ when :entry then add(value)
603
+ when :entries then value.each { |entry| add(entry) }
604
+ when :error then @on_error.call(value)
605
+ when :skipped then @source.add_skipped(value || 1)
606
+ end
607
+ flush if type == :entries
608
+ self
609
+ end
610
+
611
+ # Zig のラベル列(ルートからの相対パス NUL の連結)をそのままブロックにして渡す
612
+ def add_labels(bookmark, root, packed, count)
613
+ raise Cancelled if @cancelled.call
614
+
615
+ flush
616
+ prefix = (root.end_with?(File::SEPARATOR) ? root : root + File::SEPARATOR).b.freeze
617
+ rows = Rows.new(prefix, frozen(bookmark), Encoding.find('filesystem'), nil)
618
+ @emit.call(FuzzyCandidateBlock.new(packed.freeze, count, rows: rows, checked: true))
619
+ end
620
+
621
+ def flush
622
+ return if @builder.empty?
623
+
624
+ rows = Rows.new(@prefix, @bookmark, @encoding, @exceptions&.freeze)
625
+ block = @builder.build(rows)
626
+ @builder = FuzzyCandidateBlock::Builder.new
627
+ @exceptions = nil
628
+ @emit.call(block)
629
+ end
630
+
631
+ private
632
+
633
+ def frozen(value)
634
+ value.is_a?(String) && !value.frozen? ? value.dup.freeze : value
635
+ end
636
+
637
+ def add(entry)
638
+ relative = entry[:relative_path]
639
+ path = entry[:path]
640
+ text = relative.encoding == Encoding::UTF_8 ? relative : relative.dup.force_encoding(Encoding::UTF_8)
641
+ scrubbed = !text.valid_encoding?
642
+ text = text.scrub if scrubbed
643
+ if text.bytesize > FuzzyCandidateBlock::MAX_TEXT_BYTES || text.include?("\0")
644
+ @on_error.call("#{text[0, 200]}: file name cannot be searched")
645
+ return
646
+ end
647
+
648
+ tail = tail?(path, relative)
649
+ start_block(entry, path, tail ? path.bytesize - relative.bytesize : 0) unless fits?(entry, path, relative)
650
+ index = @builder.add(text)
651
+ # 「接頭辞 + 表示名」で組み立て直せない候補は、元の文字列をそのまま持つ
652
+ if scrubbed || !tail || relative.encoding != @encoding
653
+ (@exceptions ||= {})[index] = [frozen(path), frozen(relative)].freeze
654
+ end
655
+ flush if @builder.size >= BLOCK_SIZE
656
+ end
657
+
658
+ def tail?(path, relative)
659
+ path.end_with?(relative)
660
+ rescue Encoding::CompatibilityError
661
+ false
662
+ end
663
+
664
+ # 詰めている途中のブロックと同じブックマーク・同じルートの候補か
665
+ def fits?(entry, path, relative)
666
+ @prefix_text && entry[:bookmark] == @bookmark && path.encoding == @encoding &&
667
+ path.bytesize == @prefix_text.bytesize + relative.bytesize && path.start_with?(@prefix_text)
668
+ end
669
+
670
+ def start_block(entry, path, prefix_length)
671
+ flush
672
+ @bookmark = frozen(entry[:bookmark])
673
+ @encoding = path.encoding
674
+ @prefix_text = path.byteslice(0, prefix_length).freeze
675
+ @prefix = @prefix_text.b.freeze
676
+ end
677
+ end
678
+ end
679
+ end
680
+ end