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
@@ -0,0 +1,170 @@
1
+ //! 画像の縮小。プレビューはペインに収める用途しかないので、拡大は行わない。
2
+ //!
3
+ //! 面積平均(box filter)で縮小する。チャンネル数(3 = RGB / 4 = RGBA)はそのまま保つ。
4
+ const std = @import("std");
5
+
6
+ /// 縮小後の寸法を決める。元より大きくはしない(拡大は端末側の仕事)
7
+ pub fn fit(src_w: u32, src_h: u32, max_w: u32, max_h: u32) [2]u32 {
8
+ if (src_w == 0 or src_h == 0) return .{ 0, 0 };
9
+ if (max_w == 0 or max_h == 0) return .{ src_w, src_h };
10
+ if (src_w <= max_w and src_h <= max_h) return .{ src_w, src_h };
11
+
12
+ // 幅・高さのどちらも収まる倍率を選ぶ(アスペクト比を保つ)
13
+ const scale_w = @as(f64, @floatFromInt(max_w)) / @as(f64, @floatFromInt(src_w));
14
+ const scale_h = @as(f64, @floatFromInt(max_h)) / @as(f64, @floatFromInt(src_h));
15
+ const scale = @min(scale_w, scale_h);
16
+ const w: u32 = @max(1, @as(u32, @intFromFloat(@round(@as(f64, @floatFromInt(src_w)) * scale))));
17
+ const h: u32 = @max(1, @as(u32, @intFromFloat(@round(@as(f64, @floatFromInt(src_h)) * scale))));
18
+ return .{ @min(w, max_w), @min(h, max_h) };
19
+ }
20
+
21
+ pub const CancelError = error{Cancelled};
22
+
23
+ /// src(src_w x src_h x channels)を dst(dst_w x dst_h x channels)へ面積平均で縮小する。
24
+ /// dst は呼び出し側が確保する。dst が src より大きい場合は最近傍で埋める(拡大はしない前提)。
25
+ pub fn resize(
26
+ src: []const u8,
27
+ src_w: u32,
28
+ src_h: u32,
29
+ dst: []u8,
30
+ dst_w: u32,
31
+ dst_h: u32,
32
+ channels: u8,
33
+ ) void {
34
+ resizeCancelable(src, src_w, src_h, dst, dst_w, dst_h, channels, null) catch unreachable;
35
+ }
36
+
37
+ /// キャンセルフラグを監視しながら縮小する。中断されたら error.Cancelled を返す。
38
+ pub fn resizeCancelable(
39
+ src: []const u8,
40
+ src_w: u32,
41
+ src_h: u32,
42
+ dst: []u8,
43
+ dst_w: u32,
44
+ dst_h: u32,
45
+ channels: u8,
46
+ cancelled: ?*const std.atomic.Value(bool),
47
+ ) CancelError!void {
48
+ std.debug.assert(src.len >= @as(usize, src_w) * src_h * channels);
49
+ std.debug.assert(dst.len >= @as(usize, dst_w) * dst_h * channels);
50
+ if (dst_w == 0 or dst_h == 0 or src_w == 0 or src_h == 0) return;
51
+
52
+ if (dst_w == src_w and dst_h == src_h) {
53
+ @memcpy(dst[0 .. @as(usize, src_w) * src_h * channels], src[0 .. @as(usize, src_w) * src_h * channels]);
54
+ return;
55
+ }
56
+
57
+ if (channels == 3) {
58
+ try resizeImpl(3, src, src_w, src_h, dst, dst_w, dst_h, cancelled);
59
+ } else if (channels == 4) {
60
+ try resizeImpl(4, src, src_w, src_h, dst, dst_w, dst_h, cancelled);
61
+ } else {
62
+ try resizeGeneric(src, src_w, src_h, dst, dst_w, dst_h, channels, cancelled);
63
+ }
64
+ }
65
+
66
+ fn resizeImpl(
67
+ comptime ch: usize,
68
+ src: []const u8,
69
+ src_w: u32,
70
+ src_h: u32,
71
+ dst: []u8,
72
+ dst_w: u32,
73
+ dst_h: u32,
74
+ cancelled: ?*const std.atomic.Value(bool),
75
+ ) CancelError!void {
76
+ // 整数演算で各出力ピクセルの入力範囲を求める(内側ループから f64 を排除)
77
+ const src_stride = @as(usize, src_w) * ch;
78
+ const dst_stride = @as(usize, dst_w) * ch;
79
+
80
+ var out_y: u32 = 0;
81
+ while (out_y < dst_h) : (out_y += 1) {
82
+ if (cancelled) |flag| {
83
+ if (flag.load(.acquire)) return error.Cancelled;
84
+ }
85
+ const y0: u32 = @intCast((@as(u64, out_y) * src_h) / dst_h);
86
+ const y1_raw: u32 = @intCast((@as(u64, out_y + 1) * src_h + dst_h - 1) / dst_h);
87
+ const y1: u32 = @min(src_h, @max(y0 + 1, y1_raw));
88
+ const y_span: u64 = y1 - y0;
89
+
90
+ const dst_row = dst[@as(usize, out_y) * dst_stride ..];
91
+ var out_x: u32 = 0;
92
+ while (out_x < dst_w) : (out_x += 1) {
93
+ const x0: u32 = @intCast((@as(u64, out_x) * src_w) / dst_w);
94
+ const x1_raw: u32 = @intCast((@as(u64, out_x + 1) * src_w + dst_w - 1) / dst_w);
95
+ const x1: u32 = @min(src_w, @max(x0 + 1, x1_raw));
96
+ // 大きな画像を極小サイズへ縮小しても合計値が溢れないよう u64 を使う
97
+ const count: u64 = y_span * @as(u64, x1 - x0);
98
+ const half: u64 = count >> 1;
99
+
100
+ var s0: u64 = 0;
101
+ var s1: u64 = 0;
102
+ var s2: u64 = 0;
103
+ var s3: u64 = 0;
104
+
105
+ var y = y0;
106
+ while (y < y1) : (y += 1) {
107
+ var offset = @as(usize, y) * src_stride + @as(usize, x0) * ch;
108
+ var x = x0;
109
+ while (x < x1) : (x += 1) {
110
+ s0 += src[offset];
111
+ s1 += src[offset + 1];
112
+ s2 += src[offset + 2];
113
+ if (ch == 4) s3 += src[offset + 3];
114
+ offset += ch;
115
+ }
116
+ }
117
+
118
+ const out_offset = @as(usize, out_x) * ch;
119
+ dst_row[out_offset] = @intCast((s0 + half) / count);
120
+ dst_row[out_offset + 1] = @intCast((s1 + half) / count);
121
+ dst_row[out_offset + 2] = @intCast((s2 + half) / count);
122
+ if (ch == 4) dst_row[out_offset + 3] = @intCast((s3 + half) / count);
123
+ }
124
+ }
125
+ }
126
+
127
+ fn resizeGeneric(
128
+ src: []const u8,
129
+ src_w: u32,
130
+ src_h: u32,
131
+ dst: []u8,
132
+ dst_w: u32,
133
+ dst_h: u32,
134
+ channels: u8,
135
+ cancelled: ?*const std.atomic.Value(bool),
136
+ ) CancelError!void {
137
+ std.debug.assert(channels <= 4);
138
+ var out_y: u32 = 0;
139
+ while (out_y < dst_h) : (out_y += 1) {
140
+ if (cancelled) |flag| {
141
+ if (flag.load(.acquire)) return error.Cancelled;
142
+ }
143
+ const y0: u32 = @intCast((@as(u64, out_y) * src_h) / dst_h);
144
+ const y1: u32 = @min(src_h, @max(y0 + 1, @as(u32, @intCast((@as(u64, out_y + 1) * src_h + dst_h - 1) / dst_h))));
145
+
146
+ var out_x: u32 = 0;
147
+ while (out_x < dst_w) : (out_x += 1) {
148
+ const x0: u32 = @intCast((@as(u64, out_x) * src_w) / dst_w);
149
+ const x1: u32 = @min(src_w, @max(x0 + 1, @as(u32, @intCast((@as(u64, out_x + 1) * src_w + dst_w - 1) / dst_w))));
150
+
151
+ var sums: [4]u64 = .{ 0, 0, 0, 0 };
152
+ const count: u64 = @as(u64, y1 - y0) * @as(u64, x1 - x0);
153
+ var y = y0;
154
+ while (y < y1) : (y += 1) {
155
+ var x = x0;
156
+ while (x < x1) : (x += 1) {
157
+ const offset = (@as(usize, y) * src_w + x) * channels;
158
+ var c: u8 = 0;
159
+ while (c < channels) : (c += 1) sums[c] += src[offset + c];
160
+ }
161
+ }
162
+
163
+ const out_offset = (@as(usize, out_y) * dst_w + out_x) * channels;
164
+ var c: u8 = 0;
165
+ while (c < channels) : (c += 1) {
166
+ dst[out_offset + c] = @intCast((sums[c] + count / 2) / count);
167
+ }
168
+ }
169
+ }
170
+ }
@@ -0,0 +1,401 @@
1
+ //! 画像デコード・縮小・符号化の単体テスト。
2
+ //! テスト画像は testdata/ に置いた小さな実ファイル(PNG は Ruby の zlib で、
3
+ //! JPEG と BMP はそこから sips で変換して作成)。
4
+ const std = @import("std");
5
+ const testing = std.testing;
6
+ const image = @import("image.zig");
7
+ const png = @import("image_png.zig");
8
+ const jpeg = @import("image_jpeg.zig");
9
+ const bmp = @import("image_bmp.zig");
10
+ const resize = @import("image_resize.zig");
11
+
12
+ const GRADIENT_PNG = @embedFile("testdata/gradient.png");
13
+ const ALPHA_PNG = @embedFile("testdata/alpha.png");
14
+ const GRADIENT_JPG = @embedFile("testdata/gradient.jpg");
15
+ const GRADIENT_BMP = @embedFile("testdata/gradient.bmp");
16
+
17
+ // gradient.png は 16x12 で、画素は (x*16, y*20, 128)
18
+ fn expectedGradient(x: u32, y: u32) [3]u8 {
19
+ return .{ @intCast(x * 16), @intCast(y * 20), 128 };
20
+ }
21
+
22
+ test "形式はシグネチャで判定する" {
23
+ try testing.expectEqual(image.Kind.png, image.detect(GRADIENT_PNG));
24
+ try testing.expectEqual(image.Kind.jpeg, image.detect(GRADIENT_JPG));
25
+ try testing.expectEqual(image.Kind.bmp, image.detect(GRADIENT_BMP));
26
+ try testing.expectEqual(image.Kind.unsupported, image.detect("not an image"));
27
+ try testing.expectEqual(image.Kind.unsupported, image.detect(""));
28
+ try testing.expectEqual(image.Kind.gif, image.detect("GIF89a....."));
29
+ }
30
+
31
+ test "PNG の見出しから寸法を読む" {
32
+ const size = try png.info(GRADIENT_PNG);
33
+ try testing.expectEqual(@as(u32, 16), size[0]);
34
+ try testing.expectEqual(@as(u32, 12), size[1]);
35
+ }
36
+
37
+ test "PNG を RGB に展開する" {
38
+ var decoded = try png.decode(testing.allocator, GRADIENT_PNG, image.MAX_PIXELS);
39
+ defer decoded.deinit(testing.allocator);
40
+
41
+ try testing.expectEqual(@as(u32, 16), decoded.width);
42
+ try testing.expectEqual(@as(u32, 12), decoded.height);
43
+ try testing.expectEqual(@as(u8, 3), decoded.channels);
44
+
45
+ var y: u32 = 0;
46
+ while (y < decoded.height) : (y += 1) {
47
+ var x: u32 = 0;
48
+ while (x < decoded.width) : (x += 1) {
49
+ const expected = expectedGradient(x, y);
50
+ const offset = (y * decoded.width + x) * 3;
51
+ try testing.expectEqualSlices(u8, &expected, decoded.pixels[offset .. offset + 3]);
52
+ }
53
+ }
54
+ }
55
+
56
+ test "アルファ付き PNG は RGBA になる" {
57
+ var decoded = try png.decode(testing.allocator, ALPHA_PNG, image.MAX_PIXELS);
58
+ defer decoded.deinit(testing.allocator);
59
+
60
+ try testing.expectEqual(@as(u8, 4), decoded.channels);
61
+ try testing.expectEqual(@as(u32, 8), decoded.width);
62
+ // alpha.png は (255, 0, 0, x*32)
63
+ try testing.expectEqual(@as(u8, 255), decoded.pixels[0]);
64
+ try testing.expectEqual(@as(u8, 0), decoded.pixels[3]);
65
+ try testing.expectEqual(@as(u8, 32), decoded.pixels[7]);
66
+ }
67
+
68
+ test "PNG を書いて読み戻すと同じ画素になる" {
69
+ var decoded = try png.decode(testing.allocator, GRADIENT_PNG, image.MAX_PIXELS);
70
+ defer decoded.deinit(testing.allocator);
71
+
72
+ const encoded = try png.encode(testing.allocator, decoded.pixels, decoded.width, decoded.height, 3);
73
+ defer testing.allocator.free(encoded);
74
+ try testing.expect(std.mem.eql(u8, encoded[0..8], png.SIGNATURE));
75
+
76
+ var again = try png.decode(testing.allocator, encoded, image.MAX_PIXELS);
77
+ defer again.deinit(testing.allocator);
78
+ try testing.expectEqual(decoded.width, again.width);
79
+ try testing.expectEqual(decoded.height, again.height);
80
+ try testing.expectEqualSlices(u8, decoded.pixels, again.pixels);
81
+ }
82
+
83
+ test "BMP を展開すると PNG と同じ画素になる" {
84
+ var decoded = try bmp.decode(testing.allocator, GRADIENT_BMP, image.MAX_PIXELS);
85
+ defer decoded.deinit(testing.allocator);
86
+
87
+ try testing.expectEqual(@as(u32, 16), decoded.width);
88
+ try testing.expectEqual(@as(u32, 12), decoded.height);
89
+ try testing.expectEqual(@as(u8, 3), decoded.channels);
90
+
91
+ var y: u32 = 0;
92
+ while (y < decoded.height) : (y += 1) {
93
+ var x: u32 = 0;
94
+ while (x < decoded.width) : (x += 1) {
95
+ const expected = expectedGradient(x, y);
96
+ const offset = (y * decoded.width + x) * 3;
97
+ try testing.expectEqualSlices(u8, &expected, decoded.pixels[offset .. offset + 3]);
98
+ }
99
+ }
100
+ }
101
+
102
+ test "baseline JPEG を展開すると元の絵に近い画素になる" {
103
+ const size = try jpeg.info(GRADIENT_JPG);
104
+ try testing.expectEqual(@as(u32, 16), size[0]);
105
+ try testing.expectEqual(@as(u32, 12), size[1]);
106
+
107
+ var decoded = try jpeg.decode(testing.allocator, GRADIENT_JPG, image.MAX_PIXELS);
108
+ defer decoded.deinit(testing.allocator);
109
+
110
+ try testing.expectEqual(@as(u32, 16), decoded.width);
111
+ try testing.expectEqual(@as(u32, 12), decoded.height);
112
+ try testing.expectEqual(@as(u8, 3), decoded.channels);
113
+
114
+ // 非可逆なので、各画素が期待値から大きく外れていないことだけを見る
115
+ var max_error: i32 = 0;
116
+ var y: u32 = 0;
117
+ while (y < decoded.height) : (y += 1) {
118
+ var x: u32 = 0;
119
+ while (x < decoded.width) : (x += 1) {
120
+ const expected = expectedGradient(x, y);
121
+ const offset = (y * decoded.width + x) * 3;
122
+ var c: usize = 0;
123
+ while (c < 3) : (c += 1) {
124
+ const diff = @as(i32, decoded.pixels[offset + c]) - @as(i32, expected[c]);
125
+ max_error = @max(max_error, @as(i32, @intCast(@abs(diff))));
126
+ }
127
+ }
128
+ }
129
+ try testing.expect(max_error <= 32);
130
+ }
131
+
132
+ test "プログレッシブ JPEG は非対応として断る" {
133
+ // SOF2(プログレッシブ)の見出しだけを組み立てる
134
+ var data: [24]u8 = @splat(0);
135
+ data[0] = 0xff;
136
+ data[1] = 0xd8;
137
+ data[2] = 0xff;
138
+ data[3] = 0xc2; // SOF2
139
+ data[4] = 0x00;
140
+ data[5] = 0x11; // length = 17
141
+ data[6] = 8; // precision
142
+ data[7] = 0;
143
+ data[8] = 16; // height
144
+ data[9] = 0;
145
+ data[10] = 16; // width
146
+ data[11] = 3; // components
147
+ try testing.expectError(jpeg.Error.UnsupportedJpeg, jpeg.decode(testing.allocator, &data, image.MAX_PIXELS));
148
+ }
149
+
150
+ test "壊れた入力でも落ちずにエラーを返す" {
151
+ try testing.expectError(png.Error.InvalidPng, png.decode(testing.allocator, "not a png at all", image.MAX_PIXELS));
152
+ try testing.expectError(bmp.Error.InvalidBmp, bmp.decode(testing.allocator, "BM", image.MAX_PIXELS));
153
+ try testing.expectError(jpeg.Error.InvalidJpeg, jpeg.decode(testing.allocator, "\xff\xd8\xff", image.MAX_PIXELS));
154
+
155
+ // 途中で切れた PNG
156
+ try testing.expectError(png.Error.InvalidPng, png.decode(testing.allocator, GRADIENT_PNG[0..40], image.MAX_PIXELS));
157
+ }
158
+
159
+ test "画素数の上限を超える画像は断る" {
160
+ // IHDR だけを書き換えて巨大な寸法を名乗る PNG を作る
161
+ var data = try testing.allocator.dupe(u8, GRADIENT_PNG);
162
+ defer testing.allocator.free(data);
163
+ std.mem.writeInt(u32, data[16..20], 40000, .big);
164
+ std.mem.writeInt(u32, data[20..24], 40000, .big); // 16 億画素
165
+
166
+ try testing.expectError(png.Error.TooLarge, png.decode(testing.allocator, data, image.MAX_PIXELS));
167
+ }
168
+
169
+ test "縮小後の寸法は比を保ち、拡大はしない" {
170
+ try testing.expectEqual([2]u32{ 100, 50 }, resize.fit(200, 100, 100, 100));
171
+ try testing.expectEqual([2]u32{ 50, 100 }, resize.fit(100, 200, 100, 100));
172
+ try testing.expectEqual([2]u32{ 40, 30 }, resize.fit(40, 30, 100, 100)); // 小さい画像はそのまま
173
+ try testing.expectEqual([2]u32{ 1, 1 }, resize.fit(1000, 1, 1, 1));
174
+ try testing.expectEqual([2]u32{ 0, 0 }, resize.fit(0, 0, 10, 10));
175
+ }
176
+
177
+ test "縮小は面積平均で行う" {
178
+ // 2x2 の 1 色ずつを 1x1 にすると平均になる
179
+ const src = [_]u8{
180
+ 0, 0, 0, 255, 255, 255,
181
+ 255, 255, 255, 0, 0, 0,
182
+ };
183
+ var dst: [3]u8 = @splat(0);
184
+ resize.resize(&src, 2, 2, &dst, 1, 1, 3);
185
+ try testing.expectEqual(@as(u8, 128), dst[0]);
186
+ try testing.expectEqual(@as(u8, 128), dst[1]);
187
+ try testing.expectEqual(@as(u8, 128), dst[2]);
188
+ }
189
+
190
+ test "縮小しても端の画素は元の色に近い" {
191
+ var decoded = try png.decode(testing.allocator, GRADIENT_PNG, image.MAX_PIXELS);
192
+ defer decoded.deinit(testing.allocator);
193
+
194
+ const target = resize.fit(decoded.width, decoded.height, 8, 8);
195
+ try testing.expectEqual([2]u32{ 8, 6 }, target);
196
+ const scaled = try testing.allocator.alloc(u8, @as(usize, target[0]) * target[1] * 3);
197
+ defer testing.allocator.free(scaled);
198
+ resize.resize(decoded.pixels, decoded.width, decoded.height, scaled, target[0], target[1], 3);
199
+
200
+ // 左上は元の左上(0, 0, 128)の近く、右下は右下(240, 220, 128)の近く
201
+ try testing.expect(scaled[0] < 40);
202
+ try testing.expectEqual(@as(u8, 128), scaled[2]);
203
+ const last = (@as(usize, target[1] - 1) * target[0] + target[0] - 1) * 3;
204
+ try testing.expect(scaled[last] > 200);
205
+ }
206
+
207
+ test "PNG の高速検査は寸法とチャンネル数を返し、壊れた入力を断る" {
208
+ const rgb = try png.inspect(GRADIENT_PNG, image.MAX_PIXELS);
209
+ try testing.expectEqual(@as(u32, 16), rgb.width);
210
+ try testing.expectEqual(@as(u32, 12), rgb.height);
211
+ try testing.expectEqual(@as(u8, 3), rgb.channels);
212
+
213
+ const rgba = try png.inspect(ALPHA_PNG, image.MAX_PIXELS);
214
+ try testing.expectEqual(@as(u32, 8), rgba.width);
215
+ try testing.expectEqual(@as(u32, 8), rgba.height);
216
+ try testing.expectEqual(@as(u8, 4), rgba.channels);
217
+
218
+ // 途中で切れた PNG(IEND が無い)はエラーになる
219
+ try testing.expectError(png.Error.InvalidPng, png.inspect(GRADIENT_PNG[0..40], image.MAX_PIXELS));
220
+ }
221
+
222
+ test "セキュリティ: 不正な JPEG ハフマン表(符号数オーバーフロー)を安全に拒否する" {
223
+ // 長さ 1bit の符号を 5 個宣言する悪意ある DHT(本来は最大 2 個)
224
+ var data = [_]u8{
225
+ 0xff, 0xd8, // SOI
226
+ 0xff, 0xc4, 0x00, 0x18, // DHT, len=24 (1 + 16 + 5 + 2)
227
+ 0x00, // class=0 (DC), index=0
228
+ 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // counts: len1 = 5 (不正)
229
+ 0, 1, 2, 3, 4, // values
230
+ 0xff, 0xd9, // EOI
231
+ };
232
+ try testing.expectError(jpeg.Error.InvalidJpeg, jpeg.decode(testing.allocator, &data, image.MAX_PIXELS));
233
+ }
234
+
235
+ test "セキュリティ: JPEG の SOF 重複・SOF 前 SOS・規格外 MCU ブロック数を拒否する" {
236
+ // SOF 前に SOS が来る不正 JPEG
237
+ const sos_before_sof = [_]u8{
238
+ 0xff, 0xd8,
239
+ 0xff, 0xda, 0x00, 0x03, 0x00,
240
+ 0xff, 0xd9,
241
+ };
242
+ try testing.expectError(jpeg.Error.InvalidJpeg, jpeg.decode(testing.allocator, &sos_before_sof, image.MAX_PIXELS));
243
+
244
+ // 3 成分すべて h=4, v=4(Σ h*v = 48 > 規格上限 10)の MCU 爆弾
245
+ const huge_mcu = [_]u8{
246
+ 0xff, 0xd8,
247
+ 0xff, 0xc0, 0x00, 0x11, 8, 0, 16, 0, 16, 3,
248
+ 1, 0x44, 0,
249
+ 2, 0x44, 0,
250
+ 3, 0x44, 0,
251
+ 0xff, 0xd9,
252
+ };
253
+ try testing.expectError(jpeg.Error.InvalidJpeg, jpeg.decode(testing.allocator, &huge_mcu, image.MAX_PIXELS));
254
+ }
255
+
256
+ test "セキュリティ: PNG の decompression bomb(展開サイズが寸法を超過)を拒否する" {
257
+ // 1x1 RGB PNG(期待展開サイズは 4 バイト)だが、IDAT に大量の 0 を圧縮して仕込む
258
+ const flate = std.compress.flate;
259
+ var zbuf = try std.Io.Writer.Allocating.initCapacity(testing.allocator, 4096);
260
+ defer zbuf.deinit();
261
+ const window = try testing.allocator.alloc(u8, flate.max_window_len);
262
+ defer testing.allocator.free(window);
263
+ var comp = try flate.Compress.init(&zbuf.writer, window, .zlib, .fastest);
264
+ var zeros: [4096]u8 = @splat(0);
265
+ // 64KB 分のゼロを圧縮(1x1 の期待サイズ 4 バイトを遥かに超える)
266
+ var i: usize = 0;
267
+ while (i < 16) : (i += 1) {
268
+ try comp.writer.writeAll(&zeros);
269
+ }
270
+ try comp.finish();
271
+ try zbuf.writer.flush();
272
+ const idat_body = zbuf.written();
273
+
274
+ var bomb: std.ArrayList(u8) = .empty;
275
+ defer bomb.deinit(testing.allocator);
276
+ try bomb.appendSlice(testing.allocator, png.SIGNATURE);
277
+ // IHDR: 1x1, 8bit RGB
278
+ var ihdr = [_]u8{ 0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0 };
279
+ var len_buf: [4]u8 = undefined;
280
+ std.mem.writeInt(u32, &len_buf, 13, .big);
281
+ try bomb.appendSlice(testing.allocator, &len_buf);
282
+ try bomb.appendSlice(testing.allocator, "IHDR");
283
+ try bomb.appendSlice(testing.allocator, &ihdr);
284
+ try bomb.appendSlice(testing.allocator, &[_]u8{ 0, 0, 0, 0 });
285
+ // IDAT
286
+ std.mem.writeInt(u32, &len_buf, @intCast(idat_body.len), .big);
287
+ try bomb.appendSlice(testing.allocator, &len_buf);
288
+ try bomb.appendSlice(testing.allocator, "IDAT");
289
+ try bomb.appendSlice(testing.allocator, idat_body);
290
+ try bomb.appendSlice(testing.allocator, &[_]u8{ 0, 0, 0, 0 });
291
+ // IEND
292
+ try bomb.appendSlice(testing.allocator, &[_]u8{ 0, 0, 0, 0, 'I', 'E', 'N', 'D', 0, 0, 0, 0 });
293
+
294
+ try testing.expectError(png.Error.InvalidPng, png.decode(testing.allocator, bomb.items, image.MAX_PIXELS));
295
+ }
296
+
297
+ test "セキュリティ: BMP の header_size オーバーフローを安全に拒否する" {
298
+ var bad_bmp: [64]u8 = @splat(0);
299
+ bad_bmp[0] = 'B';
300
+ bad_bmp[1] = 'M';
301
+ std.mem.writeInt(u32, bad_bmp[10..14], 54, .little); // pixel_offset
302
+ std.mem.writeInt(u32, bad_bmp[14..18], 0xffff_fff5, .little); // 14 + header_size が u32 オーバーフロー
303
+ std.mem.writeInt(i32, bad_bmp[18..22], 1, .little);
304
+ std.mem.writeInt(i32, bad_bmp[22..26], 1, .little);
305
+ std.mem.writeInt(u16, bad_bmp[28..30], 8, .little);
306
+ try testing.expectError(bmp.Error.InvalidBmp, bmp.decode(testing.allocator, &bad_bmp, image.MAX_PIXELS));
307
+ }
308
+
309
+ test "セキュリティ: パスに NUL バイトを含む要求は拒否する" {
310
+ const path = "/tmp/foo\x00bar.png";
311
+ try testing.expectEqual(@as(u64, 0), image.core_image_create(path.ptr, path.len, 100, 100, 0));
312
+ }
313
+
314
+ test "セキュリティ: 縮小時の画素合計が u32 上限を超えてもオーバーフローしない" {
315
+ // 4100x4100 = 16,810,000 画素、4200x4200 = 17,640,000 画素(x 255 = 4,498,200,000 > u32 最大値)
316
+ const w: u32 = 4200;
317
+ const h: u32 = 4200;
318
+ const src = try testing.allocator.alloc(u8, @as(usize, w) * h * 3);
319
+ defer testing.allocator.free(src);
320
+ @memset(src, 255);
321
+
322
+ var dst: [3]u8 = @splat(0);
323
+ resize.resize(src, w, h, &dst, 1, 1, 3);
324
+ try testing.expectEqualSlices(u8, &[_]u8{ 255, 255, 255 }, &dst);
325
+ }
326
+
327
+ test "セキュリティ: PNG 直送検証は decompression bomb・末尾ゴミ・不正パレット深度を拒否する" {
328
+ // 正常な PNG は inspectVerified を通過する
329
+ const ok = try png.inspectVerified(testing.allocator, GRADIENT_PNG, image.MAX_PIXELS, null);
330
+ try testing.expectEqual(@as(u32, 16), ok.width);
331
+
332
+ // IEND の後ろに余剰データが付いた PNG は直送検証で拒否する
333
+ var trailing = try testing.allocator.alloc(u8, GRADIENT_PNG.len + 16);
334
+ defer testing.allocator.free(trailing);
335
+ @memcpy(trailing[0..GRADIENT_PNG.len], GRADIENT_PNG);
336
+ @memset(trailing[GRADIENT_PNG.len..], 'X');
337
+ try testing.expectError(png.Error.InvalidPng, png.inspectVerified(testing.allocator, trailing, image.MAX_PIXELS, null));
338
+
339
+ // palette(3) + bit_depth(16) は PNG 規格違反のため拒否する
340
+ var bad_palette = try testing.allocator.dupe(u8, GRADIENT_PNG);
341
+ defer testing.allocator.free(bad_palette);
342
+ bad_palette[24] = 16; // bit_depth
343
+ bad_palette[25] = 3; // color_type = palette
344
+ try testing.expectError(png.Error.InvalidPng, png.inspect(bad_palette, image.MAX_PIXELS));
345
+ try testing.expectError(png.Error.InvalidPng, png.decode(testing.allocator, bad_palette, image.MAX_PIXELS));
346
+
347
+ // 1x1 RGB なのに IDAT が 64KB 展開する bomb PNG は inspectVerified でも拒否する
348
+ const flate = std.compress.flate;
349
+ var zbuf = try std.Io.Writer.Allocating.initCapacity(testing.allocator, 4096);
350
+ defer zbuf.deinit();
351
+ const window = try testing.allocator.alloc(u8, flate.max_window_len);
352
+ defer testing.allocator.free(window);
353
+ var comp = try flate.Compress.init(&zbuf.writer, window, .zlib, .fastest);
354
+ var zeros: [4096]u8 = @splat(0);
355
+ var i: usize = 0;
356
+ while (i < 16) : (i += 1) try comp.writer.writeAll(&zeros);
357
+ try comp.finish();
358
+ try zbuf.writer.flush();
359
+ const idat_body = zbuf.written();
360
+
361
+ var bomb: std.ArrayList(u8) = .empty;
362
+ defer bomb.deinit(testing.allocator);
363
+ try bomb.appendSlice(testing.allocator, png.SIGNATURE);
364
+ var ihdr = [_]u8{ 0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0 };
365
+ var len_buf: [4]u8 = undefined;
366
+ std.mem.writeInt(u32, &len_buf, 13, .big);
367
+ try bomb.appendSlice(testing.allocator, &len_buf);
368
+ try bomb.appendSlice(testing.allocator, "IHDR");
369
+ try bomb.appendSlice(testing.allocator, &ihdr);
370
+ try bomb.appendSlice(testing.allocator, &[_]u8{ 0, 0, 0, 0 });
371
+ std.mem.writeInt(u32, &len_buf, @intCast(idat_body.len), .big);
372
+ try bomb.appendSlice(testing.allocator, &len_buf);
373
+ try bomb.appendSlice(testing.allocator, "IDAT");
374
+ try bomb.appendSlice(testing.allocator, idat_body);
375
+ try bomb.appendSlice(testing.allocator, &[_]u8{ 0, 0, 0, 0 });
376
+ try bomb.appendSlice(testing.allocator, &[_]u8{ 0, 0, 0, 0, 'I', 'E', 'N', 'D', 0, 0, 0, 0 });
377
+
378
+ try testing.expectError(png.Error.InvalidPng, png.inspectVerified(testing.allocator, bomb.items, image.MAX_PIXELS, null));
379
+ }
380
+
381
+ test "セキュリティ: 切れた小ファイルで巨大寸法を名乗る JPEG の空回し DoS を打ち切る" {
382
+ // 2000x2000 1成分、DC/AC ともに符号 0 (1bit) = 0x00 を定義し、SOS 直後に EOF にする
383
+ const crafted = [_]u8{
384
+ 0xff, 0xd8, // SOI
385
+ 0xff, 0xc0, 0x00, 0x0b, 8, 0x07, 0xd0, 0x07, 0xd0, 1, 1, 0x11, 0, // SOF0: 2000x2000, 1comp
386
+ 0xff, 0xc4, 0x00, 0x14, 0x00, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, // DHT DC0
387
+ 0xff, 0xc4, 0x00, 0x14, 0x10, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, // DHT AC0
388
+ 0xff, 0xda, 0x00, 0x08, 1, 1, 0x00, 0, 63, 0, // SOS (直後に EOF)
389
+ };
390
+ try testing.expectError(jpeg.Error.InvalidJpeg, jpeg.decode(testing.allocator, &crafted, image.MAX_PIXELS));
391
+ }
392
+
393
+ test "セキュリティ: デコードと縮小はキャンセルフラグで即中断できる" {
394
+ var flag = std.atomic.Value(bool).init(true);
395
+ try testing.expectError(png.Error.Cancelled, png.decodeCancelable(testing.allocator, GRADIENT_PNG, image.MAX_PIXELS, &flag));
396
+ try testing.expectError(jpeg.Error.Cancelled, jpeg.decodeCancelable(testing.allocator, GRADIENT_JPG, image.MAX_PIXELS, &flag));
397
+
398
+ const src: [4 * 4 * 3]u8 = @splat(0);
399
+ var dst: [2 * 2 * 3]u8 = @splat(0);
400
+ try testing.expectError(error.Cancelled, resize.resizeCancelable(&src, 4, 4, &dst, 2, 2, 3, &flag));
401
+ }
@@ -1,6 +1,7 @@
1
1
  const std = @import("std");
2
2
  comptime {
3
3
  _ = @import("fuzzy.zig");
4
+ _ = @import("image.zig");
4
5
  }
5
6
  const c = std.c;
6
7
  const search = @import("search.zig");
@@ -170,17 +170,21 @@ pub fn countNewlines(bytes: []const u8) usize {
170
170
  const zero: Vec = @splat(0);
171
171
  var total: usize = 0;
172
172
  var i: usize = 0;
173
- while (i + VLEN <= bytes.len) {
174
- var acc: Vec = zero;
175
- var rounds: usize = 0;
176
- while (rounds < 255 and i + VLEN <= bytes.len) : ({
177
- rounds += 1;
178
- i += VLEN;
179
- }) {
180
- const v: Vec = bytes[i..][0..VLEN].*;
181
- acc += @select(u8, v == nl, one, zero);
173
+ if (bytes.len >= VLEN) {
174
+ const limit = bytes.len - VLEN;
175
+ while (i <= limit) {
176
+ var acc: Vec = zero;
177
+ var rounds: usize = 0;
178
+ while (rounds < 255 and i <= limit) : ({
179
+ rounds += 1;
180
+ i += VLEN;
181
+ }) {
182
+ const v: Vec = bytes[i..][0..VLEN].*;
183
+ acc +%= @select(u8, v == nl, one, zero);
184
+ }
185
+ const wide: @Vector(VLEN, u16) = acc;
186
+ total += @reduce(.Add, wide);
182
187
  }
183
- total += @reduce(.Add, @as(@Vector(VLEN, u16), acc));
184
188
  }
185
189
  for (bytes[i..]) |b| total += @intFromBool(b == '\n');
186
190
  return total;
@@ -256,32 +260,47 @@ const Buf = struct {
256
260
  }
257
261
  };
258
262
 
259
- const Job = struct {
263
+ pub const Job = struct {
260
264
  next: ?*Job,
261
265
  root: u32,
262
266
  len: usize,
263
267
 
264
- fn path(self: *Job) [:0]u8 {
268
+ pub fn path(self: *Job) [:0]u8 {
265
269
  const base: [*]u8 = @ptrCast(self);
266
270
  return base[@sizeOf(Job)..][0..self.len :0];
267
271
  }
268
272
 
269
- fn create(root: u32, parent: []const u8, name: []const u8) ?*Job {
270
- const len = if (name.len == 0) parent.len else parent.len + 1 + name.len;
271
- const mem = c.malloc(@sizeOf(Job) + len + 1) orelse return null;
272
- const job: *Job = @ptrCast(@alignCast(mem));
273
+ /// Job 1 個に要るバイト数(構造体+パス+終端 NUL)
274
+ pub fn sizeFor(parent: []const u8, name: []const u8) usize {
275
+ return @sizeOf(Job) + pathLen(parent, name) + 1;
276
+ }
277
+
278
+ fn pathLen(parent: []const u8, name: []const u8) usize {
279
+ return if (name.len == 0) parent.len else parent.len + 1 + name.len;
280
+ }
281
+
282
+ /// 渡したメモリ(sizeFor 以上)に Job を組み立てる。
283
+ /// path() は [:0] スライスを返すので、終端 NUL は生ポインタで先に書く
284
+ pub fn initIn(mem: [*]align(@alignOf(Job)) u8, root: u32, parent: []const u8, name: []const u8) *Job {
285
+ const len = pathLen(parent, name);
286
+ const job: *Job = @ptrCast(mem);
273
287
  job.* = .{ .next = null, .root = root, .len = len };
274
- const p = job.path();
288
+ const p: [*]u8 = mem + @sizeOf(Job);
289
+ p[len] = 0;
275
290
  @memcpy(p[0..parent.len], parent);
276
291
  if (name.len > 0) {
277
292
  p[parent.len] = '/';
278
293
  @memcpy(p[parent.len + 1 ..][0..name.len], name);
279
294
  }
280
- p[len] = 0;
281
295
  return job;
282
296
  }
283
297
 
284
- fn destroy(self: *Job) void {
298
+ pub fn create(root: u32, parent: []const u8, name: []const u8) ?*Job {
299
+ const mem = c.malloc(sizeFor(parent, name)) orelse return null;
300
+ return initIn(@ptrCast(@alignCast(mem)), root, parent, name);
301
+ }
302
+
303
+ pub fn destroy(self: *Job) void {
285
304
  c.free(self);
286
305
  }
287
306
  };