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,426 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'thread'
4
+ require_relative 'fuzzy_search'
5
+ require_relative 'fuzzy_candidate_block'
6
+ require_relative 'fuzzy_file_source'
7
+
8
+ module Rufio
9
+ # One-shot asynchronous session. The UI calls start/update_query/poll/close;
10
+ # the index worker alone creates, uses and destroys the fuzzy index. Source
11
+ # producers must check the supplied cancellation callback between batches.
12
+ # A batch is an array of rows or a FuzzyCandidateBlock. Blocks are registered as
13
+ # packed text and only the candidates that reach the results become Ruby rows.
14
+ class FuzzySearchSession
15
+ BATCH_SIZE = 256
16
+ MAX_PENDING_BATCHES = 4
17
+ MAX_ERRORS = 100
18
+ REFRESH_INTERVAL = 0.05
19
+ EMPTY = [].freeze
20
+ State = Struct.new(:generation, :query, :results, :total_matches, :candidate_count,
21
+ :scanning, :searching, :errors, keyword_init: true)
22
+
23
+ attr_reader :snapshot
24
+
25
+ # position_limit: 一致位置を求める上位の件数(省略時は limit 件すべて)。それより後の結果の
26
+ # :positions は nil で、表示するときに FuzzySearch.positions で求める。
27
+ def initialize(root: nil, source: nil, native: true, library: nil, limit: 100,
28
+ index_factory: nil, refresh_interval: REFRESH_INTERVAL, position_limit: nil)
29
+ raise ArgumentError, 'Specify either root or source' unless root.nil? != source.nil?
30
+ unless limit.is_a?(Integer) && limit.between?(0, FuzzySearch::MAX_RESULTS)
31
+ raise ArgumentError, 'Invalid result limit'
32
+ end
33
+ unless refresh_interval.is_a?(Numeric) && refresh_interval.real? &&
34
+ refresh_interval.finite? && refresh_interval >= 0
35
+ raise ArgumentError, 'Invalid refresh interval'
36
+ end
37
+
38
+ @source = source || FuzzyFileSource.new(root, native: native)
39
+ raise ArgumentError, 'Source must implement each_batch' unless @source.respond_to?(:each_batch)
40
+
41
+ @index_factory = index_factory || -> { FuzzySearch.new(native: native, library: library) }
42
+ @limit = limit
43
+ unless position_limit.nil? || (position_limit.is_a?(Integer) && position_limit >= 0)
44
+ raise ArgumentError, 'Invalid position limit'
45
+ end
46
+
47
+ @position_limit = position_limit
48
+ @refresh_interval = refresh_interval.to_f
49
+ @mutex = Mutex.new
50
+ @wake = ConditionVariable.new
51
+ @threads = []
52
+ @batches = []
53
+ @revision = 0
54
+ @started = false
55
+ @closed = false
56
+ @failed = false
57
+ @source_done = false
58
+ @error_messages = []
59
+ @pending_snapshot = nil
60
+ @snapshot = State.new(generation: 0, query: ''.freeze, results: EMPTY, total_matches: 0,
61
+ candidate_count: 0, scanning: false, searching: false, errors: EMPTY).freeze
62
+ end
63
+
64
+ def start
65
+ starting = false
66
+ @mutex.synchronize do
67
+ raise IOError, 'Session has already started or closed' if @started || @closed
68
+
69
+ @started = true
70
+ starting = true
71
+ change_state(scanning: true, searching: true)
72
+ @threads << Thread.new { run_index }
73
+ @threads << Thread.new { run_source }
74
+ end
75
+ self
76
+ rescue StandardError
77
+ close if starting
78
+ raise
79
+ end
80
+
81
+ def active?
82
+ @mutex.synchronize { @started && !@closed }
83
+ end
84
+
85
+ def query
86
+ @snapshot.query
87
+ end
88
+
89
+ def generation
90
+ @snapshot.generation
91
+ end
92
+
93
+ def results
94
+ @snapshot.results
95
+ end
96
+
97
+ def total_matches
98
+ @snapshot.total_matches
99
+ end
100
+
101
+ def candidate_count
102
+ @snapshot.candidate_count
103
+ end
104
+
105
+ def scanning?
106
+ @snapshot.scanning
107
+ end
108
+
109
+ def searching?
110
+ @snapshot.searching
111
+ end
112
+
113
+ def errors
114
+ @snapshot.errors
115
+ end
116
+
117
+ def update_query(text)
118
+ @mutex.synchronize do
119
+ raise IOError, 'Session is not accepting input' unless @started && !cancelled_locked?
120
+ unless text.is_a?(String) && text.bytesize <= FuzzySearch::MAX_QUERY_BYTES
121
+ raise ArgumentError, 'Invalid search query'
122
+ end
123
+
124
+ text = text.dup.force_encoding(Encoding::UTF_8)
125
+ raise ArgumentError, 'Invalid UTF-8 or NUL in query' unless text.valid_encoding? && !text.include?("\0")
126
+ return generation if text == query
127
+
128
+ # A result for the previous query must not remain selectable, even if
129
+ # the index is still running it or it already arrived before poll.
130
+ @pending_snapshot = nil
131
+ change_state(generation: generation + 1, query: text.freeze, results: EMPTY,
132
+ total_matches: 0, searching: true)
133
+ @revision += 1
134
+ @wake.broadcast
135
+ generation
136
+ end
137
+ end
138
+
139
+ # At most one immutable snapshot is pending; the UI never drains a queue of
140
+ # obsolete results, and the generation check also runs at publication time.
141
+ def poll
142
+ @mutex.synchronize do
143
+ pending = @pending_snapshot
144
+ @pending_snapshot = nil
145
+ return false if @closed || !pending || pending.generation != generation
146
+
147
+ @snapshot = pending
148
+ true
149
+ end
150
+ end
151
+
152
+ # Nonblocking. No Thread#kill, joins, or native destroy from the caller.
153
+ def close
154
+ @mutex.synchronize do
155
+ return if @closed
156
+
157
+ @closed = true
158
+ @batches.clear
159
+ @pending_snapshot = nil
160
+ change_state(results: EMPTY, total_matches: 0, candidate_count: 0, scanning: false, searching: false)
161
+ @wake.broadcast
162
+ end
163
+ nil
164
+ end
165
+
166
+ # Explicit cleanup barrier, outside the input loop. A running native query
167
+ # completes before its owner frees the handle. False means cleanup is pending.
168
+ def wait(timeout: nil)
169
+ if timeout && (!timeout.is_a?(Numeric) || !timeout.real? || !timeout.finite? || timeout < 0)
170
+ raise ArgumentError, 'Invalid wait timeout'
171
+ end
172
+ deadline = timeout && monotonic + timeout
173
+ threads = @mutex.synchronize { @threads.dup }
174
+ threads.each do |thread|
175
+ remaining = deadline && [deadline - monotonic, 0].max
176
+ return false unless thread.join(remaining)
177
+ end
178
+ true
179
+ end
180
+
181
+ private
182
+
183
+ def monotonic
184
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
185
+ end
186
+
187
+ def change_state(**changes)
188
+ @snapshot = State.new(**@snapshot.to_h.merge(changes)).freeze
189
+ end
190
+
191
+ def cancelled_locked?
192
+ @closed || @failed
193
+ end
194
+
195
+ def cancelled?
196
+ @mutex.synchronize { cancelled_locked? }
197
+ end
198
+
199
+ def immutable_entry(value)
200
+ row = value.is_a?(String) ? { text: value } : value
201
+ raise ArgumentError, 'Candidate must contain text' unless row.is_a?(Hash) && row[:text].is_a?(String)
202
+ return row if reusable?(row)
203
+
204
+ copied = row.each_with_object({}) do |(key, item), copy|
205
+ unless item.is_a?(String) || item.is_a?(Numeric) || item.is_a?(Symbol) ||
206
+ item.nil? || item == true || item == false
207
+ raise ArgumentError, 'Candidate metadata must contain scalar values'
208
+ end
209
+ copy[key] = item.is_a?(String) ? item.dup.freeze : item
210
+ end
211
+ text = row[:text].dup.force_encoding(Encoding::UTF_8)
212
+ unless text.valid_encoding? && !text.include?("\0") && text.bytesize <= FuzzySearch::MAX_CANDIDATE_BYTES
213
+ raise ArgumentError, 'Invalid candidate text'
214
+ end
215
+ copied[:text] = text.freeze
216
+ copied.freeze
217
+ end
218
+
219
+ # A frozen row whose strings are frozen cannot change after it is queued, so the
220
+ # session keeps it as is instead of copying every candidate (sources freeze rows).
221
+ def reusable?(row)
222
+ return false unless row.frozen?
223
+
224
+ text = row[:text]
225
+ return false unless text.frozen? && text.encoding == Encoding::UTF_8 && text.valid_encoding? &&
226
+ !text.include?("\0") && text.bytesize <= FuzzySearch::MAX_CANDIDATE_BYTES
227
+
228
+ row.each_value.all? do |item|
229
+ item.is_a?(String) ? item.frozen? : (item.is_a?(Numeric) || item.is_a?(Symbol) || item.nil? || item == true || item == false)
230
+ end
231
+ end
232
+
233
+ # 登録済みの候補。ブロックは詰めたまま持ち、結果に出す候補だけ行にする
234
+ class Entries
235
+ attr_reader :length
236
+
237
+ def initialize
238
+ @starts = []
239
+ @parts = []
240
+ @length = 0
241
+ end
242
+
243
+ def add(part)
244
+ if part.is_a?(Array) && @parts.last.is_a?(Array)
245
+ @parts.last.concat(part)
246
+ else
247
+ @starts << @length
248
+ @parts << (part.is_a?(Array) ? part.dup : part)
249
+ end
250
+ @length += part.size
251
+ end
252
+
253
+ def fetch(id)
254
+ raise IndexError, "candidate #{id} is not registered" unless id.is_a?(Integer) && id >= 0 && id < @length
255
+
256
+ at = (@starts.bsearch_index { |start| start > id } || @starts.length) - 1
257
+ part = @parts[at]
258
+ part.is_a?(Array) ? part.fetch(id - @starts[at]) : part.entry(id - @starts[at])
259
+ end
260
+
261
+ def clear
262
+ @starts.clear
263
+ @parts.clear
264
+ @length = 0
265
+ end
266
+ end
267
+
268
+ def enqueue(batch)
269
+ rows = batch.is_a?(FuzzyCandidateBlock) ? batch : batch.map { |row| immutable_entry(row) }.freeze
270
+ return true if rows.empty?
271
+
272
+ @mutex.synchronize do
273
+ while @batches.length >= MAX_PENDING_BATCHES && !cancelled_locked?
274
+ @wake.wait(@mutex)
275
+ end
276
+ return false if cancelled_locked?
277
+
278
+ @batches << rows
279
+ @revision += 1
280
+ @wake.broadcast
281
+ true
282
+ end
283
+ end
284
+
285
+ def record_error(message)
286
+ @mutex.synchronize do
287
+ return if cancelled_locked? || @error_messages.length >= MAX_ERRORS
288
+
289
+ @error_messages << message.to_s.dup.force_encoding(Encoding::UTF_8).scrub.freeze
290
+ @revision += 1
291
+ @wake.broadcast
292
+ end
293
+ end
294
+
295
+ def run_source
296
+ @source.each_batch(cancelled: method(:cancelled?), on_error: method(:record_error)) do |batch|
297
+ break if cancelled?
298
+
299
+ if batch.is_a?(FuzzyCandidateBlock)
300
+ break unless enqueue(batch)
301
+
302
+ # ブロックは待ち行列でほとんど待たされないので、検索ワーカーと UI に実行を譲る
303
+ Thread.pass
304
+ else
305
+ batch.each_slice(BATCH_SIZE) do |part|
306
+ break unless enqueue(part)
307
+ end
308
+ end
309
+ end
310
+ rescue StandardError, NoMemoryError => e
311
+ record_error("#{e.class}: #{e.message}")
312
+ ensure
313
+ @mutex.synchronize do
314
+ @source = nil
315
+ @source_done = true
316
+ @revision += 1
317
+ @wake.broadcast
318
+ end
319
+ end
320
+
321
+ def take_work(previous_revision, refresh_at)
322
+ @mutex.synchronize do
323
+ while @revision == previous_revision && !cancelled_locked?
324
+ remaining = refresh_at && refresh_at - monotonic
325
+ break if remaining && remaining <= 0
326
+
327
+ @wake.wait(@mutex, remaining)
328
+ end
329
+ return if cancelled_locked?
330
+
331
+ batches = @batches
332
+ @batches = []
333
+ @wake.broadcast
334
+ [@revision, batches]
335
+ end
336
+ end
337
+
338
+ def publish(current_generation, text, matches, total, count, searching)
339
+ @mutex.synchronize do
340
+ return if cancelled_locked? || generation != current_generation
341
+
342
+ @pending_snapshot = State.new(generation: current_generation, query: text, results: matches,
343
+ total_matches: total, candidate_count: count,
344
+ scanning: !@source_done || !@batches.empty?, searching: searching,
345
+ errors: @error_messages.dup.freeze).freeze
346
+ end
347
+ end
348
+
349
+ def run_index
350
+ entries = Entries.new
351
+ index = nil
352
+ return if cancelled?
353
+
354
+ index = @index_factory.call
355
+ previous_revision = -1
356
+ signature = nil
357
+ matches = EMPTY
358
+ total = 0
359
+ refresh_at = nil
360
+ next_query_at = 0
361
+ while (work = take_work(previous_revision, refresh_at))
362
+ previous_revision, batches = work
363
+ batches.each do |batch|
364
+ break if cancelled?
365
+
366
+ if !batch.is_a?(FuzzyCandidateBlock)
367
+ index.add(batch.map { |row| row[:text] })
368
+ elsif index.respond_to?(:add_packed)
369
+ index.add_packed(batch.packed)
370
+ else
371
+ index.add(batch.texts)
372
+ end
373
+ entries.add(batch)
374
+ end
375
+ break if cancelled?
376
+
377
+ current_generation, text, complete = @mutex.synchronize do
378
+ [generation, query, @source_done && @batches.empty?]
379
+ end
380
+ desired = [current_generation, entries.length]
381
+ dirty = signature != desired
382
+ # Input changes and a complete scan bypass throttling. Candidate-only
383
+ # changes are batched so loading N files doesn't trigger N/B full scans.
384
+ force = signature.nil? || signature[0] != current_generation || complete
385
+ if dirty && (force || monotonic >= next_query_at)
386
+ raw = @position_limit ? index.query(text, limit: @limit, positions: @position_limit) : index.query(text, limit: @limit)
387
+ break if cancelled?
388
+
389
+ total = index.total_matches
390
+ matches = raw.map do |match|
391
+ match.merge(positions: match[:positions].dup.freeze, entry: entries.fetch(match[:id])).freeze
392
+ end.freeze
393
+ signature = desired
394
+ dirty = false
395
+ # 候補がまだない検索は集約の待ち時間を始めない(最初の候補が届いたらすぐ照合する)
396
+ next_query_at = entries.length.zero? ? 0 : monotonic + @refresh_interval
397
+ end
398
+ refresh_at = dirty ? next_query_at : nil
399
+ publish(current_generation, text, matches, total, entries.length, dirty)
400
+ end
401
+ rescue StandardError, NoMemoryError => e
402
+ fail_session(e)
403
+ ensure
404
+ entries.clear
405
+ begin
406
+ index&.close
407
+ rescue StandardError, NoMemoryError => e
408
+ fail_session(e)
409
+ end
410
+ end
411
+
412
+ def fail_session(error)
413
+ @mutex.synchronize do
414
+ return if @closed
415
+
416
+ @failed = true
417
+ @batches.clear
418
+ @error_messages << "#{error.class}: #{error.message}".freeze if @error_messages.length < MAX_ERRORS
419
+ @pending_snapshot = State.new(generation: generation, query: query, results: EMPTY,
420
+ total_matches: 0, candidate_count: 0, scanning: false, searching: false,
421
+ errors: @error_messages.dup.freeze).freeze
422
+ @wake.broadcast
423
+ end
424
+ end
425
+ end
426
+ end
@@ -0,0 +1,223 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'kitty_graphics'
4
+ require_relative 'terminal_graphics'
5
+
6
+ module Rufio
7
+ # 端末に置いた画像の状態を持ち、セル差分描画の後に APC を書き出す層。
8
+ #
9
+ # 描画側(UIRenderer)は毎フレーム request / clear を呼ぶだけで、実際に送るかは
10
+ # ここが決める。前のフレームと同じ画像・同じ位置で、矩形の中が書き換えられても
11
+ # いなければ 1 バイトも出さない(静止時のコストを 0 にして、差分描画の方針に合わせる)。
12
+ #
13
+ # 送る条件:
14
+ # - 置いていない画像を頼まれた(別のファイルへ移ったときは少し待つ = デバウンス)
15
+ # - 置き場所・切り出し(ズーム)が変わった
16
+ # - 置いてある矩形の中のセルが書き換えられた(通知やモード切替で画像が削れたとき)
17
+ class GraphicsLayer
18
+ # 画像 ID は他アプリと衝突しないよう rufio の印と PID から決める
19
+ ID_BASE = 0x5200_0000
20
+ # 別のファイルへ移ってから送るまでの待ち(j/k の連打で MB 級の転送を繰り返さない)
21
+ DEFAULT_DEBOUNCE = 0.08
22
+ # 覚えておく画像の枚数と合計バイト数(Base64 後)
23
+ DEFAULT_CACHE_ENTRIES = 4
24
+ DEFAULT_CACHE_BYTES = 8 * 1024 * 1024
25
+
26
+ Placement = Struct.new(:source, :key, :payload, :encoded, :row, :col, :cols, :rows,
27
+ :area_rows, :format, :pixels, :crop, keyword_init: true)
28
+
29
+ attr_reader :id
30
+
31
+ def initialize(id: nil, passthrough: false, debounce: DEFAULT_DEBOUNCE,
32
+ cache_entries: DEFAULT_CACHE_ENTRIES, cache_bytes: DEFAULT_CACHE_BYTES)
33
+ @id = id || (ID_BASE | ((Process.pid & 0xffff) << 8))
34
+ @passthrough = passthrough
35
+ @debounce = debounce.to_f
36
+ @cache_entries = cache_entries
37
+ @cache_bytes = cache_bytes
38
+ @cache = {}
39
+ @cache_size = 0
40
+ @placed = nil
41
+ @desired = nil
42
+ @failed = nil
43
+ @last_source = nil
44
+ @pending_since = nil
45
+ end
46
+
47
+ # このフレームで出したい画像を伝える(毎フレーム呼ばれる)
48
+ #
49
+ # @param source [Object] ペイロードの同一性(パスと mtime など)。これが変わると
50
+ # 別の画像として扱い、少し待ってから送る
51
+ # @param payload [String, #call] 端末へ送るバイト列。Proc を渡すと、実際に送ると
52
+ # 決まったときだけ呼ばれる(毎フレーム大きなファイルを読まないため)
53
+ # @param row [Integer] 矩形の左上の行(1 始まりの端末座標)
54
+ # @param col [Integer] 矩形の左上の桁(1 始まりの端末座標)
55
+ # @param crop [Array(Integer, Integer, Integer, Integer), nil] 元画像から切り出す
56
+ # 領域 [x, y, 幅, 高さ](ズーム)。nil なら全体
57
+ # @param encoded [Boolean] payload が既に Base64 済みなら true(ネイティブ経路)
58
+ def request(source:, payload:, row:, col:, cols: nil, rows: nil, area_rows: nil, encoded: false,
59
+ format: KittyGraphics::FORMAT_PNG, pixels: nil, crop: nil, now: monotonic)
60
+ # 別のファイルに移ったときだけ待つ(最初の 1 枚と置き直しは待たせない)
61
+ @pending_since = now if @last_source && @last_source != source
62
+ @last_source = source
63
+ occupied_rows = (area_rows || rows).to_i
64
+ @desired = Placement.new(source: source, key: [source, row, col, cols, rows, crop],
65
+ payload: payload, encoded: encoded, row: row, col: col,
66
+ cols: cols, rows: rows, area_rows: occupied_rows,
67
+ format: format, pixels: pixels, crop: crop)
68
+ true
69
+ end
70
+
71
+ # このフレームでは画像を出さない(置いてあれば flush で消える)。
72
+ # 直前に頼まれた画像(デバウンスの基準)は忘れない。描画側は毎フレーム
73
+ # clear してから request し直すため、ここで忘れると待ち時間が効かなくなる
74
+ def clear
75
+ @desired = nil
76
+ end
77
+
78
+ def placed?
79
+ !@placed.nil?
80
+ end
81
+
82
+ # 変化があれば端末へ書く
83
+ #
84
+ # @param rewritten_rows [Array<Integer>, nil] このフレームで Renderer が書き換えた
85
+ # 行(0 始まりの画面行)。画像の矩形と交差したら置き直す
86
+ # @return [Boolean] 何か書いたか
87
+ def flush(output, rewritten_rows: nil, now: monotonic)
88
+ return false if output.nil?
89
+ return false if @desired.nil? && @placed.nil?
90
+ return remove(output) if @desired.nil?
91
+
92
+ if @placed && @placed.key == @desired.key
93
+ # 同じ画像・同じ位置。矩形の中が書き換えられたときだけ置き直す
94
+ return false unless painted_over?(rewritten_rows)
95
+
96
+ return send_image(output)
97
+ end
98
+
99
+ # 別のファイルへ移ったときは、古い画像を先に消してから待つ
100
+ return remove(output) if @placed && @placed.source != @desired.source
101
+ return false if waiting?(now)
102
+ return false if @placed.nil? && @desired.key == @failed
103
+
104
+ send_image(output)
105
+ end
106
+
107
+ # 置いてある画像をすべて消す(終了処理・全画面の再描画)
108
+ def clear_all(output)
109
+ @desired = nil
110
+ @placed = nil
111
+ @failed = nil
112
+ @last_source = nil
113
+ @pending_since = nil
114
+ write(output, KittyGraphics.delete_all(passthrough: @passthrough))
115
+ end
116
+
117
+ private
118
+
119
+ def monotonic
120
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
121
+ end
122
+
123
+ def waiting?(now)
124
+ return false if @pending_since.nil? || @debounce <= 0
125
+
126
+ now - @pending_since < @debounce
127
+ end
128
+
129
+ # 画像の矩形(端末座標の 1 始まり)と、書き換えられた画面行(0 始まり)が重なるか
130
+ def painted_over?(rewritten_rows)
131
+ return false if rewritten_rows.nil? || rewritten_rows.empty?
132
+ return false unless @placed.area_rows.to_i.positive?
133
+
134
+ top = @placed.row - 1
135
+ bottom = top + @placed.area_rows - 1
136
+ rewritten_rows.any? { |row| row >= top && row <= bottom }
137
+ end
138
+
139
+ def remove(output)
140
+ return false unless @placed
141
+
142
+ @placed = nil
143
+ write(output, KittyGraphics.delete(id: @id, passthrough: @passthrough))
144
+ end
145
+
146
+ def send_image(output)
147
+ encoded = encoded_payload(@desired)
148
+ if encoded.nil? || encoded.empty?
149
+ # 読めなかった画像は覚えておき、毎フレーム読み直さない
150
+ @failed = @desired.key
151
+ return false
152
+ end
153
+
154
+ sequence = +''
155
+ # 置き換えは先に消す(同じ ID を上書きしない端末があるため)
156
+ sequence << KittyGraphics.delete(id: @id, passthrough: @passthrough) if @placed
157
+ sequence << KittyGraphics.place_at(row: @desired.row, col: @desired.col,
158
+ id: @id, payload: encoded, encoded: true,
159
+ cols: @desired.cols, rows: @desired.rows,
160
+ format: @desired.format, pixels: @desired.pixels,
161
+ crop: @desired.crop, passthrough: @passthrough)
162
+ return false unless write(output, sequence)
163
+
164
+ @placed = @desired
165
+ @failed = nil
166
+ @pending_since = nil
167
+ true
168
+ end
169
+
170
+ # Base64 済みのペイロードを返す。同じ画像は読み直さず、符号化もし直さない
171
+ def encoded_payload(desired)
172
+ key = desired.source
173
+ cached = @cache[key]
174
+ if cached
175
+ # 直近に使ったものを残す(LRU)
176
+ @cache.delete(key)
177
+ @cache[key] = cached
178
+ return cached
179
+ end
180
+
181
+ bytes = resolve(desired.payload)
182
+ return nil if bytes.nil? || bytes.empty?
183
+
184
+ # ネイティブ経路は Zig 側で Base64 済み(Ruby で数 MB を符号化しない)
185
+ encoded = desired.encoded ? bytes : [bytes].pack('m0')
186
+ store(key, encoded)
187
+ encoded
188
+ end
189
+
190
+ def store(key, encoded)
191
+ # 1 枚で上限を超える画像は覚えない(キャッシュが丸ごと入れ替わるのを防ぐ)
192
+ return if encoded.bytesize > @cache_bytes
193
+
194
+ @cache[key] = encoded
195
+ @cache_size += encoded.bytesize
196
+ while @cache.size > @cache_entries || @cache_size > @cache_bytes
197
+ oldest, value = @cache.first
198
+ break if oldest.nil?
199
+
200
+ @cache.delete(oldest)
201
+ @cache_size -= value.bytesize
202
+ end
203
+ end
204
+
205
+ # 送ると決まってから初めてバイト列を用意する
206
+ def resolve(payload)
207
+ payload.respond_to?(:call) ? payload.call : payload
208
+ rescue StandardError
209
+ nil
210
+ end
211
+
212
+ # 端末が閉じていても落ちない(画像はおまけの機能なので操作を止めない)
213
+ def write(output, sequence)
214
+ return false if output.nil? || sequence.nil? || sequence.empty?
215
+
216
+ output.write(sequence)
217
+ output.flush
218
+ true
219
+ rescue IOError, SystemCallError
220
+ false
221
+ end
222
+ end
223
+ end