-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbuild.zig
More file actions
2172 lines (1992 loc) · 96.5 KB
/
Copy pathbuild.zig
File metadata and controls
2172 lines (1992 loc) · 96.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const headless = b.option(bool, "headless", "Build headless server (no SDL/X11 link)") orelse false;
// Expose the headless flag to the app as a `build_options` import.
const build_options = b.addOptions();
build_options.addOption(bool, "headless", headless);
// Default API keys compiled into the binary so a fresh install works out of
// the box — end users of a release build don't have to register their own.
// Resolved at build time from env vars (release CI injects repo secrets),
// falling back to a repo-root `.env` (gitignored) for local release builds.
// Empty when unset, which just restores bring-your-own-key behavior. A
// runtime env var / .env / Settings entry always OVERRIDES the embedded
// value (see state.loadTmdbTokenFromEnv). NB: an embedded key is extractable
// from the shipped binary — only bake in free, rate-limited keys (a TMDB
// read token, an OMDb free key), never anything sensitive.
// App version, read from build.zig.zon so there is ONE source of truth.
// updater.zig used to carry its own `APP_VERSION` constant "kept in sync"
// by hand; it drifted, and v0.6.1 shipped reporting itself as 0.6.0 in the
// About page — and, worse, telling every 0.6.1 user an update was
// available forever, because the update check compares this string to the
// latest GitHub tag (issue #21).
build_options.addOption([]const u8, "app_version", zonVersion(b));
build_options.addOption([]const u8, "tmdb_default_token", embeddedKey(b, &.{ "OPAL_TMDB_TOKEN", "TMDB_API_TOKEN" }));
build_options.addOption([]const u8, "omdb_default_key", embeddedKey(b, &.{ "OPAL_OMDB_KEY", "OMDB_API_KEY" }));
const build_options_module = build_options.createModule();
const exe = b.addExecutable(.{
.name = "opal",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
}),
});
exe.use_llvm = true;
// Windows: embed an application manifest declaring Per-Monitor-V2 DPI
// awareness. Windows reads this at process creation (before SDL_Init), so
// the whole app renders at native pixel density instead of being bitmap-
// stretched from a virtualized low resolution (the "looks low-res / blurry"
// report). Also flips on longPathAware. No-op on macOS/Linux.
if (target.result.os.tag == .windows) {
exe.win32_manifest = b.path("packaging/windows/opal.manifest");
// Embed the app icon (resource ID 1) so Explorer, the taskbar and
// Alt-Tab show the Opal gem instead of the generic default exe icon.
exe.root_module.addWin32ResourceFile(.{ .file = b.path("packaging/windows/opal.rc") });
// GUI subsystem for the desktop build so launching the app does NOT pop
// a console window alongside it. The headless server build keeps the
// console subsystem (it's a CLI that logs to stdout). Child processes
// are spawned with CREATE_NO_WINDOW (io_global) so they don't flash
// their own consoles now that we have none to inherit.
if (!headless) exe.subsystem = .Windows;
}
// System SDL2 integration. On Wayland compositors (COSMIC DE, etc.) the bundled SDL2
// only has X11 support (runs under XWayland) and window title updates are ignored.
// Linux distributions provide a correctly linked SDL2 (and, on Wayland,
// native Wayland support). Prefer it by default: Zig 0.16's linker rejects
// the prebuilt SDL2 archive when it contains shared-library members such
// as libX11.so. Users can still opt out with `-fsys=sdl2=false`.
_ = b.systemIntegrationOption("sdl2", .{
.default = target.result.os.tag == .linux,
});
const dvui_dep = b.dependency("dvui", .{
.target = target,
.optimize = optimize,
});
// Homebrew prefix for macOS lib/include paths. Apple Silicon installs to
// /opt/homebrew (default); Intel macs use /usr/local. `brew shellenv`
// exports HOMEBREW_PREFIX, so honor it when set.
const brew_prefix = b.graph.environ_map.get("HOMEBREW_PREFIX") orelse "/opt/homebrew";
// MSYS2 MINGW64 prefix for Windows lib/include paths. MSYS2 exports
// MINGW_PREFIX inside a MINGW64 shell (e.g. C:/msys64/mingw64); honor it
// when set, analogous to HOMEBREW_PREFIX on macOS.
const mingw_prefix = b.graph.environ_map.get("MINGW_PREFIX") orelse "C:/msys64/mingw64";
// MSYS2 install root (parent of the mingw64 prefix): `sh` lives in
// <root>/usr/bin while the compiler and runtime DLLs live in
// <prefix>/bin. Both are needed by build/run steps below because a plain
// PowerShell/cmd session has neither on its PATH.
const msys_root = std.fs.path.dirname(std.mem.trimEnd(u8, mingw_prefix, "/\\")) orelse "C:/msys64";
const msys_path_prefix = b.fmt("{s}/bin;{s}/usr/bin", .{ mingw_prefix, msys_root });
const is_windows = target.result.os.tag == .windows;
if (target.result.os.tag == .macos) {
exe.root_module.addLibraryPath(.{ .cwd_relative = b.fmt("{s}/lib", .{brew_prefix}) });
exe.root_module.addIncludePath(.{ .cwd_relative = b.fmt("{s}/include", .{brew_prefix}) });
// Native Now Playing card + hardware media keys (MPNowPlayingInfoCenter
// / MPRemoteCommandCenter) — see src/macos/media_remote.m and its Zig
// side src/player/media_remote.zig. Desktop only: it drags in the ObjC
// runtime + Foundation, which the desktop build got transitively from
// dvui's bundled SDL2 and which headless (Phase S1) no longer links.
if (!headless) {
exe.root_module.addCSourceFile(.{
.file = b.path("src/macos/media_remote.m"),
.flags = &[_][]const u8{ "-fobjc-arc", "-O2" },
});
exe.root_module.linkFramework("MediaPlayer", .{});
}
} else if (is_windows) {
// Windows (MinGW/MSYS2): headers + import libs from the MINGW64 prefix.
// dvui's bundled SDL2 supplies the SDL symbols (like macOS), so only
// SDL2 *headers* are needed from mingw64 (mingw-w64-SDL2 package).
exe.root_module.addLibraryPath(.{ .cwd_relative = b.fmt("{s}/lib", .{mingw_prefix}) });
exe.root_module.addIncludePath(.{ .cwd_relative = b.fmt("{s}/include", .{mingw_prefix}) });
// Aro (zig 0.16's translate-c) predefines _FORTIFY_SOURCE=2 for
// optimized builds; the MinGW fortify inline wrappers it then pulls
// from <wchar.h> translate into Zig that fails AstGen ("unused local
// constant"), breaking every @cImport in ReleaseSafe/ReleaseFast.
// Force fortify off for every module that @cImports windows headers:
// ours, dvui's (tinyfiledialogs), and dvui's sdl backend (SDL.h).
exe.root_module.addCMacro("_FORTIFY_SOURCE", "0");
exe.root_module.linkSystemLibrary("crypt32", .{});
// Win32 window-procedure fixes the custom title bar can't get through
// SDL: work-area-aware maximize and caption double-click. Desktop only
// — it calls into SDL, which the headless build does not link.
if (!headless) {
exe.root_module.addCSourceFile(.{
.file = b.path("src/ui/win_titlebar.c"),
.flags = &[_][]const u8{"-O2"},
});
}
const dvui_mod = dvui_dep.module("dvui_sdl2");
dvui_mod.addCMacro("_FORTIFY_SOURCE", "0");
if (dvui_mod.import_table.get("backend")) |backend_mod| {
backend_mod.addCMacro("_FORTIFY_SOURCE", "0");
}
} else if (!headless) {
// Non-macOS: link system SDL2. On macOS, dvui's bundled SDL2 is used
// (avoids duplicate-class ObjC warnings when both static + dyn SDL2 load).
exe.root_module.linkSystemLibrary("SDL2", .{});
}
if (headless) {
// ── Phase S1: the server build links no GUI stack at all ──
// dvui is swapped for a stub (src/core/dvui_headless.zig). This works
// only because Zig analyzes reachable decls: `main == headlessEntry`
// never references appFrame, so ui/* and every render* in services/*
// are not compiled. See docs/headless-server-spec.md.
const stub = b.createModule(.{
.root_source_file = b.path("src/core/dvui_headless.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
});
// The stub's one real dependency: poster.zig decodes cover art through
// dvui.c.stbi_*, and /poster serves it over HTTP. Compile dvui's OWN
// vendored stb_image so the decoder is byte-for-byte the desktop one.
stub.addIncludePath(dvui_dep.path("vendor/stb"));
stub.addCSourceFile(.{
.file = dvui_dep.path("vendor/stb/stb_image_impl.c"),
.flags = &[_][]const u8{"-O2"},
});
exe.root_module.addImport("dvui", stub);
} else {
// Add dvui_sdl2 which is a fully bundled standalone backend.
exe.root_module.addImport("dvui", dvui_dep.module("dvui_sdl2"));
}
// Expose -Dheadless to the app code via @import("build_options").
exe.root_module.addImport("build_options", build_options_module);
// Fetch and bind TVG Icons library
const icons_dep = b.dependency("icons", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("icons", icons_dep.module("icons"));
const tv_detail_tests = b.addTest(.{
.root_module = exe.root_module,
.filters = &.{"TV detail"},
});
const run_tv_detail_tests = b.addRunArtifact(tv_detail_tests);
if (is_windows) {
run_tv_detail_tests.setEnvironmentVariable("PATH", b.fmt("{s};{s}", .{
msys_path_prefix,
b.graph.environ_map.get("PATH") orelse "",
}));
}
b.step("test-tv-detail", "Test production TV metadata and restore helpers").dependOn(&run_tv_detail_tests.step);
// DPI-bypass sidecar (debpalash/zig-bypassdpi): a cross-platform userspace
// proxy that fragments the TLS ClientHello so ISP DPI can't read the SNI.
// Built as its own exe here and installed alongside `opal`; the app spawns it
// as a managed subprocess when the Settings toggle is on (see
// services/dpi_bypass.zig), and build-app.sh bundles it into Resources.
// Built for every target now — the sidecar compiles on Windows since
// zig-bypassdpi switched argv parsing to iterateAllocator (the old
// std.process.Args.iterate() was a hard @compileError on Windows).
const bypassdpi_dep = b.dependency("bypassdpi", .{
.target = target,
.optimize = optimize,
});
b.installArtifact(bypassdpi_dep.artifact("zig-bypassdpi"));
// Link MPV and SQLite.
// Windows: zig's -l search for windows-gnu only tries `{name}.dll`,
// `{name}.lib` and `lib{name}.a` — it never finds MinGW `lib{name}.dll.a`
// import libs, so pass those explicitly as linker objects.
if (is_windows) {
exe.root_module.addObjectFile(.{ .cwd_relative = b.fmt("{s}/lib/libmpv.dll.a", .{mingw_prefix}) });
exe.root_module.addObjectFile(.{ .cwd_relative = b.fmt("{s}/lib/libsqlite3.dll.a", .{mingw_prefix}) });
} else {
exe.root_module.linkSystemLibrary("mpv", .{});
exe.root_module.linkSystemLibrary("sqlite3", .{});
}
// SQLite Vector DB. -DSQLITE_CORE makes sqlite-vec call the linked
// sqlite3 directly instead of going through the extension API pointer —
// required because db.zig registers it per-connection via a direct
// sqlite3_vec_init() call (Apple's libsqlite3 does not support
// process-global sqlite3_auto_extension, which used to fail silently
// and left every vec0 CREATE TABLE a no-op on macOS).
exe.root_module.addCSourceFile(.{
.file = b.path("src/core/sqlite/sqlite-vec.c"),
.flags = &[_][]const u8{ "-O3", "-fomit-frame-pointer", "-DSQLITE_CORE" },
});
// Libtorrent & C++ Linkage (Dynamic Shared Object isolating GCC C++ ABIs)
// Checking modification times avoids recompiling the heavy C++ wrapper on every `zig build` iteration.
// Windows note: zig's windows-gnu -l search tries `torrent_wrapper.dll`
// first and MinGW-flavored lld links directly against a DLL, so name the
// artifact `torrent_wrapper.dll` (no `lib` prefix). MSYS2 has sh + g++.
// pkg-config supplies the TLS-backend defines the wrapper needs: since
// libtorrent-rasterbar 2.0.13, config.hpp enables TORRENT_USE_RTC (WebRTC)
// and hard-errors unless TORRENT_USE_OPENSSL/GNUTLS is also defined to match
// how libtorrent was built. pkg-config --cflags emits the right -D flags
// (and --libs the matching -lssl/-lcrypto); we keep -I{prefix}/include for
// boost and a trailing -ltorrent-rasterbar as an empty-pkg-config fallback.
const compile_cmd = if (target.result.os.tag == .macos)
b.fmt("if [ ! -f libtorrent_wrapper.so ] || [ src/torrent_wrapper.cpp -nt libtorrent_wrapper.so ]; then echo 'Compiling C++ torrent wrapper...'; g++ -std=c++17 -O3 -shared -fPIC -I{s}/include $(pkg-config --cflags libtorrent-rasterbar 2>/dev/null) -L{s}/lib src/torrent_wrapper.cpp -o libtorrent_wrapper.so $(pkg-config --libs libtorrent-rasterbar 2>/dev/null) -ltorrent-rasterbar; fi", .{ brew_prefix, brew_prefix })
else if (is_windows)
// pkg-config --cflags is REQUIRED here, same as the POSIX branches:
// MSYS2's libtorrent-rasterbar (≥2.0.13) enables TORRENT_USE_RTC in
// config.hpp, which hard-#errors unless the matching TLS backend define
// (TORRENT_USE_OPENSSL/GNUTLS) is also passed. pkg-config emits it (plus
// -lssl/-lcrypto/-lbcrypt/-lmswsock in --libs); the trailing
// -ltorrent-rasterbar -lws2_32 -liphlpapi -lcrypt32 stay as a fallback
// for an empty pkg-config.
b.fmt("if [ ! -f torrent_wrapper.dll ] || [ src/torrent_wrapper.cpp -nt torrent_wrapper.dll ]; then echo 'Compiling C++ torrent wrapper...'; g++ -std=c++17 -O3 -shared -I{s}/include $(pkg-config --cflags libtorrent-rasterbar 2>/dev/null) -L{s}/lib src/torrent_wrapper.cpp -o torrent_wrapper.dll $(pkg-config --libs libtorrent-rasterbar 2>/dev/null) -ltorrent-rasterbar -lws2_32 -liphlpapi -lcrypt32; fi", .{ mingw_prefix, mingw_prefix })
else
// -Wl,-soname is REQUIRED: without it the .so has no SONAME, so the
// linker records the ABSOLUTE build path (/src/libtorrent_wrapper.so)
// as the exe's DT_NEEDED — which breaks the moment the binary runs
// anywhere but the build dir (the Docker runtime stage failed exactly
// this way). With a SONAME the NEEDED is just the name, resolved via
// rpath / ldconfig (/usr/local/lib) wherever it's installed. The
// wrapper's own $ORIGIN runpath also lets a rootless/private bundle put
// libtorrent beside it; an executable RUNPATH is not transitive through
// dependent DSOs.
"if [ ! -f libtorrent_wrapper.so ] || [ src/torrent_wrapper.cpp -nt libtorrent_wrapper.so ]; then echo 'Compiling C++ torrent wrapper...'; g++ -std=c++17 -O3 -shared -fPIC -Wl,-soname,libtorrent_wrapper.so -Wl,-rpath,'$ORIGIN' $(pkg-config --cflags libtorrent-rasterbar 2>/dev/null) src/torrent_wrapper.cpp -o libtorrent_wrapper.so $(pkg-config --libs libtorrent-rasterbar 2>/dev/null) -ltorrent-rasterbar; fi";
// Only invoke the host g++ when it can actually produce a wrapper for the
// target (native builds). Cross-compiling (e.g. windows from macOS for a
// semantic-analysis check) would otherwise emit a host-ABI object under the
// target's expected name and confuse the link.
if (b.graph.host.result.os.tag == target.result.os.tag) {
// Windows: sh, g++ and pkg-config all live inside MSYS2, which a plain
// PowerShell/cmd session does NOT have on its PATH — a bare "sh" then
// aborts the whole build with a bare `FileNotFound`. Locate the shell
// under the MSYS2 root (MINGW_PREFIX's parent) and hand the step a PATH
// carrying both MSYS2 bin dirs, so the toolchain resolves inside the
// script too (g++/pkg-config are in mingw64/bin, sh in usr/bin).
const shell: []const u8 = if (is_windows)
b.findProgram(&.{"sh"}, &.{b.fmt("{s}/usr/bin", .{msys_root})}) catch
std.debug.panic("MSYS2 shell not found: no `sh` on PATH and none at {s}/usr/bin. Install MSYS2 (see docs) or set MINGW_PREFIX to your mingw64 prefix.", .{msys_root})
else
"sh";
const compile_wrapper = b.addSystemCommand(&.{ shell, "-c", compile_cmd });
if (is_windows) {
compile_wrapper.setEnvironmentVariable("PATH", b.fmt("{s};{s}", .{
msys_path_prefix,
b.graph.environ_map.get("PATH") orelse "",
}));
}
exe.step.dependOn(&compile_wrapper.step);
}
if (target.result.os.tag == .linux) {
// Link the ELF DSO directly. addLibraryPath() makes Zig automatically
// append that absolute directory to DT_RUNPATH, even when explicit
// portable $ORIGIN paths are also present. The wrapper has a SONAME, so
// the resulting DT_NEEDED remains the portable basename.
exe.root_module.addObjectFile(b.path("libtorrent_wrapper.so"));
} else {
exe.root_module.addLibraryPath(b.path("."));
exe.root_module.linkSystemLibrary("torrent_wrapper", .{});
}
// An absolute checkout RUNPATH is useful for an unbundled Debug dev run,
// but must never leak into distributed Linux binaries: on a developer
// machine it shadows the installed wrapper, and on every other machine it
// is a dead/non-reproducible path. macOS's bundle rewrite still needs the
// build-tree lookup before install_name_tool lays out Frameworks.
if (!is_windows and (target.result.os.tag == .macos or optimize == .Debug)) {
exe.root_module.addRPath(b.path("."));
}
// Packaged-install layouts (deb/rpm/.run/tarball): let the installed
// binary find libtorrent_wrapper.so relative to itself — next to the
// binary (tarball) or in ../lib/opal (/usr/bin + /usr/lib/opal).
if (target.result.os.tag != .macos and !is_windows) {
exe.root_module.addRPathSpecial("$ORIGIN");
exe.root_module.addRPathSpecial("$ORIGIN/../lib/opal");
}
// For .app bundles: let the binary find libtorrent_wrapper.so in
// Contents/Frameworks/ when launched via Finder/NSWorkspace (CWD=/).
if (target.result.os.tag == .macos) {
exe.root_module.addRPathSpecial("@executable_path/../Frameworks");
// Reserve enough header space so install_name_tool can rewrite LC_LOAD_DYLIB
// entries after the bundle is laid out (scripts/build-app.sh).
exe.headerpad_max_install_names = true;
}
// OCR via ONNX Runtime (PP-OCR pipeline) — optional, gated by -Docr.
// Default off: onnxruntime isn't a standard Arch/Debian package and the
// manga/video frame OCR features are only used by a subset of users.
// Build with `-Docr=true` to enable (requires `onnxruntime` installed:
// Arch: `pacman -S onnxruntime-cpu`, macOS: `brew install onnxruntime`).
const enable_ocr = b.option(bool, "ocr", "Enable OCR via ONNX Runtime (default: auto-detect)") orelse false;
if (enable_ocr) {
exe.root_module.addCSourceFile(.{
.file = b.path("ort/ocr_ort.c"),
.flags = &[_][]const u8{ "-O2", "-Wno-unused-result" },
});
exe.root_module.addIncludePath(b.path("ort"));
exe.root_module.addLibraryPath(b.path("ort"));
if (is_windows) {
// ONNXRUNTIME_DIR: root of a vendored Microsoft onnxruntime release
// (github.com/microsoft/onnxruntime, onnxruntime-win-x64-<ver>.zip —
// include/*.h + lib/onnxruntime.{lib,dll}). MSYS2 has no onnxruntime
// package for the MINGW64 environment, and the UCRT64 one links a
// different CRT than zig's x86_64-windows-gnu output — mixing them is
// what produced the "entry point strtod could not be located" launch
// failure in v0.1.0 (issue #3). The MS build is MSVC-compiled but
// exposes a pure C ABI, and its onnxruntime.lib is a plain COFF
// import lib that zig's lld links fine from the gnu target.
if (b.graph.environ_map.get("ONNXRUNTIME_DIR")) |ort_dir| {
exe.root_module.addIncludePath(.{ .cwd_relative = b.fmt("{s}/include", .{ort_dir}) });
exe.root_module.addObjectFile(.{ .cwd_relative = b.fmt("{s}/lib/onnxruntime.lib", .{ort_dir}) });
} else {
// No vendored dir: fall back to a MinGW-built import lib under
// MINGW_PREFIX for anyone who has one (see the mpv/sqlite3 note
// above on why .dll.a needs addObjectFile).
exe.root_module.addObjectFile(.{ .cwd_relative = b.fmt("{s}/lib/libonnxruntime.dll.a", .{mingw_prefix}) });
}
} else {
exe.root_module.linkSystemLibrary("onnxruntime", .{});
exe.root_module.addRPath(b.path("ort"));
}
}
// Surface OCR availability to the app source via `@import("ocr_build_options")`.
const ocr_build_options = b.addOptions();
ocr_build_options.addOption(bool, "has_ocr", enable_ocr);
exe.root_module.addOptions("ocr_build_options", ocr_build_options);
exe.root_module.addIncludePath(b.path("src"));
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
// opal.exe imports libmpv-2.dll / libsqlite3-0.dll, and torrent_wrapper.dll
// pulls in libtorrent, boost, openssl and libstdc++ — all MSYS2 DLLs. A GUI
// (subsystem:windows) exe that can't resolve them dies in a modal loader
// dialog with nothing on stderr, so give the child the MSYS2 bin dir even
// when the launching shell has no MSYS2 on PATH.
if (is_windows) {
run_cmd.setEnvironmentVariable("PATH", b.fmt("{s};{s}", .{
msys_path_prefix,
b.graph.environ_map.get("PATH") orelse "",
}));
}
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
// ── Fast build: use `zig build -Doptimize=ReleaseSafe` ──
// Note: a separate exe with different optimize level causes UBSan
// linker mismatch with dvui's bundled SDL2, so we use the standard
// -Doptimize flag instead.
// ── Unit Tests (pure Zig modules only) ──
const test_step = b.step("test", "Run unit tests");
// Executable torrent-search seam: nova2 must survive being launched by
// Zig's std.Io.Threaded child runtime. This is intentionally offline; the
// Python selftest exercises only the app-mode pool dispatcher.
const test_nova2_spawn = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("tests/nova2_spawn_test.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
}),
});
test_nova2_spawn.use_llvm = true;
test_nova2_spawn.root_module.addImport("io_global", b.createModule(.{
.root_source_file = b.path("src/core/io_global.zig"),
.target = target,
.optimize = optimize,
}));
test_step.dependOn(&b.addRunArtifact(test_nova2_spawn).step);
const test_m3u = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/m3u.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_m3u).step);
const test_playback_snapshot_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/playback_snapshot_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_playback_snapshot_pure).step);
const test_paths = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/paths.zig"),
.target = target,
.optimize = optimize,
// paths.zig uses std.c (getenv); Linux requires explicit libc.
.link_libc = true,
}),
});
test_paths.use_llvm = true;
test_step.dependOn(&b.addRunArtifact(test_paths).step);
const test_text = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/text.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_text).step);
const test_voice = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/voice_filter.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_voice).step);
const test_plugins_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/plugins_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_plugins_pure).step);
// Untrusted plugin process lifecycle: process-tree containment, output
// cap, deadline, exit status, and watchdog failure cleanup.
const test_bounded_process = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/bounded_process.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
}),
});
test_bounded_process.use_llvm = true;
test_step.dependOn(&b.addRunArtifact(test_bounded_process).step);
// Native/unsafe plugin approval hashes the deterministic complete tree and
// rejects symlinks or other special files.
const test_plugins_trust = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/plugins_trust.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_plugins_trust).step);
// Headless account auth: bcrypt hash/verify + credential validation.
const test_auth_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/auth_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_auth_pure).step);
// Web UI toggle: loopback URL construction + header tooltip states.
const test_remote_url_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/remote_url_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_remote_url_pure).step);
// Web UI access page: bind mode, port validation, token masking, password
// change rules.
const test_access_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/access_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_access_pure).step);
// Web settings API: key registry + value validation.
const test_settings_api_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/settings_api_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_settings_api_pure).step);
// Rich web player interface: action allowlist and bounded values. Keeping
// this pure means the security contract is tested without linking mpv.
const test_player_api_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/player_api_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_player_api_pure).step);
// Browser playability rules for the web UI's "Play here" destination.
const test_playback_target_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/playback_target_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_playback_target_pure).step);
// Failed-login throttling for the web auth routes.
const test_login_rate_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/login_rate_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_login_rate_pure).step);
// Fixed-memory per-client/global request budgets. The table deliberately
// fails closed under identity spray and excludes normal media polling.
const test_remote_limits_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/remote_limits_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_remote_limits_pure).step);
// First-admin bootstrap: IP/localhost Host allowlist and same-authority
// Origin policy, isolated from the socket/database implementation.
const test_setup_policy_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/setup_policy_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_setup_policy_pure).step);
// Logs view: level-tag normalization + consecutive-duplicate collapsing.
const test_logs_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/logs_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_logs_pure).step);
// Log ingestion is the single seam for mpv/curl/plugin diagnostics. Keep
// signed URLs, userinfo, bearer headers and tracker passkeys out of both
// the in-app ring and the authenticated /api/logs response.
const test_log_redact_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/log_redact_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_log_redact_pure).step);
// Sensitive scratch data: random private workspaces, exclusive owner-only
// files, traversal rejection, and recursive cleanup.
const test_secure_temp = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/secure_temp.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
}),
});
test_secure_temp.use_llvm = true;
test_step.dependOn(&b.addRunArtifact(test_secure_temp).step);
// Authenticated curl calls feed config headers over a closed stdin pipe so
// bearer/API keys never become process-list-visible argv entries.
const test_curl_secret = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/curl_secret.zig"),
.target = target,
.optimize = optimize,
.link_libc = true,
}),
});
test_curl_secret.use_llvm = true;
test_step.dependOn(&b.addRunArtifact(test_curl_secret).step);
const test_deps = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/deps_test.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_deps).step);
const test_env = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/env.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_env).step);
const test_workers = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/workers.zig"),
.target = target,
.optimize = optimize,
// workers.zig pulls std.c; Linux requires explicit libc.
.link_libc = true,
}),
});
test_workers.use_llvm = true;
test_step.dependOn(&b.addRunArtifact(test_workers).step);
const test_chrome = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/ui/chrome_autohide.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_chrome).step);
const test_resume = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/resume_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_resume).step);
// Control-bar drop-ups: anchored-above / right-aligned / clamp-to-window
// placement math + the click-outside hit test (ui/pickers.zig routes every
// popover through it).
const test_dropup_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/ui/dropup_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_dropup_pure).step);
// Input gestures: the double-tap window shared by F F (ui/input.zig) and
// double-click-to-fullscreen (ui/grid.zig).
const test_input_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/ui/input_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_input_pure).step);
// Player control bar: clock formatting, scrub geometry (pointer→fraction,
// fraction→gravity), torrent buffered-ahead analysis, seek throttle, volume
// ramp, transport state, responsive collapse.
//
// ON THE SHIPPED PATH (footer.zig calls these, so the tests cover real
// behaviour): formatTime, formatTrailing, percentToFrac, fractionAt,
// pieceMapFraction, shouldSeek, shouldPrioritize, volumeFraction,
// volumePercent.
//
// Control-bar decisions: clock formatting and label widths, scrub-band
// paint geometry, hover-chip placement, buffered-ahead range, the seek
// throttle, the volume ramp, the transport state machine, and the
// width-based collapse order. All of it is wired into footer.zig — a test
// there asserts no export goes unreachable.
const test_footer_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/ui/footer_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_footer_pure).step);
// Playback loading screen: art-URL resolution for every source (TMDB
// fragment vs. an absolute music-server cover), splitting a summary into
// rotating fact cards, which card is showing, and the meta line.
const test_loading_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/ui/loading_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_loading_pure).step);
// Installed-source table: capacity (sized in FIELDS, not sources), the
// filename-safety rule shared by install/uninstall, and the overflow
// report that must never be silent again.
const test_source_config_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/source_config_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_source_config_pure).step);
// Per-source mirror failover: candidate ordering (base first, then the
// `mirrors` list), last-good rotation, and 200-OK challenge-page detection.
// mirrors.zig routes every selection decision through these.
const test_mirrors_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/mirrors_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_mirrors_pure).step);
// Audio EQ preset → af spec, video-filter clamp, download-limit sanitize —
// the persist-and-replay mapping shared by settings.zig + player.zig init.
const test_av_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/av_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_av_pure).step);
// YouTube browse: suggestion-JSON parse, channel-URL validation, duration/
// view-count formatting — youtube.zig routes through these.
const test_youtube_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/youtube_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_youtube_pure).step);
// Winamp-style audio visualisers: the mpv lavfi-complex filter graph. Pure
// because a theme colour is spliced into an ffmpeg graph — it must be
// validated, not interpolated — and because every style has to keep
// `asplit [ao]` or the visualiser silently costs you the audio.
const test_visualizer_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/visualizer_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_visualizer_pure).step);
// Keyless subtitle providers: media-name → query/show/season/episode parse.
const test_subs_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/subtitles_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_subs_pure).step);
// Plex: restored-session section load trigger + stale-worker publish guard.
const test_plex_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/plex_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_plex_pure).step);
// Anime NSFW filter: Jikan rating classification + sfw query param.
const test_anime_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/anime_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_anime_pure).step);
// `lists` anime source plugin: anime-airing.json → anime index rows.
const test_anime_lists_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/anime_lists_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_anime_lists_pure).step);
// AniList metadata parsing (Page.media[] iterator + malformed-JSON regression).
const test_anilist_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/anilist_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_anilist_pure).step);
// Podcasts: iTunes JSON + podcast RSS episode parsing (malformed regressions).
const test_podcasts_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/podcasts_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_podcasts_pure).step);
// Internet Radio: RadioBrowser station-search JSON parsing (numeric fields +
// url_resolved/url fallback + malformed-JSON regressions).
const test_radio_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/radio_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_radio_pure).step);
// Live TV / IPTV: iptv-org streams.json parsing, m3u8 recognition, the
// NSFW/accept gate, the query filter, and the <base>/streams.json builder.
const test_iptv_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/iptv_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_iptv_pure).step);
// App-wide stream health: the probe classifier shared by Live TV and Radio
// (iptv_pure.zig re-exports these names; services/link_health.zig routes
// every probe worker through classify()).
const test_link_health_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/link_health_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_link_health_pure).step);
// YouTube InnerTube fast search: POST body building, the videoRenderer
// iterator, duration/view-count/published text parsing, the YYYYMMDD
// conversion, the thumbnail-URL builder, and the channel-row rejection
// shared with the yt-dlp line parser.
const test_youtube_innertube_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/youtube_innertube_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_youtube_innertube_pure).step);
// mpv ytdl-raw-options: the exact option string handed to mpv, incl. the
// regression guard that no YouTube player client is ever pinned again.
const test_ytdl_opts_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/ytdl_opts_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_ytdl_opts_pure).step);
// yt-dlp helper updater: exact release-asset checksum matching and strict
// staged version-probe output validation before atomic publication.
const test_ytdlp_update_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/ytdlp_update_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_ytdlp_update_pure).step);
const test_install_identity_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/core/install_identity_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_install_identity_pure).step);
// mpv per-request HTTP headers: comma-safe joining for `http-header-fields`
// and the Origin-from-Referer derivation. player.zig routes through these.
const test_http_headers_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/http_headers_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_http_headers_pure).step);
// Typed mpv load seam: replace clears persistent HTTP state; every queue
// entry receives its own UA/headers without append mutating current media.
const test_playback_load_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/playback_load_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_playback_load_pure).step);
// A media-version fallback stays armed through demux/decoder setup, is
// consumed once on a pre-playback failure, and cannot switch mid-stream.
const test_playback_fallback_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/playback_fallback_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_playback_fallback_pure).step);
// Hardware-decoder feedback waits until mpv has a real video decoder and
// distinguishes software fallback from unavailable/early property states.
const test_hwdec_feedback_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/player/hwdec_feedback_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_hwdec_feedback_pure).step);
// DPI-bypass sidecar: mode validation, the "127.0.0.1:<port>" builder, and
// the enabled&&running proxy gate. dpi_bypass.zig routes through these.
const test_proxy_url_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/proxy_url_pure.zig"),
.target = target,
.optimize = optimize,
}),
});
test_step.dependOn(&b.addRunArtifact(test_proxy_url_pure).step);
const test_dpi_bypass_pure = b.addTest(.{
.root_module = b.createModule(.{
.root_source_file = b.path("src/services/dpi_bypass_pure.zig"),