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,561 @@
1
+ //! PNG の読み書き。zlib は Zig 標準ライブラリ(std.compress.flate)を使う。
2
+ //!
3
+ //! 読み: 8bit / 16bit(上位 8bit だけ使う)の グレースケール・RGB・パレット・アルファ付きを
4
+ //! RGB か RGBA の生画素に展開する。インターレース(Adam7)は非対応で、呼び出し側が
5
+ //! テキスト表示にフォールバックする。
6
+ //! 書き: フィルタ 0(None)・高速圧縮(.fastest)で zlib 圧縮する。端末へ渡すだけなので圧縮率より速さを採る。
7
+ const std = @import("std");
8
+ const flate = std.compress.flate;
9
+ const Crc32 = std.hash.Crc32;
10
+
11
+ pub const SIGNATURE = "\x89PNG\r\n\x1a\n";
12
+ /// 1 辺の最大ピクセル数(細工した極端な縦長・横長画像を拒否する)
13
+ const MAX_DIMENSION: u32 = 16384;
14
+ /// 伸長後の生データ(フィルタバイト込み)の上限(decompression bomb 対策)
15
+ const MAX_DECODED_BYTES: usize = 256 * 1024 * 1024;
16
+
17
+ pub const Error = error{
18
+ InvalidPng,
19
+ UnsupportedPng,
20
+ TooLarge,
21
+ OutOfMemory,
22
+ Cancelled,
23
+ };
24
+
25
+ pub const Image = struct {
26
+ width: u32,
27
+ height: u32,
28
+ channels: u8, // 3 = RGB / 4 = RGBA
29
+ pixels: []u8,
30
+
31
+ pub fn deinit(self: *Image, alloc: std.mem.Allocator) void {
32
+ alloc.free(self.pixels);
33
+ self.pixels = &.{};
34
+ }
35
+ };
36
+
37
+ pub const Meta = struct {
38
+ width: u32,
39
+ height: u32,
40
+ channels: u8,
41
+ };
42
+
43
+ const ColorType = enum(u8) {
44
+ gray = 0,
45
+ rgb = 2,
46
+ palette = 3,
47
+ gray_alpha = 4,
48
+ rgba = 6,
49
+ };
50
+
51
+ /// 見出しだけを読んで寸法を返す(画素は展開しない)
52
+ pub fn info(data: []const u8) Error![2]u32 {
53
+ if (data.len < 24) return Error.InvalidPng;
54
+ if (!std.mem.eql(u8, data[0..8], SIGNATURE)) return Error.InvalidPng;
55
+ if (!std.mem.eql(u8, data[12..16], "IHDR")) return Error.InvalidPng;
56
+ const width = std.mem.readInt(u32, data[16..20], .big);
57
+ const height = std.mem.readInt(u32, data[20..24], .big);
58
+ if (width == 0 or height == 0) return Error.InvalidPng;
59
+ return .{ width, height };
60
+ }
61
+
62
+ /// 画素を展開せずにチャンク構造・寸法・チャンネル数を検査する(軽量メタ検証用)
63
+ pub fn inspect(data: []const u8, max_pixels: u64) Error!Meta {
64
+ return inspectInternal(null, data, max_pixels, null, false);
65
+ }
66
+
67
+ /// チャンク構造に加えて IDAT の伸長サイズ(decompression bomb 等)も検証する(縮小不要 PNG の直送判定用)
68
+ pub fn inspectVerified(
69
+ alloc: std.mem.Allocator,
70
+ data: []const u8,
71
+ max_pixels: u64,
72
+ cancelled: ?*const std.atomic.Value(bool),
73
+ ) Error!Meta {
74
+ return inspectInternal(alloc, data, max_pixels, cancelled, true);
75
+ }
76
+
77
+ fn inspectInternal(
78
+ maybe_alloc: ?std.mem.Allocator,
79
+ data: []const u8,
80
+ max_pixels: u64,
81
+ cancelled: ?*const std.atomic.Value(bool),
82
+ verify_idat: bool,
83
+ ) Error!Meta {
84
+ if (data.len < 8 or !std.mem.eql(u8, data[0..8], SIGNATURE)) return Error.InvalidPng;
85
+
86
+ var width: u32 = 0;
87
+ var height: u32 = 0;
88
+ var bit_depth: u8 = 0;
89
+ var color_type: ColorType = .rgb;
90
+ var palette_alpha_len: usize = 0;
91
+ var seen_ihdr = false;
92
+ var seen_plte = false;
93
+ var seen_idat = false;
94
+ var seen_iend = false;
95
+
96
+ var idat: std.ArrayList(u8) = .empty;
97
+ defer if (maybe_alloc) |a| idat.deinit(a);
98
+
99
+ var offset: usize = 8;
100
+ while (offset + 8 <= data.len) {
101
+ const length = std.mem.readInt(u32, data[offset..][0..4], .big);
102
+ const kind = data[offset + 4 ..][0..4];
103
+ const body_start = offset + 8;
104
+ // 32bit 加算オーバーフローを避けて減算で境界検証する
105
+ if (data.len - body_start < 4 or length > data.len - body_start - 4) return Error.InvalidPng;
106
+ const body = data[body_start .. body_start + length];
107
+
108
+ if (std.mem.eql(u8, kind, "IHDR")) {
109
+ if (seen_ihdr or offset != 8 or length != 13) return Error.InvalidPng;
110
+ width = std.mem.readInt(u32, body[0..4], .big);
111
+ height = std.mem.readInt(u32, body[4..8], .big);
112
+ bit_depth = body[8];
113
+ color_type = std.enums.fromInt(ColorType, body[9]) orelse return Error.UnsupportedPng;
114
+ if (body[10] != 0 or body[11] != 0 or body[12] != 0) return Error.UnsupportedPng;
115
+ if (bit_depth != 8 and bit_depth != 16) return Error.UnsupportedPng;
116
+ if (color_type == .palette and bit_depth != 8) return Error.InvalidPng;
117
+ if (width == 0 or height == 0) return Error.InvalidPng;
118
+ if (width > MAX_DIMENSION or height > MAX_DIMENSION) return Error.TooLarge;
119
+ if (@as(u64, width) * height > max_pixels) return Error.TooLarge;
120
+ seen_ihdr = true;
121
+ } else if (std.mem.eql(u8, kind, "PLTE")) {
122
+ if (seen_plte or length == 0 or length > 768 or length % 3 != 0) return Error.InvalidPng;
123
+ seen_plte = true;
124
+ } else if (std.mem.eql(u8, kind, "tRNS")) {
125
+ if (color_type == .palette) {
126
+ if (length > 256) return Error.InvalidPng;
127
+ palette_alpha_len = length;
128
+ }
129
+ } else if (std.mem.eql(u8, kind, "IDAT")) {
130
+ if (length > 0) {
131
+ seen_idat = true;
132
+ if (verify_idat) {
133
+ try idat.appendSlice(maybe_alloc.?, body);
134
+ }
135
+ }
136
+ } else if (std.mem.eql(u8, kind, "IEND")) {
137
+ // IEND は長さ 0 かつ末尾チャンクでなければならない(末尾余剰データの直送を防ぐ)
138
+ if (length != 0 or body_start + 4 != data.len) return Error.InvalidPng;
139
+ seen_iend = true;
140
+ break;
141
+ }
142
+
143
+ offset = body_start + length + 4;
144
+ }
145
+
146
+ if (!seen_ihdr or !seen_idat or !seen_iend) return Error.InvalidPng;
147
+ if (color_type == .palette and !seen_plte) return Error.InvalidPng;
148
+
149
+ if (verify_idat) {
150
+ const samples = samplesPerPixel(color_type);
151
+ const bytes_per_sample: u8 = if (bit_depth == 16) 2 else 1;
152
+ const bytes_per_pixel: usize = @as(usize, samples) * bytes_per_sample;
153
+ const stride = std.math.mul(usize, width, bytes_per_pixel) catch return Error.TooLarge;
154
+ const row_bytes = std.math.add(usize, stride, 1) catch return Error.TooLarge;
155
+ const expected = std.math.mul(usize, row_bytes, height) catch return Error.TooLarge;
156
+ if (expected > MAX_DECODED_BYTES) return Error.TooLarge;
157
+ try verifyInflate(maybe_alloc.?, idat.items, expected, cancelled);
158
+ }
159
+
160
+ const channels: u8 = if (hasAlpha(color_type, palette_alpha_len)) 4 else 3;
161
+ return .{ .width = width, .height = height, .channels = channels };
162
+ }
163
+
164
+ /// PNG を RGB / RGBA の生画素に展開する
165
+ pub fn decode(alloc: std.mem.Allocator, data: []const u8, max_pixels: u64) Error!Image {
166
+ return decodeCancelable(alloc, data, max_pixels, null);
167
+ }
168
+
169
+ /// キャンセルフラグを監視しながら PNG を RGB / RGBA の生画素に展開する
170
+ pub fn decodeCancelable(
171
+ alloc: std.mem.Allocator,
172
+ data: []const u8,
173
+ max_pixels: u64,
174
+ cancelled: ?*const std.atomic.Value(bool),
175
+ ) Error!Image {
176
+ if (data.len < 8 or !std.mem.eql(u8, data[0..8], SIGNATURE)) return Error.InvalidPng;
177
+
178
+ var width: u32 = 0;
179
+ var height: u32 = 0;
180
+ var bit_depth: u8 = 0;
181
+ var color_type: ColorType = .rgb;
182
+ var palette: []u8 = &.{};
183
+ var palette_alpha: []u8 = &.{};
184
+ defer alloc.free(palette);
185
+ defer alloc.free(palette_alpha);
186
+
187
+ // IDAT はファイル内で分割されていることがあるので、まとめてから伸長する
188
+ var idat: std.ArrayList(u8) = .empty;
189
+ defer idat.deinit(alloc);
190
+
191
+ var offset: usize = 8;
192
+ var seen_ihdr = false;
193
+ var seen_plte = false;
194
+ while (offset + 8 <= data.len) {
195
+ const length = std.mem.readInt(u32, data[offset..][0..4], .big);
196
+ const kind = data[offset + 4 ..][0..4];
197
+ const body_start = offset + 8;
198
+ if (data.len - body_start < 4 or length > data.len - body_start - 4) return Error.InvalidPng;
199
+ const body = data[body_start .. body_start + length];
200
+
201
+ if (std.mem.eql(u8, kind, "IHDR")) {
202
+ if (seen_ihdr or offset != 8 or length != 13) return Error.InvalidPng;
203
+ width = std.mem.readInt(u32, body[0..4], .big);
204
+ height = std.mem.readInt(u32, body[4..8], .big);
205
+ bit_depth = body[8];
206
+ color_type = std.enums.fromInt(ColorType, body[9]) orelse return Error.UnsupportedPng;
207
+ if (body[10] != 0 or body[11] != 0 or body[12] != 0) return Error.UnsupportedPng; // インターレース・未知圧縮/フィルタは非対応
208
+ if (bit_depth != 8 and bit_depth != 16) return Error.UnsupportedPng;
209
+ if (color_type == .palette and bit_depth != 8) return Error.InvalidPng;
210
+ if (width == 0 or height == 0) return Error.InvalidPng;
211
+ if (width > MAX_DIMENSION or height > MAX_DIMENSION) return Error.TooLarge;
212
+ if (@as(u64, width) * height > max_pixels) return Error.TooLarge;
213
+ seen_ihdr = true;
214
+ } else if (std.mem.eql(u8, kind, "PLTE")) {
215
+ if (seen_plte or length == 0 or length > 768 or length % 3 != 0) return Error.InvalidPng;
216
+ palette = try alloc.realloc(palette, length);
217
+ @memcpy(palette, body);
218
+ seen_plte = true;
219
+ } else if (std.mem.eql(u8, kind, "tRNS")) {
220
+ if (color_type == .palette) {
221
+ if (length > 256) return Error.InvalidPng;
222
+ palette_alpha = try alloc.realloc(palette_alpha, length);
223
+ @memcpy(palette_alpha, body);
224
+ }
225
+ } else if (std.mem.eql(u8, kind, "IDAT")) {
226
+ try idat.appendSlice(alloc, body);
227
+ } else if (std.mem.eql(u8, kind, "IEND")) {
228
+ break;
229
+ }
230
+
231
+ offset = body_start + length + 4; // CRC は読み飛ばす(端末に出すだけなので検証しない)
232
+ }
233
+ if (!seen_ihdr or idat.items.len == 0) return Error.InvalidPng;
234
+ if (color_type == .palette and !seen_plte) return Error.InvalidPng;
235
+
236
+ const samples = samplesPerPixel(color_type);
237
+ const bytes_per_sample: u8 = if (bit_depth == 16) 2 else 1;
238
+ const bytes_per_pixel: usize = @as(usize, samples) * bytes_per_sample;
239
+ const stride = std.math.mul(usize, width, bytes_per_pixel) catch return Error.TooLarge;
240
+ const row_bytes = std.math.add(usize, stride, 1) catch return Error.TooLarge;
241
+ const expected = std.math.mul(usize, row_bytes, height) catch return Error.TooLarge;
242
+ if (expected > MAX_DECODED_BYTES) return Error.TooLarge;
243
+
244
+ const raw = try inflate(alloc, idat.items, expected, cancelled);
245
+ defer alloc.free(raw);
246
+ if (raw.len != expected) return Error.InvalidPng;
247
+ if (cancelled) |flag| {
248
+ if (flag.load(.acquire)) return Error.Cancelled;
249
+ }
250
+
251
+ unfilter(raw, width, height, stride, bytes_per_pixel);
252
+
253
+ const out_channels: u8 = if (hasAlpha(color_type, palette_alpha.len)) 4 else 3;
254
+ const pixel_bytes = std.math.mul(usize, std.math.mul(usize, width, height) catch return Error.TooLarge, out_channels) catch return Error.TooLarge;
255
+ const pixels = try alloc.alloc(u8, pixel_bytes);
256
+ errdefer alloc.free(pixels);
257
+ try expand(raw, pixels, width, height, stride, color_type, bit_depth, out_channels, palette, palette_alpha);
258
+
259
+ return .{ .width = width, .height = height, .channels = out_channels, .pixels = pixels };
260
+ }
261
+
262
+ /// RGB / RGBA の生画素を PNG にする(フィルタなし・高速 zlib 圧縮)
263
+ pub fn encode(alloc: std.mem.Allocator, pixels: []const u8, width: u32, height: u32, channels: u8) Error![]u8 {
264
+ std.debug.assert(channels == 3 or channels == 4);
265
+ const stride = @as(usize, width) * channels;
266
+ if (pixels.len < stride * height) return Error.InvalidPng;
267
+
268
+ // フィルタ種別 0 を各行の先頭に付けて高速 zlib 圧縮(level_1)する。端末送信用のため速度と転送量のバランスを採る
269
+ var compressed = std.Io.Writer.Allocating.initCapacity(alloc, @max(@as(usize, 64 * 1024), stride * height / 4)) catch
270
+ return Error.OutOfMemory;
271
+ defer compressed.deinit();
272
+ const window = alloc.alloc(u8, flate.max_window_len) catch return Error.OutOfMemory;
273
+ defer alloc.free(window);
274
+ var deflate = flate.Compress.init(&compressed.writer, window, .zlib, .fastest) catch return Error.OutOfMemory;
275
+ var y: u32 = 0;
276
+ while (y < height) : (y += 1) {
277
+ deflate.writer.writeAll(&.{0}) catch return Error.OutOfMemory;
278
+ deflate.writer.writeAll(pixels[@as(usize, y) * stride ..][0..stride]) catch return Error.OutOfMemory;
279
+ }
280
+ deflate.finish() catch return Error.OutOfMemory;
281
+ compressed.writer.flush() catch return Error.OutOfMemory;
282
+ const body = compressed.written();
283
+
284
+ var out: std.ArrayList(u8) = .empty;
285
+ errdefer out.deinit(alloc);
286
+ try out.ensureTotalCapacity(alloc, SIGNATURE.len + 25 + 12 + body.len + 12);
287
+ try out.appendSlice(alloc, SIGNATURE);
288
+
289
+ var ihdr: [13]u8 = undefined;
290
+ std.mem.writeInt(u32, ihdr[0..4], width, .big);
291
+ std.mem.writeInt(u32, ihdr[4..8], height, .big);
292
+ ihdr[8] = 8; // bit depth
293
+ ihdr[9] = if (channels == 4) 6 else 2; // RGBA / RGB
294
+ ihdr[10] = 0; // compression
295
+ ihdr[11] = 0; // filter
296
+ ihdr[12] = 0; // interlace
297
+ try writeChunk(alloc, &out, "IHDR", &ihdr);
298
+ try writeChunk(alloc, &out, "IDAT", body);
299
+ try writeChunk(alloc, &out, "IEND", &.{});
300
+ return out.toOwnedSlice(alloc);
301
+ }
302
+
303
+ fn writeChunk(alloc: std.mem.Allocator, out: *std.ArrayList(u8), kind: []const u8, body: []const u8) Error!void {
304
+ var length: [4]u8 = undefined;
305
+ std.mem.writeInt(u32, &length, @intCast(body.len), .big);
306
+ try out.appendSlice(alloc, &length);
307
+ try out.appendSlice(alloc, kind);
308
+ try out.appendSlice(alloc, body);
309
+
310
+ var crc: Crc32 = .init();
311
+ crc.update(kind);
312
+ crc.update(body);
313
+ var checksum: [4]u8 = undefined;
314
+ std.mem.writeInt(u32, &checksum, crc.final(), .big);
315
+ try out.appendSlice(alloc, &checksum);
316
+ }
317
+
318
+ fn inflate(
319
+ alloc: std.mem.Allocator,
320
+ zlib_data: []const u8,
321
+ expected: usize,
322
+ cancelled: ?*const std.atomic.Value(bool),
323
+ ) Error![]u8 {
324
+ var reader: std.Io.Reader = .fixed(zlib_data);
325
+ var out = std.Io.Writer.Allocating.initCapacity(alloc, @min(expected + 16, 32 * 1024 * 1024)) catch
326
+ return Error.OutOfMemory;
327
+ errdefer out.deinit();
328
+ const window = alloc.alloc(u8, flate.max_window_len) catch return Error.OutOfMemory;
329
+ defer alloc.free(window);
330
+ var decompress: flate.Decompress = .init(&reader, .zlib, window);
331
+
332
+ // 展開サイズが expected を 1 バイトでも超えたら即座に打ち切る(decompression bomb 対策)。
333
+ // 64KB ごとにキャンセルも確認する
334
+ var total: usize = 0;
335
+ const limit = std.math.add(usize, expected, 1) catch return Error.TooLarge;
336
+ while (total < limit) {
337
+ if (cancelled) |flag| {
338
+ if (flag.load(.acquire)) return Error.Cancelled;
339
+ }
340
+ const step = @min(limit - total, 64 * 1024);
341
+ const n = decompress.reader.stream(&out.writer, .limited(step)) catch |err| switch (err) {
342
+ error.EndOfStream => break,
343
+ error.WriteFailed => return Error.OutOfMemory,
344
+ else => return Error.InvalidPng,
345
+ };
346
+ total += n;
347
+ }
348
+ if (total > expected) return Error.InvalidPng;
349
+
350
+ out.writer.flush() catch return Error.OutOfMemory;
351
+ // バッファを丸ごと再コピーせず、そのまま所有権を返す
352
+ return out.toOwnedSlice() catch return Error.OutOfMemory;
353
+ }
354
+
355
+ /// 画素バッファを確保せず IDAT を固定スクラッチへ伸長し、展開サイズが expected と一致するかだけ検証する
356
+ fn verifyInflate(
357
+ alloc: std.mem.Allocator,
358
+ zlib_data: []const u8,
359
+ expected: usize,
360
+ cancelled: ?*const std.atomic.Value(bool),
361
+ ) Error!void {
362
+ var reader: std.Io.Reader = .fixed(zlib_data);
363
+ const window = alloc.alloc(u8, flate.max_window_len) catch return Error.OutOfMemory;
364
+ defer alloc.free(window);
365
+ var decompress: flate.Decompress = .init(&reader, .zlib, window);
366
+
367
+ var scratch: [16 * 1024]u8 = undefined;
368
+ var total: usize = 0;
369
+ const limit = std.math.add(usize, expected, 1) catch return Error.TooLarge;
370
+ while (total < limit) {
371
+ if (cancelled) |flag| {
372
+ if (flag.load(.acquire)) return Error.Cancelled;
373
+ }
374
+ const step = @min(limit - total, scratch.len);
375
+ var sink: std.Io.Writer = .fixed(&scratch);
376
+ const n = decompress.reader.stream(&sink, .limited(step)) catch |err| switch (err) {
377
+ error.EndOfStream => break,
378
+ else => return Error.InvalidPng,
379
+ };
380
+ total += n;
381
+ }
382
+ if (total != expected) return Error.InvalidPng;
383
+ }
384
+
385
+ fn samplesPerPixel(color_type: ColorType) u8 {
386
+ return switch (color_type) {
387
+ .gray => 1,
388
+ .rgb => 3,
389
+ .palette => 1,
390
+ .gray_alpha => 2,
391
+ .rgba => 4,
392
+ };
393
+ }
394
+
395
+ fn hasAlpha(color_type: ColorType, palette_alpha_len: usize) bool {
396
+ return switch (color_type) {
397
+ .rgba, .gray_alpha => true,
398
+ .palette => palette_alpha_len > 0,
399
+ else => false,
400
+ };
401
+ }
402
+
403
+ /// PNG の行フィルタを戻す(raw は [フィルタ種別][行データ] の繰り返し)
404
+ fn unfilter(raw: []u8, width: u32, height: u32, stride: usize, bpp: usize) void {
405
+ _ = width;
406
+ var y: u32 = 0;
407
+ while (y < height) : (y += 1) {
408
+ const row_start = @as(usize, y) * (stride + 1);
409
+ const filter = raw[row_start];
410
+ const row = raw[row_start + 1 ..][0..stride];
411
+ const prev: ?[]const u8 = if (y == 0) null else raw[@as(usize, y - 1) * (stride + 1) + 1 ..][0..stride];
412
+
413
+ switch (filter) {
414
+ 0 => {},
415
+ 1 => { // Sub
416
+ var i = bpp;
417
+ while (i < stride) : (i += 1) row[i] +%= row[i - bpp];
418
+ },
419
+ 2 => { // Up
420
+ if (prev) |up| {
421
+ var i: usize = 0;
422
+ while (i < stride) : (i += 1) row[i] +%= up[i];
423
+ }
424
+ },
425
+ 3 => { // Average
426
+ if (prev) |up| {
427
+ var i: usize = 0;
428
+ while (i < bpp) : (i += 1) row[i] +%= up[i] >> 1;
429
+ while (i < stride) : (i += 1) {
430
+ const sum: u16 = @as(u16, row[i - bpp]) + @as(u16, up[i]);
431
+ row[i] +%= @intCast(sum >> 1);
432
+ }
433
+ } else {
434
+ var i = bpp;
435
+ while (i < stride) : (i += 1) row[i] +%= row[i - bpp] >> 1;
436
+ }
437
+ },
438
+ 4 => { // Paeth
439
+ if (prev) |up| {
440
+ var i: usize = 0;
441
+ while (i < bpp) : (i += 1) row[i] +%= up[i];
442
+ while (i < stride) : (i += 1) {
443
+ const a: i16 = row[i - bpp];
444
+ const b: i16 = up[i];
445
+ const c: i16 = up[i - bpp];
446
+ const p = a + b - c;
447
+ const pa = @abs(p - a);
448
+ const pb = @abs(p - b);
449
+ const pc = @abs(p - c);
450
+ const pred: u8 = if (pa <= pb and pa <= pc)
451
+ @intCast(a)
452
+ else if (pb <= pc)
453
+ @intCast(b)
454
+ else
455
+ @intCast(c);
456
+ row[i] +%= pred;
457
+ }
458
+ } else {
459
+ var i = bpp;
460
+ while (i < stride) : (i += 1) row[i] +%= row[i - bpp];
461
+ }
462
+ },
463
+ else => {}, // 未知のフィルタは素通し(壊れた画像でも落ちない)
464
+ }
465
+ }
466
+ }
467
+
468
+ /// フィルタを戻した行を RGB / RGBA に並べ替える
469
+ fn expand(
470
+ raw: []const u8,
471
+ out: []u8,
472
+ width: u32,
473
+ height: u32,
474
+ stride: usize,
475
+ color_type: ColorType,
476
+ bit_depth: u8,
477
+ out_channels: u8,
478
+ palette: []const u8,
479
+ palette_alpha: []const u8,
480
+ ) Error!void {
481
+ const out_stride = @as(usize, width) * out_channels;
482
+
483
+ // 8bit RGB / RGBA は最も頻度が高く、そのまま行コピーできる
484
+ if (bit_depth == 8 and ((color_type == .rgb and out_channels == 3) or
485
+ (color_type == .rgba and out_channels == 4)))
486
+ {
487
+ var y: u32 = 0;
488
+ while (y < height) : (y += 1) {
489
+ const src_row = raw[@as(usize, y) * (stride + 1) + 1 ..][0..out_stride];
490
+ const dst_row = out[@as(usize, y) * out_stride ..][0..out_stride];
491
+ @memcpy(dst_row, src_row);
492
+ }
493
+ return;
494
+ }
495
+
496
+ const step: usize = if (bit_depth == 16) 2 else 1;
497
+ var y: u32 = 0;
498
+ while (y < height) : (y += 1) {
499
+ const row = raw[@as(usize, y) * (stride + 1) + 1 ..][0..stride];
500
+ const dst_row = out[@as(usize, y) * out_stride ..][0..out_stride];
501
+ switch (color_type) {
502
+ .gray => {
503
+ var x: usize = 0;
504
+ while (x < width) : (x += 1) {
505
+ const value = row[x * step];
506
+ const off = x * 3;
507
+ dst_row[off] = value;
508
+ dst_row[off + 1] = value;
509
+ dst_row[off + 2] = value;
510
+ }
511
+ },
512
+ .gray_alpha => {
513
+ var x: usize = 0;
514
+ while (x < width) : (x += 1) {
515
+ const value = row[x * 2 * step];
516
+ const off = x * 4;
517
+ dst_row[off] = value;
518
+ dst_row[off + 1] = value;
519
+ dst_row[off + 2] = value;
520
+ dst_row[off + 3] = row[x * 2 * step + step];
521
+ }
522
+ },
523
+ .rgb => {
524
+ var x: usize = 0;
525
+ while (x < width) : (x += 1) {
526
+ const base = x * 3 * step;
527
+ const off = x * 3;
528
+ dst_row[off] = row[base];
529
+ dst_row[off + 1] = row[base + step];
530
+ dst_row[off + 2] = row[base + 2 * step];
531
+ }
532
+ },
533
+ .rgba => {
534
+ var x: usize = 0;
535
+ while (x < width) : (x += 1) {
536
+ const base = x * 4 * step;
537
+ const off = x * 4;
538
+ dst_row[off] = row[base];
539
+ dst_row[off + 1] = row[base + step];
540
+ dst_row[off + 2] = row[base + 2 * step];
541
+ dst_row[off + 3] = row[base + 3 * step];
542
+ }
543
+ },
544
+ .palette => {
545
+ var x: usize = 0;
546
+ while (x < width) : (x += 1) {
547
+ const index = row[x];
548
+ const base = @as(usize, index) * 3;
549
+ if (base + 2 >= palette.len) return Error.InvalidPng;
550
+ const off = x * out_channels;
551
+ dst_row[off] = palette[base];
552
+ dst_row[off + 1] = palette[base + 1];
553
+ dst_row[off + 2] = palette[base + 2];
554
+ if (out_channels == 4) {
555
+ dst_row[off + 3] = if (index < palette_alpha.len) palette_alpha[index] else 255;
556
+ }
557
+ }
558
+ },
559
+ }
560
+ }
561
+ }