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
@@ -14,6 +14,26 @@ module Rufio
14
14
  # 後方互換性のためのパス(非推奨)
15
15
  YAML_CONFIG_PATH = Config::YAML_CONFIG_PATH
16
16
  LOCAL_YAML_PATH = Config::LOCAL_YAML_PATH
17
+ # 改名・統合したアクション(旧名 => 新名)。ユーザー設定の旧名も受け付ける。
18
+ # 2.0.0 で検索を :search 一本にまとめたため、旧 s / / / F / G の設定は :search に移す
19
+ LEGACY_KEYBIND_ACTIONS = {
20
+ fzf_search: :search, fzf_search_alt: :search,
21
+ file_search: :search, file_search_alt: :search,
22
+ rga_search: :search, global_search: :search
23
+ }.freeze
24
+
25
+ # 表プレビュー(CSV / TSV / Excel / SQLite)の読み込み上限と表示設定。
26
+ # max_bytes はテキスト形式(CSV / TSV)を読む量。max_rows 行で解析を打ち切るため、
27
+ # ここを広げても解析時間は増えない(読み込みと文字コード判定の分だけ増える)。
28
+ DEFAULT_TABLE_PREVIEW = {
29
+ max_bytes: 512 * 1024, max_rows: 1000, max_columns: 256, max_column_width: 32
30
+ }.freeze
31
+ MIN_TABLE_PREVIEW = {
32
+ max_bytes: 1024, max_rows: 1, max_columns: 1, max_column_width: 3
33
+ }.freeze
34
+ MAX_TABLE_PREVIEW = {
35
+ max_bytes: 4 * 1024 * 1024, max_rows: 100_000, max_columns: 4096, max_column_width: 200
36
+ }.freeze
17
37
 
18
38
  class << self
19
39
  def load_config
@@ -58,14 +78,13 @@ module Rufio
58
78
  create_dir: 'A',
59
79
  move_selected: 'm',
60
80
  copy_selected: 'c',
81
+ copy_to_clipboard: 'y',
61
82
  delete_selected: 'x',
62
83
  open_explorer: 'e',
63
84
  # 選択・検索
64
85
  select: ' ',
65
86
  filter: 'f',
66
- fzf_search: 's',
67
- fzf_search_alt: '/',
68
- rga_search: 'F',
87
+ search: '/',
69
88
  # ブックマーク
70
89
  add_bookmark: 'b',
71
90
  bookmark_menu: 'B',
@@ -73,7 +92,6 @@ module Rufio
73
92
  start_dir: '0',
74
93
  # モード・ツール
75
94
  job_mode: 'J',
76
- global_search: 'G',
77
95
  config_mode: 'C',
78
96
  help: '?',
79
97
  log_viewer: 'L',
@@ -101,11 +119,42 @@ module Rufio
101
119
  raw_user_keybinds = load_config[:keybinds] || {}
102
120
  # 新フォーマット(単一文字列値)のみ受け入れ、古いフォーマット(配列値)は無視
103
121
  user_keybinds = raw_user_keybinds.select { |_, v| v.is_a?(String) }
104
- default_keybinds.merge(user_keybinds)
122
+ # 旧アクション名は新しい名前の別名として扱う(新しい名前の指定を優先)
123
+ legacy = user_keybinds.select { |action, _| LEGACY_KEYBIND_ACTIONS.key?(action) }
124
+ current = user_keybinds.reject { |action, _| LEGACY_KEYBIND_ACTIONS.key?(action) }
125
+ renamed = legacy.each_with_object({}) { |(action, key), map| map[LEGACY_KEYBIND_ACTIONS[action]] = key }
126
+ default_keybinds.merge(renamed).merge(current)
105
127
  end
106
128
 
107
- def global_search_excluded_extensions
108
- values = load_config[:global_search_excluded_extensions]
129
+ # クリップボードへコピーするコマンド(文字列または argv 配列)。
130
+ # 未設定なら OS ごとの既定コマンド → OSC 52 の順で試す。
131
+ def clipboard_command
132
+ value = load_config[:clipboard_command]
133
+ return value if value.is_a?(String) && !value.empty?
134
+ return value if value.is_a?(Array) && value.all? { |item| item.is_a?(String) } && !value.empty?
135
+
136
+ nil
137
+ end
138
+
139
+ # 表プレビュー設定(整数は min..max に丸め、不正な値は既定値のまま)
140
+ def table_preview
141
+ values = load_config[:table_preview]
142
+ values = {} unless values.is_a?(Hash)
143
+
144
+ settings = DEFAULT_TABLE_PREVIEW.each_with_object({}) do |(key, default), acc|
145
+ value = values[key]
146
+ acc[key] = value.is_a?(Integer) ? value.clamp(MIN_TABLE_PREVIEW[key], MAX_TABLE_PREVIEW[key]) : default
147
+ end
148
+
149
+ settings[:header] = values[:header] != false
150
+ settings[:delimiter] = values[:delimiter].is_a?(String) ? values[:delimiter] : 'auto'
151
+ settings[:encoding] = values[:encoding].is_a?(String) ? values[:encoding] : 'auto'
152
+ settings
153
+ end
154
+
155
+ # 検索(`/`)で中身を読まない拡張子・ディレクトリ
156
+ def search_excluded_extensions
157
+ values = load_config[:search_excluded_extensions]
109
158
  return [] unless values.is_a?(Array)
110
159
 
111
160
  values.select { |value| value.is_a?(String) }.map do |value|
@@ -294,7 +343,11 @@ module Rufio
294
343
  applications: safe_const_get(:APPLICATIONS, default_config[:applications]),
295
344
  colors: safe_const_get(:COLORS, default_config[:colors]),
296
345
  keybinds: safe_const_get(:KEYBINDS, {}),
297
- global_search_excluded_extensions: safe_const_get(:GLOBAL_SEARCH_EXCLUDED_EXTENSIONS, [])
346
+ # SEARCH_EXCLUDED_EXTENSIONS が新しい名前。旧名の設定もそのまま使える
347
+ search_excluded_extensions: safe_const_get(:SEARCH_EXCLUDED_EXTENSIONS,
348
+ safe_const_get(:GLOBAL_SEARCH_EXCLUDED_EXTENSIONS, [])),
349
+ table_preview: safe_const_get(:TABLE_PREVIEW, {}),
350
+ clipboard_command: safe_const_get(:CLIPBOARD_COMMAND, nil)
298
351
  }
299
352
 
300
353
  if Object.const_defined?(:LANGUAGE)
@@ -343,9 +396,11 @@ module Rufio
343
396
  selected: { hsl: [50, 90, 70] },
344
397
  preview: { hsl: [180, 60, 65] }
345
398
  },
346
- global_search_excluded_extensions: [],
347
- keybinds: {}, # ユーザーの上書きのみ格納(デフォルトはdefault_keybindsを参照)
348
- ui_options: {} # ユーザーの上書きのみ格納(デフォルトはdefault_ui_optionsを参照)
399
+ search_excluded_extensions: [],
400
+ keybinds: {}, # ユーザーの上書きのみ格納(デフォルトはdefault_keybindsを参照)
401
+ ui_options: {}, # ユーザーの上書きのみ格納(デフォルトはdefault_ui_optionsを参照)
402
+ table_preview: {}, # ユーザーの上書きのみ格納(デフォルトはDEFAULT_TABLE_PREVIEWを参照)
403
+ clipboard_command: nil # 未設定なら OS 既定のコマンド → OSC 52
349
404
  }
350
405
  end
351
406
  end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'csv'
4
+ require_relative 'table_source'
5
+ require_relative 'table_document'
6
+ require_relative 'encoding_detector'
7
+
8
+ module Rufio
9
+ # CSV / TSV を表として読む TableSource。
10
+ class CsvTableSource < TableSource
11
+ # 拡張子ごとの既定の区切り文字
12
+ DELIMITERS = {
13
+ '.csv' => ',',
14
+ '.tsv' => "\t",
15
+ '.tab' => "\t"
16
+ }.freeze
17
+
18
+ # 区切り文字の自動判定で数える候補
19
+ SNIFF_CANDIDATES = [',', ';', "\t"].freeze
20
+
21
+ class << self
22
+ def supports?(path)
23
+ DELIMITERS.key?(File.extname(path.to_s).downcase)
24
+ end
25
+
26
+ # @return [TableDocument]
27
+ def open(path, limits: TableSource::Limits.default, options: {})
28
+ decoded = EncodingDetector.read_text(
29
+ path, max_bytes: limits.max_bytes, encoding: options.fetch(:encoding, 'auto')
30
+ )
31
+ delimiter = resolve_delimiter(path, decoded.text, options[:delimiter])
32
+ rows, row_truncated, column_truncated = parse(decoded.text, delimiter, limits)
33
+
34
+ header = options.fetch(:header, true) && !rows.empty? ? rows.shift : nil
35
+ sheet = MemoryTableSheet.new(
36
+ name: File.basename(path.to_s), header: header, rows: rows,
37
+ row_truncated: row_truncated, column_truncated: column_truncated
38
+ )
39
+
40
+ TableDocument.new(
41
+ sheets: [sheet], encoding: decoded.encoding,
42
+ byte_truncated: decoded.truncated, label: File.basename(path.to_s)
43
+ )
44
+ end
45
+
46
+ private
47
+
48
+ # 設定 > 拡張子 > 1 行目の文字数による推定
49
+ def resolve_delimiter(path, text, configured)
50
+ return configured if configured.is_a?(String) && !configured.empty? && configured != 'auto'
51
+
52
+ default = DELIMITERS[File.extname(path.to_s).downcase] || ','
53
+ return default unless default == ','
54
+
55
+ sniff(text) || default
56
+ end
57
+
58
+ # 欧州式 CSV(';' 区切り)を拾う。',' より明らかに多い候補だけ採用する。
59
+ def sniff(text)
60
+ line = text.each_line.find { |candidate| !candidate.strip.empty? }
61
+ return nil unless line
62
+
63
+ counts = SNIFF_CANDIDATES.map { |char| [char, line.count(char)] }.to_h
64
+ best = counts.max_by { |_, count| count }
65
+ return nil if best.nil? || best[1].zero? || best[0] == ','
66
+ return nil unless best[1] > counts[',']
67
+
68
+ best[0]
69
+ end
70
+
71
+ def parse(text, delimiter, limits)
72
+ raw_rows = parse_rows(text, delimiter, limits.max_rows)
73
+ row_truncated = raw_rows.length > limits.max_rows
74
+ raw_rows = raw_rows[0, limits.max_rows] if row_truncated
75
+
76
+ column_truncated = false
77
+ rows = raw_rows.map do |row|
78
+ cells = Array(row).map { |value| value.nil? ? '' : value.to_s }
79
+ if cells.length > limits.max_columns
80
+ cells = cells[0, limits.max_columns]
81
+ column_truncated = true
82
+ end
83
+ cells
84
+ end
85
+
86
+ [rows, row_truncated, column_truncated]
87
+ end
88
+
89
+ # 壊れた CSV を 3 段階で読む。
90
+ # 1. 通常のパース
91
+ # 2. liberal_parsing(引用符の中途半端な使い方を許容する)
92
+ # 3. 閉じ引用符を補う(バイト上限が引用符つきセルの途中に当たった場合)
93
+ # すべて失敗したら ParseError にして、呼び出し側でテキストプレビューへ戻す。
94
+ #
95
+ # 表示する行数が決まっているので、読み込んだバイト全体をパースせず
96
+ # row_limit + 1 行で打ち切る。こうするとバイト上限を広げても解析時間は増えない。
97
+ def parse_rows(text, delimiter, row_limit)
98
+ attempts = [
99
+ [text, false],
100
+ [text, true],
101
+ ["#{text}\"", true]
102
+ ]
103
+
104
+ last_error = nil
105
+ attempts.each do |source, liberal|
106
+ return read_rows(source, delimiter, liberal, row_limit)
107
+ rescue CSV::MalformedCSVError, ArgumentError => e
108
+ last_error = e
109
+ end
110
+
111
+ raise TableSource::ParseError, last_error.message
112
+ end
113
+
114
+ # 切り詰めの有無を判定できるよう、上限より 1 行だけ多く読む
115
+ def read_rows(source, delimiter, liberal, row_limit)
116
+ rows = []
117
+ CSV.new(source, col_sep: delimiter, liberal_parsing: liberal).each do |row|
118
+ rows << row
119
+ break if rows.length > row_limit
120
+ end
121
+ rows
122
+ end
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rufio
4
+ # バイト列の文字コードを判定し、UTF-8 文字列に変換する。
5
+ #
6
+ # 判定順: BOM → UTF-8 → CP932 → EUC-JP → UTF-8(不正バイトは置換)
7
+ # CP932 と EUC-JP はどちらも「読めてしまう」ことがあるため、CP932 を先に試し、
8
+ # 結果が半角カタカナばかりになる場合だけ EUC-JP を採用するヒューリスティックを使う。
9
+ # 誤判定は設定(TABLE_PREVIEW の encoding)で上書きできる。
10
+ module EncodingDetector
11
+ UTF8_BOM = "\xEF\xBB\xBF".b
12
+ UTF16LE_BOM = "\xFF\xFE".b
13
+ UTF16BE_BOM = "\xFE\xFF".b
14
+
15
+ # 自動判定で試す日本語エンコーディング(CP932 を優先)
16
+ CP932 = 'CP932'
17
+ EUC_JP = 'EUC-JP'
18
+
19
+ REPLACEMENT = '?'
20
+
21
+ # CP932 として読んだ結果がこの割合を超えて半角カタカナなら EUC-JP を採用する
22
+ HALFWIDTH_KATAKANA_RATIO = 0.5
23
+
24
+ Result = Struct.new(:text, :encoding, :truncated, :replaced, keyword_init: true)
25
+
26
+ class << self
27
+ # 先頭 max_bytes までを読み、UTF-8 文字列に変換して返す。
28
+ # 上限で切るときは多バイト文字を割らないよう「上限内の最後の改行」までで切る。
29
+ #
30
+ # @param path [String]
31
+ # @param max_bytes [Integer]
32
+ # @param encoding [String] 'auto' または明示的なエンコーディング名
33
+ # @return [Result]
34
+ def read_text(path, max_bytes:, encoding: 'auto')
35
+ raw = File.binread(path, max_bytes + 1) || ''
36
+ raw = raw.b
37
+ truncated = raw.bytesize > max_bytes
38
+ raw = cut_at_line_boundary(raw, max_bytes) if truncated
39
+
40
+ result = decode(raw, encoding: encoding)
41
+ result.truncated = truncated
42
+ result
43
+ end
44
+
45
+ # @param raw [String] バイト列
46
+ # @return [Result]
47
+ def decode(raw, encoding: 'auto')
48
+ raw = raw.to_s.dup.force_encoding(Encoding::BINARY)
49
+ return decode_as(raw, encoding) unless auto?(encoding)
50
+
51
+ decode_bom(raw) || decode_utf8(raw) || decode_japanese(raw) || decode_with_replacement(raw)
52
+ end
53
+
54
+ private
55
+
56
+ def auto?(encoding)
57
+ encoding.nil? || encoding.to_s.empty? || encoding.to_s.casecmp?('auto')
58
+ end
59
+
60
+ # 上限内の最後の改行までで切る(行指向データなので境界が自然に取れる)。
61
+ # ただし 1 行が上限より長い場合、改行まで戻すとその行が丸ごと消えてしまうため、
62
+ # 半分以上を捨てることになるならバイト位置で切る(末尾の文字が割れても置換される)。
63
+ def cut_at_line_boundary(raw, max_bytes)
64
+ head = raw.byteslice(0, max_bytes)
65
+ index = head.rindex("\n".b)
66
+ return head if index.nil?
67
+
68
+ cut = head.byteslice(0, index + 1)
69
+ cut.bytesize * 2 >= max_bytes ? cut : head
70
+ end
71
+
72
+ def decode_bom(raw)
73
+ if raw.start_with?(UTF8_BOM)
74
+ body = raw.byteslice(UTF8_BOM.bytesize, raw.bytesize - UTF8_BOM.bytesize) || ''
75
+ decode_utf8(body)
76
+ elsif raw.start_with?(UTF16LE_BOM)
77
+ decode_utf16(raw, Encoding::UTF_16LE)
78
+ elsif raw.start_with?(UTF16BE_BOM)
79
+ decode_utf16(raw, Encoding::UTF_16BE)
80
+ end
81
+ end
82
+
83
+ # UTF-16 は BOM を除いた偶数バイト長で変換する(改行位置で切ると奇数になりうる)
84
+ def decode_utf16(raw, source)
85
+ body = raw.byteslice(2, raw.bytesize - 2) || ''
86
+ body = body.byteslice(0, body.bytesize - 1) if body.bytesize.odd?
87
+ text = body.force_encoding(source)
88
+ .encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
89
+ Result.new(text: strip_bom(text), encoding: source.to_s, truncated: false, replaced: false)
90
+ rescue EncodingError
91
+ nil
92
+ end
93
+
94
+ def decode_utf8(raw)
95
+ text = raw.dup.force_encoding(Encoding::UTF_8)
96
+ return nil unless text.valid_encoding?
97
+
98
+ Result.new(text: strip_bom(text), encoding: 'UTF-8', truncated: false, replaced: false)
99
+ end
100
+
101
+ def decode_japanese(raw)
102
+ cp932 = decode_candidate(raw, CP932)
103
+ euc_jp = decode_candidate(raw, EUC_JP)
104
+ return euc_jp unless cp932
105
+ return cp932 unless euc_jp
106
+
107
+ halfwidth_katakana_ratio(cp932.text) > HALFWIDTH_KATAKANA_RATIO ? euc_jp : cp932
108
+ end
109
+
110
+ def decode_candidate(raw, name)
111
+ source = raw.dup.force_encoding(name)
112
+ return nil unless source.valid_encoding?
113
+
114
+ Result.new(text: strip_bom(source.encode(Encoding::UTF_8)), encoding: name,
115
+ truncated: false, replaced: false)
116
+ rescue ArgumentError, EncodingError
117
+ nil
118
+ end
119
+
120
+ def decode_with_replacement(raw)
121
+ text = raw.dup.force_encoding(Encoding::UTF_8)
122
+ .encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
123
+ Result.new(text: strip_bom(text), encoding: 'UTF-8', truncated: false, replaced: true)
124
+ end
125
+
126
+ # 明示指定されたエンコーディングで変換する。未知の名前なら自動判定に戻す。
127
+ def decode_as(raw, name)
128
+ text = raw.dup.force_encoding(name)
129
+ .encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: REPLACEMENT)
130
+ Result.new(text: strip_bom(text), encoding: name.to_s, truncated: false, replaced: false)
131
+ rescue ArgumentError, EncodingError
132
+ decode(raw, encoding: 'auto')
133
+ end
134
+
135
+ def halfwidth_katakana_ratio(text)
136
+ return 0.0 if text.empty?
137
+
138
+ count = 0
139
+ total = 0
140
+ text.each_char do |char|
141
+ total += 1
142
+ count += 1 if char.match?(/[。-゚]/)
143
+ end
144
+ total.zero? ? 0.0 : count.to_f / total
145
+ end
146
+
147
+ def strip_bom(text)
148
+ text.start_with?("") ? text.sub("", '') : text
149
+ end
150
+ end
151
+ end
152
+ end
@@ -5,6 +5,7 @@ require_relative 'dialog_support'
5
5
  require_relative 'file_operations'
6
6
  require_relative 'dialog_renderer'
7
7
  require_relative 'logger'
8
+ require_relative 'clipboard'
8
9
 
9
10
  module Rufio
10
11
  # ファイル操作専用コントローラ
@@ -30,6 +31,16 @@ module Rufio
30
31
  @terminal_ui = terminal_ui
31
32
  end
32
33
 
34
+ # 選択は「選択したディレクトリ」と対で保持されているため、そのディレクトリを基準に解決する
35
+ def selected_paths
36
+ return [] if @selection_manager.nil? || @selection_manager.empty?
37
+
38
+ source = @selection_manager.source_directory || @directory_listing&.current_path
39
+ return [] if source.nil?
40
+
41
+ @selection_manager.selected_items.map { |name| File.join(source, name) }
42
+ end
43
+
33
44
  def set_directory_listing(directory_listing)
34
45
  @directory_listing = directory_listing
35
46
  end
@@ -38,6 +49,7 @@ module Rufio
38
49
  # ファイル作成
39
50
  # ============================
40
51
 
52
+
41
53
  def create_file
42
54
  prompt_and_select_entry("Create File", "Enter file name:", "\e[32m", "\e[1;32m") do |path, name|
43
55
  @file_operations.create_file(path, name)
@@ -178,6 +190,26 @@ module Rufio
178
190
  end
179
191
  end
180
192
 
193
+ # ============================
194
+ # クリップボード
195
+ # ============================
196
+
197
+ # y: 選択中のファイルがあればその全パス、なければカーソル位置のパスをコピーする
198
+ # @param entry [Hash, nil] カーソル位置のエントリ
199
+ def copy_paths_to_clipboard(entry)
200
+ paths = selected_paths
201
+ paths = [entry[:path]] if paths.empty? && entry
202
+ paths = paths.compact.map { |path| File.expand_path(path) }
203
+ if paths.empty?
204
+ notify_clipboard('nothing to copy')
205
+ return false
206
+ end
207
+
208
+ method = Clipboard.copy(paths.join("\n"))
209
+ notify_clipboard(method ? "#{copied_label(paths)} copied (#{method})" : 'clipboard unavailable')
210
+ !method.nil? && method != false
211
+ end
212
+
181
213
  # ============================
182
214
  # 終了確認
183
215
  # ============================
@@ -203,6 +235,15 @@ module Rufio
203
235
 
204
236
  private
205
237
 
238
+ def copied_label(paths)
239
+ paths.length == 1 ? File.basename(paths.first) : "#{paths.length} paths"
240
+ end
241
+
242
+ def notify_clipboard(message)
243
+ status = @terminal_ui&.ui_renderer&.background_status
244
+ status ? status.notify(message) : false
245
+ end
246
+
206
247
  def prompt_and_select_entry(title, prompt, border_color, title_color)
207
248
  current_path = @directory_listing&.current_path || Dir.pwd
208
249
 
@@ -1,9 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative 'preview_registry'
4
+ require_relative 'table_layout'
5
+ require_relative 'table_source'
6
+
3
7
  module Rufio
4
8
  class FilePreview
5
9
  BINARY_THRESHOLD = 0.3 # treat as binary if 30% or more binary characters
6
10
  DEFAULT_MAX_LINES = 50
11
+ # プレビューモード(P)はスクロールとファイル内検索(/)で先の行まで見るため、
12
+ # 行数の上限を広げる。読み込む量そのものは MAX_PREVIEW_BYTES が決める
13
+ PREVIEW_MODE_MAX_LINES = 20_000
7
14
  MAX_LINE_LENGTH = 500
8
15
  MAX_PREVIEW_BYTES = 64 * 1024
9
16
 
@@ -32,25 +39,13 @@ module Rufio
32
39
  # PDF bodies are not displayed; never scan their binary streams as text.
33
40
  return binary_response(file_path) if File.extname(file_path).casecmp?('.pdf')
34
41
 
35
- return archive_response(file_path, max_lines) if zip_archive?(file_path)
36
-
37
- # binary file detection
38
- sample = File.binread(file_path, [file_size, BINARY_SAMPLE_SIZE].min)
39
- return binary_response(file_path) if binary_file?(sample)
40
-
41
- # process as text file
42
- lines = read_text_file(file_path, max_lines)
43
- file_type = determine_file_type(file_path)
44
-
45
- {
46
- type: file_type[:type],
47
- language: file_type[:language],
48
- lines: lines[:content],
49
- truncated: lines[:truncated],
50
- size: file_size,
51
- modified: File.mtime(file_path),
52
- encoding: lines[:encoding]
53
- }
42
+ # 表として読める形式(CSV / TSV / Excel / SQLite)はグリッド表示に回す。
43
+ # UTF-16 の CSV は NUL バイトが多くバイナリ判定に引っかかるため、判定より前に置く。
44
+ table, table_error = table_response(file_path, max_lines)
45
+ return table if table
46
+
47
+ # 表として読めなかった場合は従来の流れに戻す(.xlsx なら ZIP のエントリ一覧になる)
48
+ with_table_error(fallback_response(file_path, file_size, max_lines), table_error)
54
49
  rescue => e
55
50
  error_response("#{ConfigLoader.message('file.read_error')}: #{e.message}")
56
51
  end
@@ -58,6 +53,84 @@ module Rufio
58
53
 
59
54
  private
60
55
 
56
+ # 表として読めなかったときの従来の流れ(ZIP → バイナリ → テキスト)
57
+ def fallback_response(file_path, file_size, max_lines)
58
+ return archive_response(file_path, max_lines) if zip_archive?(file_path)
59
+
60
+ sample = File.binread(file_path, [file_size, BINARY_SAMPLE_SIZE].min)
61
+ return binary_response(file_path) if binary_file?(sample)
62
+
63
+ text_response(file_path, max_lines)
64
+ end
65
+
66
+ # 表として読めなかった理由は、テキスト表示になったときだけ先頭行に出す
67
+ def with_table_error(response, table_error)
68
+ return response if table_error.nil? || !%w[text code].include?(response[:type])
69
+
70
+ response[:table_error] = table_error
71
+ response[:lines] = ["(#{ConfigLoader.message('file.not_parsed_as_table')}: #{table_error})"] +
72
+ Array(response[:lines])
73
+ response
74
+ end
75
+
76
+ # 通常のテキスト/コードプレビュー
77
+ def text_response(file_path, max_lines)
78
+ lines = read_text_file(file_path, max_lines)
79
+ file_type = determine_file_type(file_path)
80
+
81
+ {
82
+ type: file_type[:type],
83
+ language: file_type[:language],
84
+ lines: lines[:content],
85
+ truncated: lines[:truncated],
86
+ size: File.size(file_path),
87
+ modified: File.mtime(file_path),
88
+ encoding: lines[:encoding]
89
+ }
90
+ end
91
+
92
+ # 行列(グリッド)プレビュー。
93
+ # lines には整形済みのグリッド文字列も入れておき、表描画を知らない利用側
94
+ # (検索画面のプレビューなど)でもそのまま読めるようにする。
95
+ # @return [Array(Hash, nil), Array(nil, String)] 表として読めなければ [nil, 理由]
96
+ def table_response(file_path, max_lines)
97
+ return [nil, nil] unless PreviewRegistry.table?(file_path)
98
+
99
+ settings = ConfigLoader.table_preview
100
+ limits = TableSource::Limits.new(
101
+ max_bytes: settings[:max_bytes],
102
+ max_rows: settings[:max_rows],
103
+ max_columns: settings[:max_columns]
104
+ )
105
+ document = PreviewRegistry.load_table(
106
+ file_path,
107
+ limits: limits,
108
+ options: {
109
+ header: settings[:header],
110
+ delimiter: settings[:delimiter],
111
+ encoding: settings[:encoding]
112
+ }
113
+ )
114
+ raise TableSource::ParseError, 'no table source' unless document
115
+
116
+ [{
117
+ type: 'table',
118
+ language: nil,
119
+ document: document,
120
+ # グリッドの文字列は表示を知らない利用側向けの控えなので、行数は既定の上限で足りる
121
+ lines: TableLayout.plain_lines(
122
+ document, max_lines: [max_lines, DEFAULT_MAX_LINES].min,
123
+ max_column_width: settings[:max_column_width]
124
+ ),
125
+ truncated: document.truncated?,
126
+ size: File.size(file_path),
127
+ modified: File.mtime(file_path),
128
+ encoding: document.encoding
129
+ }, nil]
130
+ rescue TableSource::ParseError => e
131
+ [nil, e.message]
132
+ end
133
+
61
134
  def zip_archive?(file_path)
62
135
  File.extname(file_path).casecmp?('.zip') || ZipArchive.zip_signature?(file_path)
63
136
  end